From 38bb15300e02ffd9cc90d65b700ef6727fd23970 Mon Sep 17 00:00:00 2001 From: Alexander Votteler Date: Mon, 17 Feb 2025 19:47:39 +0100 Subject: [PATCH 001/130] fix: wrong documentation for --trusted-ip (#2959) --- docs/docs/configuration/overview.md | 52 ++++++++++++++--------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 7ce5a6e3..69f218bf 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -187,32 +187,32 @@ Provider specific options can be found on their respective subpages. ### Proxy Options -| Flag / Config Field | Type | Description | Default | -| ------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | -| flag: `--api-route`
toml: `api_routes` | string \| list | return HTTP 401 instead of redirecting to authentication server if token is not valid. Format: path_regex | | -| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | -| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | -| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | -| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | -| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | -| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | -| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | -| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | -| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | -| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | -| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | -| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | -| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | -| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | -| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | -| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | -| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | -| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | -| flag: `--trusted-ip`
toml: `trusted_ips` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | return HTTP 401 instead of redirecting to authentication server if token is not valid. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | [^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. From 876feeeb3fa470eff80694992fc23548fb7949e5 Mon Sep 17 00:00:00 2001 From: Alexander Votteler Date: Tue, 18 Feb 2025 17:41:16 +0100 Subject: [PATCH 002/130] fix: wrong documentation for --trusted-ip in v7.6, v7.7, v7.8 --- .../version-7.6.x/configuration/overview.md | 52 +++++++++---------- .../version-7.7.x/configuration/overview.md | 52 +++++++++---------- .../version-7.8.x/configuration/overview.md | 52 +++++++++---------- 3 files changed, 78 insertions(+), 78 deletions(-) diff --git a/docs/versioned_docs/version-7.6.x/configuration/overview.md b/docs/versioned_docs/version-7.6.x/configuration/overview.md index 61a239c9..e43a71c4 100644 --- a/docs/versioned_docs/version-7.6.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.6.x/configuration/overview.md @@ -186,32 +186,32 @@ Provider specific options can be found on their respective subpages. ### Proxy Options -| Flag / Config Field | Type | Description | Default | -| ------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | -| flag: `--api-route`
toml: `api_routes` | string \| list | return HTTP 401 instead of redirecting to authentication server if token is not valid. Format: path_regex | | -| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | -| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | -| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | -| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | -| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | -| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | -| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | -| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | -| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, or X-ProxyUser-IP) | X-Real-IP | -| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | -| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | -| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | -| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | -| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | -| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | -| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | -| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | -| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | -| flag: `--trusted-ip`
toml: `trusted_ips` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | return HTTP 401 instead of redirecting to authentication server if token is not valid. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, or X-ProxyUser-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | [^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. diff --git a/docs/versioned_docs/version-7.7.x/configuration/overview.md b/docs/versioned_docs/version-7.7.x/configuration/overview.md index d470f40f..d43e86ce 100644 --- a/docs/versioned_docs/version-7.7.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.7.x/configuration/overview.md @@ -186,32 +186,32 @@ Provider specific options can be found on their respective subpages. ### Proxy Options -| Flag / Config Field | Type | Description | Default | -| ------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | -| flag: `--api-route`
toml: `api_routes` | string \| list | return HTTP 401 instead of redirecting to authentication server if token is not valid. Format: path_regex | | -| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | -| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | -| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | -| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | -| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | -| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | -| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | -| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | -| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, or X-ProxyUser-IP) | X-Real-IP | -| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | -| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | -| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | -| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | -| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | -| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | -| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | -| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | -| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | -| flag: `--trusted-ip`
toml: `trusted_ips` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | return HTTP 401 instead of redirecting to authentication server if token is not valid. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, or X-ProxyUser-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | [^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. diff --git a/docs/versioned_docs/version-7.8.x/configuration/overview.md b/docs/versioned_docs/version-7.8.x/configuration/overview.md index 7ce5a6e3..69f218bf 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.8.x/configuration/overview.md @@ -187,32 +187,32 @@ Provider specific options can be found on their respective subpages. ### Proxy Options -| Flag / Config Field | Type | Description | Default | -| ------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | -| flag: `--api-route`
toml: `api_routes` | string \| list | return HTTP 401 instead of redirecting to authentication server if token is not valid. Format: path_regex | | -| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | -| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | -| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | -| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | -| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | -| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | -| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | -| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | -| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | -| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | -| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | -| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | -| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | -| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | -| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | -| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | -| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | -| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | -| flag: `--trusted-ip`
toml: `trusted_ips` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | return HTTP 401 instead of redirecting to authentication server if token is not valid. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | [^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. From a393ea3ca053427d2d1a7759e4fc8130478939f7 Mon Sep 17 00:00:00 2001 From: Matthias Penner Date: Mon, 10 Feb 2025 18:28:57 +0000 Subject: [PATCH 003/130] pkg/cookies: use 'Max-Age' instead of 'Expires' for cookie expiration --- CHANGELOG.md | 1 + pkg/cookies/cookies.go | 8 ++++--- pkg/cookies/cookies_suite_test.go | 7 ------ pkg/cookies/cookies_test.go | 29 +++++++++++++++++++---- pkg/cookies/csrf.go | 2 -- pkg/cookies/csrf_per_request_test.go | 7 +++--- pkg/cookies/csrf_test.go | 7 +++--- pkg/sessions/cookie/session_store.go | 7 +++--- pkg/sessions/persistence/ticket.go | 2 -- pkg/sessions/tests/session_store_tests.go | 2 +- 10 files changed, 40 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb53e319..f1398152 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.8.1 - [#2927](https://github.com/oauth2-proxy/oauth2-proxy/pull/2927) chore(deps/build): bump golang to 1.23 and use go.mod as single point of truth for all build files (@tuunit) +- [#2697](https://github.com/oauth2-proxy/oauth2-proxy/pull/2697) Use `Max-Age` instead of `Expires` for cookie expiration (@matpen-wi) # V7.8.1 diff --git a/pkg/cookies/cookies.go b/pkg/cookies/cookies.go index 1e017366..24ae2841 100644 --- a/pkg/cookies/cookies.go +++ b/pkg/cookies/cookies.go @@ -14,7 +14,7 @@ import ( // MakeCookieFromOptions constructs a cookie based on the given *options.CookieOptions, // value and creation time -func MakeCookieFromOptions(req *http.Request, name string, value string, opts *options.Cookie, expiration time.Duration, now time.Time) *http.Cookie { +func MakeCookieFromOptions(req *http.Request, name string, value string, opts *options.Cookie, expiration time.Duration) *http.Cookie { domain := GetCookieDomain(req, opts.Domains) // If nothing matches, create the cookie with the shortest domain if domain == "" && len(opts.Domains) > 0 { @@ -35,8 +35,10 @@ func MakeCookieFromOptions(req *http.Request, name string, value string, opts *o SameSite: ParseSameSite(opts.SameSite), } - if expiration != time.Duration(0) { - c.Expires = now.Add(expiration) + if expiration > time.Duration(0) { + c.MaxAge = int(expiration.Seconds()) + } else if expiration < time.Duration(0) { + c.MaxAge = -1 } warnInvalidDomain(c, req) diff --git a/pkg/cookies/cookies_suite_test.go b/pkg/cookies/cookies_suite_test.go index 1e2e6f9c..f4893cbd 100644 --- a/pkg/cookies/cookies_suite_test.go +++ b/pkg/cookies/cookies_suite_test.go @@ -1,9 +1,7 @@ package cookies import ( - "net/http" "testing" - "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" . "github.com/onsi/ginkgo/v2" @@ -28,8 +26,3 @@ func TestProviderSuite(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Cookies") } - -func testCookieExpires(exp time.Time) string { - var buf [len(http.TimeFormat)]byte - return string(exp.UTC().AppendFormat(buf[:0], http.TimeFormat)) -} diff --git a/pkg/cookies/cookies_test.go b/pkg/cookies/cookies_test.go index 31b155a9..ef0fbd4f 100644 --- a/pkg/cookies/cookies_test.go +++ b/pkg/cookies/cookies_test.go @@ -87,7 +87,7 @@ var _ = Describe("Cookie Tests", func() { opts options.Cookie expiration time.Duration now time.Time - expectedOutput time.Time + expectedOutput int } validName := "_oauth2_proxy" @@ -95,7 +95,7 @@ var _ = Describe("Cookie Tests", func() { domains := []string{"www.cookies.test"} now := time.Now() - var expectedExpires time.Time + var expectedMaxAge int DescribeTable("should return cookies with or without expiration", func(in makeCookieFromOptionsTableInput) { @@ -106,7 +106,7 @@ var _ = Describe("Cookie Tests", func() { ) Expect(err).ToNot(HaveOccurred()) - Expect(MakeCookieFromOptions(req, in.name, in.value, &in.opts, in.expiration, in.now).Expires).To(Equal(in.expectedOutput)) + Expect(MakeCookieFromOptions(req, in.name, in.value, &in.opts, in.expiration).MaxAge).To(Equal(in.expectedOutput)) }, Entry("persistent cookie", makeCookieFromOptionsTableInput{ host: "www.cookies.test", @@ -125,7 +125,26 @@ var _ = Describe("Cookie Tests", func() { }, expiration: 15 * time.Minute, now: now, - expectedOutput: now.Add(15 * time.Minute), + expectedOutput: int((15 * time.Minute).Seconds()), + }), + Entry("persistent cookie to be cleared", makeCookieFromOptionsTableInput{ + host: "www.cookies.test", + name: validName, + value: "1", + opts: options.Cookie{ + Name: validName, + Secret: validSecret, + Domains: domains, + Path: "", + Expire: time.Hour * -1, + Refresh: 15 * time.Minute, + Secure: true, + HTTPOnly: false, + SameSite: "", + }, + expiration: time.Hour * -1, + now: now, + expectedOutput: -1, }), Entry("session cookie", makeCookieFromOptionsTableInput{ host: "www.cookies.test", @@ -144,7 +163,7 @@ var _ = Describe("Cookie Tests", func() { }, expiration: 0, now: now, - expectedOutput: expectedExpires, + expectedOutput: expectedMaxAge, }), ) }) diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go index b1f95763..698a7c8d 100644 --- a/pkg/cookies/csrf.go +++ b/pkg/cookies/csrf.go @@ -145,7 +145,6 @@ func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cooki encoded, c.cookieOpts, c.cookieOpts.CSRFExpire, - c.time.Now(), ) http.SetCookie(rw, cookie) @@ -160,7 +159,6 @@ func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) { "", c.cookieOpts, time.Hour*-1, - c.time.Now(), )) } diff --git a/pkg/cookies/csrf_per_request_test.go b/pkg/cookies/csrf_per_request_test.go index 79d633bb..28e2e296 100644 --- a/pkg/cookies/csrf_per_request_test.go +++ b/pkg/cookies/csrf_per_request_test.go @@ -159,10 +159,10 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { )) Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring( fmt.Sprintf( - "; Path=%s; Domain=%s; Expires=%s; HttpOnly; Secure", + "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure", cookiePath, cookieDomain, - testCookieExpires(testNow.Add(cookieOpts.CSRFExpire)), + int(cookieOpts.CSRFExpire.Seconds()), ), )) }) @@ -176,11 +176,10 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { Expect(rw.Header().Get("Set-Cookie")).To(Equal( fmt.Sprintf( - "%s=; Path=%s; Domain=%s; Expires=%s; HttpOnly; Secure", + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure", privateCSRF.cookieName(), cookiePath, cookieDomain, - testCookieExpires(testNow.Add(time.Hour*-1)), ), )) }) diff --git a/pkg/cookies/csrf_test.go b/pkg/cookies/csrf_test.go index 8b22e408..37527bd0 100644 --- a/pkg/cookies/csrf_test.go +++ b/pkg/cookies/csrf_test.go @@ -161,10 +161,10 @@ var _ = Describe("CSRF Cookie Tests", func() { )) Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring( fmt.Sprintf( - "; Path=%s; Domain=%s; Expires=%s; HttpOnly; Secure", + "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure", cookiePath, cookieDomain, - testCookieExpires(testNow.Add(cookieOpts.CSRFExpire)), + int(cookieOpts.CSRFExpire.Seconds()), ), )) }) @@ -239,11 +239,10 @@ var _ = Describe("CSRF Cookie Tests", func() { Expect(rw.Header().Get("Set-Cookie")).To(Equal( fmt.Sprintf( - "%s=; Path=%s; Domain=%s; Expires=%s; HttpOnly; Secure", + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure", privateCSRF.cookieName(), cookiePath, cookieDomain, - testCookieExpires(testNow.Add(time.Hour*-1)), ), )) }) diff --git a/pkg/sessions/cookie/session_store.go b/pkg/sessions/cookie/session_store.go index f2f4045f..3947177f 100644 --- a/pkg/sessions/cookie/session_store.go +++ b/pkg/sessions/cookie/session_store.go @@ -74,7 +74,7 @@ func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error { for _, c := range req.Cookies() { if cookieNameRegex.MatchString(c.Name) { - clearCookie := s.makeCookie(req, c.Name, "", time.Hour*-1, time.Now()) + clearCookie := s.makeCookie(req, c.Name, "", time.Hour*-1) http.SetCookie(rw, clearCookie) } @@ -126,21 +126,20 @@ func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now ti return nil, err } } - c := s.makeCookie(req, s.Cookie.Name, strValue, s.Cookie.Expire, now) + c := s.makeCookie(req, s.Cookie.Name, strValue, s.Cookie.Expire) if len(c.String()) > maxCookieLength { return splitCookie(c), nil } return []*http.Cookie{c}, nil } -func (s *SessionStore) makeCookie(req *http.Request, name string, value string, expiration time.Duration, now time.Time) *http.Cookie { +func (s *SessionStore) makeCookie(req *http.Request, name string, value string, expiration time.Duration) *http.Cookie { return pkgcookies.MakeCookieFromOptions( req, name, value, s.Cookie, expiration, - now, ) } diff --git a/pkg/sessions/persistence/ticket.go b/pkg/sessions/persistence/ticket.go index 5020ada9..581a7f45 100644 --- a/pkg/sessions/persistence/ticket.go +++ b/pkg/sessions/persistence/ticket.go @@ -223,7 +223,6 @@ func (t *ticket) clearCookie(rw http.ResponseWriter, req *http.Request) { "", t.options, time.Hour*-1, - time.Now(), )) } @@ -242,7 +241,6 @@ func (t *ticket) makeCookie(req *http.Request, value string, expires time.Durati value, t.options, expires, - now, ), nil } diff --git a/pkg/sessions/tests/session_store_tests.go b/pkg/sessions/tests/session_store_tests.go index 8e2d02f9..a4818ef2 100644 --- a/pkg/sessions/tests/session_store_tests.go +++ b/pkg/sessions/tests/session_store_tests.go @@ -385,7 +385,7 @@ func SessionStoreInterfaceTests(in *testInput) { broken := "BrokenSessionFromADifferentSessionImplementation" value, err := encryption.SignedValue(in.cookieOpts.Secret, in.cookieOpts.Name, []byte(broken), time.Now()) Expect(err).ToNot(HaveOccurred()) - cookie := cookiesapi.MakeCookieFromOptions(in.request, in.cookieOpts.Name, value, in.cookieOpts, in.cookieOpts.Expire, time.Now()) + cookie := cookiesapi.MakeCookieFromOptions(in.request, in.cookieOpts.Name, value, in.cookieOpts, in.cookieOpts.Expire) in.request.AddCookie(cookie) err = in.ss().Save(in.response, in.request, in.session) From cc87465e9b6c8d29476764c3797358d1dacd7331 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Tue, 25 Feb 2025 08:50:43 +1100 Subject: [PATCH 004/130] Update golang.org/x/oauth2 to v0.27.0. This addresses CVE-2025-22868 (https://go.dev/issue/71490). --- CHANGELOG.md | 1 + go.mod | 2 +- go.sum | 23 ++++++----------------- 3 files changed, 8 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f1398152..9178b233 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#2927](https://github.com/oauth2-proxy/oauth2-proxy/pull/2927) chore(deps/build): bump golang to 1.23 and use go.mod as single point of truth for all build files (@tuunit) - [#2697](https://github.com/oauth2-proxy/oauth2-proxy/pull/2697) Use `Max-Age` instead of `Expires` for cookie expiration (@matpen-wi) +- [#2969](https://github.com/oauth2-proxy/oauth2-proxy/pull/2969) Update golang.org/x/oauth2 to v0.27.0 to address CVE-2025-22868 (@dsymonds) # V7.8.1 diff --git a/go.mod b/go.mod index d7c2bb0a..f163f8f6 100644 --- a/go.mod +++ b/go.mod @@ -37,7 +37,7 @@ require ( golang.org/x/crypto v0.32.0 golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c golang.org/x/net v0.34.0 - golang.org/x/oauth2 v0.25.0 + golang.org/x/oauth2 v0.27.0 golang.org/x/sync v0.10.0 google.golang.org/api v0.219.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 diff --git a/go.sum b/go.sum index fe081fa1..0bae8ef3 100644 --- a/go.sum +++ b/go.sum @@ -179,7 +179,6 @@ github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs= github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4= github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y= github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= @@ -213,10 +212,10 @@ go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ= go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE= -go.opentelemetry.io/otel/sdk v1.31.0 h1:xLY3abVHYZ5HSfOg3l2E5LUj2Cwva5Y7yGxnSW9H5Gk= -go.opentelemetry.io/otel/sdk v1.31.0/go.mod h1:TfRbMdhvxIIr/B2N2LQW2S5v9m3gOQ/08KsbbO5BPT0= -go.opentelemetry.io/otel/sdk/metric v1.31.0 h1:i9hxxLJF/9kkvfHppyLL55aW7iIJz4JjxTeYusH7zMc= -go.opentelemetry.io/otel/sdk/metric v1.31.0/go.mod h1:CRInTMVvNhUKgSAMbKyTMxqOBC0zgyxzW55lZzX43Y8= +go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4= +go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU= +go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU= +go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ= go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -228,8 +227,6 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= -golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 h1:yqrTHse8TCMW1M1ZCP+VAR/l0kKxwaAIqN/il7x4voA= -golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c h1:KL/ZBHXgKGVmuZBZ01Lt57yE5ws8ZPSkkihmEyq7FXc= golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -250,8 +247,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= -golang.org/x/oauth2 v0.25.0 h1:CY4y7XT9v0cRI9oupztF8AgiIu99L/ksR/Xp/6jrZ70= -golang.org/x/oauth2 v0.25.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= +golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= +golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -307,19 +304,13 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.217.0 h1:GYrUtD289o4zl1AhiTZL0jvQGa2RDLyC+kX1N/lfGOU= -google.golang.org/api v0.217.0/go.mod h1:qMc2E8cBAbQlRypBTBWHklNJlaZZJBwDv81B1Iu8oSI= google.golang.org/api v0.219.0 h1:nnKIvxKs/06jWawp2liznTBnMRQBEPpGo7I+oEypTX0= google.golang.org/api v0.219.0/go.mod h1:K6OmjGm+NtLrIkHxv1U3a0qIf/0JOvAHd5O/6AoyKYE= google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 h1:ToEetK57OidYuqD4Q5w+vfEnPvPpuTwedCNVohYJfNk= google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576 h1:CkkIfIt50+lT6NHAVoRYEyAvQGFM7xEwXUUywFvEb3Q= google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576/go.mod h1:1R3kvZ1dtP3+4p4d3G8uJ8rFk/fWlScl38vanWACI08= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f h1:OxYkA3wjPsZyBylwymxSHa7ViiW1Sml4ToBrncvFehI= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50= google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47 h1:91mG8dNTpkC0uChJUQ9zCiRqx3GEEFOWaRZ0mI6Oj2I= google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50= -google.golang.org/grpc v1.69.4 h1:MF5TftSMkd8GLw/m0KM6V8CMOCY6NZ1NQDPGFgbTt4A= -google.golang.org/grpc v1.69.4/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4= google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ= google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= @@ -328,8 +319,6 @@ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.36.3 h1:82DV7MYdb8anAVi3qge1wSnMDrnKK7ebr+I0hHRN1BU= -google.golang.org/protobuf v1.36.3/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= google.golang.org/protobuf v1.36.4 h1:6A3ZDJHn/eNqc1i+IdefRzy/9PokBTPvcqMySR7NNIM= google.golang.org/protobuf v1.36.4/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From 8a36a6622d4e395dc22a802f788bd6bcca61d901 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Wed, 5 Mar 2025 08:11:38 +1100 Subject: [PATCH 005/130] Update golang.org/x/net to v0.36.0. This addresses CVE-2025-22870 (https://go.dev/issue/71984). --- CHANGELOG.md | 1 + go.mod | 10 +++++----- go.sum | 20 ++++++++++---------- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9178b233..9802a14d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#2927](https://github.com/oauth2-proxy/oauth2-proxy/pull/2927) chore(deps/build): bump golang to 1.23 and use go.mod as single point of truth for all build files (@tuunit) - [#2697](https://github.com/oauth2-proxy/oauth2-proxy/pull/2697) Use `Max-Age` instead of `Expires` for cookie expiration (@matpen-wi) - [#2969](https://github.com/oauth2-proxy/oauth2-proxy/pull/2969) Update golang.org/x/oauth2 to v0.27.0 to address CVE-2025-22868 (@dsymonds) +- [#2977](https://github.com/oauth2-proxy/oauth2-proxy/pull/2977) Update golang.org/x/net to v0.36.0 to address CVE-2025-22870 (@dsymonds) # V7.8.1 diff --git a/go.mod b/go.mod index f163f8f6..33796df7 100644 --- a/go.mod +++ b/go.mod @@ -34,11 +34,11 @@ require ( github.com/spf13/viper v1.19.0 github.com/stretchr/testify v1.10.0 github.com/vmihailenco/msgpack/v5 v5.4.1 - golang.org/x/crypto v0.32.0 + golang.org/x/crypto v0.35.0 golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c - golang.org/x/net v0.34.0 + golang.org/x/net v0.36.0 golang.org/x/oauth2 v0.27.0 - golang.org/x/sync v0.10.0 + golang.org/x/sync v0.11.0 google.golang.org/api v0.219.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 k8s.io/apimachinery v0.32.1 @@ -87,8 +87,8 @@ require ( go.opentelemetry.io/otel/metric v1.34.0 // indirect go.opentelemetry.io/otel/trace v1.34.0 // indirect go.uber.org/multierr v1.11.0 // indirect - golang.org/x/sys v0.29.0 // indirect - golang.org/x/text v0.21.0 // indirect + golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.22.0 // indirect golang.org/x/tools v0.29.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47 // indirect google.golang.org/grpc v1.70.0 // indirect diff --git a/go.sum b/go.sum index 0bae8ef3..1e8e308c 100644 --- a/go.sum +++ b/go.sum @@ -225,8 +225,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= -golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= +golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs= +golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ= golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c h1:KL/ZBHXgKGVmuZBZ01Lt57yE5ws8ZPSkkihmEyq7FXc= golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -245,8 +245,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= -golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= +golang.org/x/net v0.36.0 h1:vWF2fRbw4qslQsQzgFqZff+BItCvGFQqKzKIzx1rmoA= +golang.org/x/net v0.36.0/go.mod h1:bFmbeoIPfrw4sMHNhb4J9f6+tPziuGjq7Jk/38fxi1I= golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -255,8 +255,8 @@ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -275,8 +275,8 @@ golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= -golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -288,8 +288,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= From ee7d79c5d94172b242b3a0ac1d13586697eb48e6 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 5 Mar 2025 09:31:19 +0000 Subject: [PATCH 006/130] chore(deps): update module github.com/go-jose/go-jose/v3 to v3.0.4 [security] --- go.mod | 2 +- go.sum | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 33796df7..6447a199 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,7 @@ require ( github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.8.0 github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 - github.com/go-jose/go-jose/v3 v3.0.3 + github.com/go-jose/go-jose/v3 v3.0.4 github.com/golang-jwt/jwt/v5 v5.2.1 github.com/google/go-cmp v0.6.0 github.com/google/uuid v1.6.0 diff --git a/go.sum b/go.sum index 1e8e308c..584d2fa4 100644 --- a/go.sum +++ b/go.sum @@ -60,6 +60,8 @@ github.com/go-git/go-git/v5 v5.4.2 h1:BXyZu9t0VkbiHtqrsvdq39UDhGJTl1h55VW6CSC4aY github.com/go-git/go-git/v5 v5.4.2/go.mod h1:gQ1kArt6d+n+BGd+/B/I74HwRTLhth2+zti4ihgckDc= github.com/go-jose/go-jose/v3 v3.0.3 h1:fFKWeig/irsp7XD2zBxvnmA/XaRWp5V3CBsZXJF7G7k= github.com/go-jose/go-jose/v3 v3.0.3/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= +github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= +github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v4 v4.0.4 h1:VsjPI33J0SB9vQM6PLmNjoHqMQNGPiZ0rHL7Ni7Q6/E= github.com/go-jose/go-jose/v4 v4.0.4/go.mod h1:NKb5HO1EZccyMpiZNbdUw/14tiXNyUJh188dfnMCAfc= github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= From 33e7c052dc0ecf2c911cc28936a320c9b88e89e7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 12 Mar 2025 07:46:30 +0000 Subject: [PATCH 007/130] chore(deps): update alpine docker tag to v3.21.3 --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index f1fe8bc7..280ac6c6 100644 --- a/Makefile +++ b/Makefile @@ -55,7 +55,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM} DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x -DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.21.2 +DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.21.3 DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS} DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push From 67c1cd6ee7989d8e762e371feaa7740a0d7f6711 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 12 Mar 2025 07:52:38 +0000 Subject: [PATCH 008/130] chore(deps): update dependency golangci/golangci-lint to v1.64.7 --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4ea61159..7c9f2a29 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v1.63.4 + GOLANGCI_LINT_VERSION: v1.64.7 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index ce29e179..4d65ce65 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v1.63.4 + GOLANGCI_LINT_VERSION: v1.64.7 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter From 9ac8f4b5de134b850c1b9027ed038dc3109d9bc3 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 12 Mar 2025 07:56:26 +0000 Subject: [PATCH 009/130] chore(deps): update docker-compose --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 4 ++-- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index ce3ae517..7e1480a5 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -42,7 +42,7 @@ services: - httpbin.localtest.me gitea: - image: gitea/gitea:1.23.1 + image: gitea/gitea:1.23.5 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 9e3f16e2..a9c79ec9 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -55,7 +55,7 @@ services: httpbin: {} dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.41.1 + image: ghcr.io/dexidp/dex:v2.42.0 command: dex serve /dex.yaml hostname: dex volumes: @@ -81,7 +81,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.5.17 + image: gcr.io/etcd-development/etcd:v3.5.19 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index c3ccf1c2..531267d0 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.18 + image: traefik:v2.11.21 volumes: - "./traefik:/etc/traefik" ports: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 9f551812..6b428e57 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -29,7 +29,7 @@ services: - httpbin dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.41.1 + image: ghcr.io/dexidp/dex:v2.42.0 command: dex serve /dex.yaml hostname: dex volumes: @@ -55,7 +55,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.5.17 + image: gcr.io/etcd-development/etcd:v3.5.19 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From 8a8fcab5809a01c5c75dfe999a9f0d7b66cab97b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olivier=20Mengu=C3=A9?= Date: Tue, 11 Mar 2025 11:23:49 +0100 Subject: [PATCH 010/130] deps: remove tools/reference-gen from go.mod Remove github.com/oauth2-proxy/tools/reference-gen from dependencies. Instead we are now running it with "go run" with a version suffix. Long version: - github.com/oauth2-proxy/tools/reference-gen is removed from tools/tool/go - in pkg/apis/options/doc.go we now run reference-run with a version suffix (go run package@version) with the version comming from go.mod. - the "//go:generate" line is split in 2 lines (using the -command flag) for readability - "go mod tidy" for cleaning dependencies from go.mod, go.sum Note: we are not upgrading reference-gen here. That will be a further separate change. --- CHANGELOG.md | 1 + go.mod | 5 --- go.sum | 87 ----------------------------------------- pkg/apis/options/doc.go | 3 +- tools/tools.go | 7 ---- 5 files changed, 3 insertions(+), 100 deletions(-) delete mode 100644 tools/tools.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 9802a14d..db8b5728 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - [#2697](https://github.com/oauth2-proxy/oauth2-proxy/pull/2697) Use `Max-Age` instead of `Expires` for cookie expiration (@matpen-wi) - [#2969](https://github.com/oauth2-proxy/oauth2-proxy/pull/2969) Update golang.org/x/oauth2 to v0.27.0 to address CVE-2025-22868 (@dsymonds) - [#2977](https://github.com/oauth2-proxy/oauth2-proxy/pull/2977) Update golang.org/x/net to v0.36.0 to address CVE-2025-22870 (@dsymonds) +- [#2982](https://github.com/oauth2-proxy/oauth2-proxy/pull/2982) chore(deps): remove go:generate tool from go.mod # V7.8.1 diff --git a/go.mod b/go.mod index 6447a199..d309f9a3 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,6 @@ require ( github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa github.com/mitchellh/mapstructure v1.5.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/oauth2-proxy/tools/reference-gen v0.0.0-20220223111546-d3b50d1a591a github.com/onsi/ginkgo/v2 v2.22.2 github.com/onsi/gomega v1.36.2 github.com/pierrec/lz4/v4 v4.1.22 @@ -67,8 +66,6 @@ require ( github.com/kylelemons/godebug v1.1.0 // indirect github.com/magiconair/properties v1.8.9 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/nxadm/tail v1.4.11 // indirect - github.com/onsi/ginkgo v1.16.5 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.1 // indirect @@ -96,6 +93,4 @@ require ( gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - k8s.io/gengo v0.0.0-20240404160639-a0386bf69313 // indirect - k8s.io/klog/v2 v2.130.1 // indirect ) diff --git a/go.sum b/go.sum index 584d2fa4..1c66057a 100644 --- a/go.sum +++ b/go.sum @@ -49,50 +49,32 @@ github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2 github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= -github.com/go-git/go-git/v5 v5.4.2 h1:BXyZu9t0VkbiHtqrsvdq39UDhGJTl1h55VW6CSC4aY4= -github.com/go-git/go-git/v5 v5.4.2/go.mod h1:gQ1kArt6d+n+BGd+/B/I74HwRTLhth2+zti4ihgckDc= github.com/go-jose/go-jose/v3 v3.0.3 h1:fFKWeig/irsp7XD2zBxvnmA/XaRWp5V3CBsZXJF7G7k= github.com/go-jose/go-jose/v3 v3.0.3/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v4 v4.0.4 h1:VsjPI33J0SB9vQM6PLmNjoHqMQNGPiZ0rHL7Ni7Q6/E= github.com/go-jose/go-jose/v4 v4.0.4/go.mod h1:NKb5HO1EZccyMpiZNbdUw/14tiXNyUJh188dfnMCAfc= -github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY= github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad h1:a6HEuzUHeKH6hwfN/ZoQgRgVIWFJljSWa/zetS2WTvg= github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= @@ -108,16 +90,12 @@ github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo= github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA= github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= @@ -132,22 +110,10 @@ github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyua github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= -github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY= -github.com/nxadm/tail v1.4.11/go.mod h1:OTaG3NK980DZzxbRq6lEuzgU+mug70nY11sMd4JXXHc= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/oauth2-proxy/tools/reference-gen v0.0.0-20220223111546-d3b50d1a591a h1:2RkJiJXdto2/qHaM7mTUKSR8yxImz0zei8LW0bcbav0= -github.com/oauth2-proxy/tools/reference-gen v0.0.0-20220223111546-d3b50d1a591a/go.mod h1:J9TATNVXZX2MAsXx9J35weO47Fp3FQtx+f48AHLFAug= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= -github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/ginkgo/v2 v2.22.2 h1:/3X8Panh8/WwhU/3Ssa6rCKqPLuAkVY2I0RoyDLySlU= github.com/onsi/ginkgo/v2 v2.22.2/go.mod h1:oeMosUL+8LtarXBHu/c0bx2D/K9zyQ6uX3cTyztHwsk= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8= github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY= github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= @@ -173,21 +139,17 @@ github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsF github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k= github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= -github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs= github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4= github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y= github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= @@ -197,8 +159,6 @@ github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IU github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ= github.com/yuin/gopher-lua v0.0.0-20191213034115-f46add6fdb5c/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ= @@ -223,26 +183,15 @@ go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs= golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ= golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c h1:KL/ZBHXgKGVmuZBZ01Lt57yE5ws8ZPSkkihmEyq7FXc= golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= -golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= @@ -251,29 +200,17 @@ golang.org/x/net v0.36.0 h1:vWF2fRbw4qslQsQzgFqZff+BItCvGFQqKzKIzx1rmoA= golang.org/x/net v0.36.0/go.mod h1:bFmbeoIPfrw4sMHNhb4J9f6+tPziuGjq7Jk/38fxi1I= golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= @@ -296,16 +233,11 @@ golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200505023115-26f46d2f7ef8/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.29.0 h1:Xx0h3TtM9rzQpQuR4dKLrdglAmCEN5Oi+P74JdhdzXE= golang.org/x/tools v0.29.0/go.mod h1:KMQVMRsVxU6nHCFXrBPhDB8XncLNLM0lIy/F14RP588= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.219.0 h1:nnKIvxKs/06jWawp2liznTBnMRQBEPpGo7I+oEypTX0= google.golang.org/api v0.219.0/go.mod h1:K6OmjGm+NtLrIkHxv1U3a0qIf/0JOvAHd5O/6AoyKYE= google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 h1:ToEetK57OidYuqD4Q5w+vfEnPvPpuTwedCNVohYJfNk= @@ -315,29 +247,16 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47 h1: google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50= google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ= google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.36.4 h1:6A3ZDJHn/eNqc1i+IdefRzy/9PokBTPvcqMySR7NNIM= google.golang.org/protobuf v1.36.4/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= @@ -345,9 +264,3 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= k8s.io/apimachinery v0.32.1 h1:683ENpaCBjma4CYqsmZyhEzrGz6cjn1MY/X2jB2hkZs= k8s.io/apimachinery v0.32.1/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= -k8s.io/gengo v0.0.0-20240404160639-a0386bf69313 h1:wBIDZID8ju9pwOiLlV22YYKjFGtiNSWgHf5CnKLRUuM= -k8s.io/gengo v0.0.0-20240404160639-a0386bf69313/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= -k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= -k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= -k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= -sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= diff --git a/pkg/apis/options/doc.go b/pkg/apis/options/doc.go index 8209369a..8ef112dd 100644 --- a/pkg/apis/options/doc.go +++ b/pkg/apis/options/doc.go @@ -1,2 +1,3 @@ -//go:generate go run github.com/oauth2-proxy/tools/reference-gen/cmd/reference-gen --package github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options --types AlphaOptions --header-file ../../../docs/docs/configuration/alpha_config.md.tmpl --out-file ../../../docs/docs/configuration/alpha_config.md +//go:generate -command reference-gen go run github.com/oauth2-proxy/tools/reference-gen/cmd/reference-gen@v0.0.0-20220223111546-d3b50d1a591a +//go:generate reference-gen --package github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options --types AlphaOptions --header-file ../../../docs/docs/configuration/alpha_config.md.tmpl --out-file ../../../docs/docs/configuration/alpha_config.md package options diff --git a/tools/tools.go b/tools/tools.go deleted file mode 100644 index 28f266ad..00000000 --- a/tools/tools.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build tools - -package tools - -import ( - _ "github.com/oauth2-proxy/tools/reference-gen/cmd/reference-gen" -) From ef5168549137628a5480895495ad65a5f0b47623 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 18 Mar 2025 23:37:55 +0000 Subject: [PATCH 011/130] chore(deps): update dependency @easyops-cn/docusaurus-search-local to ^0.49.0 --- docs/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/package.json b/docs/package.json index d4adeb1d..17fa4352 100644 --- a/docs/package.json +++ b/docs/package.json @@ -17,7 +17,7 @@ "@docusaurus/core": "^3.3.2", "@docusaurus/preset-classic": "^3.3.2", "@docusaurus/theme-mermaid": "^3.3.2", - "@easyops-cn/docusaurus-search-local": "^0.48.0", + "@easyops-cn/docusaurus-search-local": "^0.49.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.0.0", "prism-react-renderer": "^2.3.0", From 4e2100a2879ef06aea1411790327019c1a09217c Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 19 Mar 2025 22:19:40 +0100 Subject: [PATCH 012/130] chore(deps): update gomod (#2952) * chore(deps): update gomod Co-authored-by: Jan Larwig --- go.mod | 49 +++++++++++------------ go.sum | 121 +++++++++++++++++++++++++++++---------------------------- 2 files changed, 86 insertions(+), 84 deletions(-) diff --git a/go.mod b/go.mod index d309f9a3..03b0f1f3 100644 --- a/go.mod +++ b/go.mod @@ -10,41 +10,41 @@ require ( github.com/benbjohnson/clock v1.3.5 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 - github.com/coreos/go-oidc/v3 v3.12.0 + github.com/coreos/go-oidc/v3 v3.13.0 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.8.0 github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/go-jose/go-jose/v3 v3.0.4 github.com/golang-jwt/jwt/v5 v5.2.1 - github.com/google/go-cmp v0.6.0 + github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa github.com/mitchellh/mapstructure v1.5.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.22.2 + github.com/onsi/ginkgo/v2 v2.23.1 github.com/onsi/gomega v1.36.2 github.com/pierrec/lz4/v4 v4.1.22 - github.com/prometheus/client_golang v1.20.5 - github.com/redis/go-redis/v9 v9.7.0 + github.com/prometheus/client_golang v1.21.1 + github.com/redis/go-redis/v9 v9.7.1 github.com/spf13/cast v1.7.1 github.com/spf13/pflag v1.0.6 github.com/spf13/viper v1.19.0 github.com/stretchr/testify v1.10.0 github.com/vmihailenco/msgpack/v5 v5.4.1 - golang.org/x/crypto v0.35.0 - golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c - golang.org/x/net v0.36.0 - golang.org/x/oauth2 v0.27.0 - golang.org/x/sync v0.11.0 - google.golang.org/api v0.219.0 + golang.org/x/crypto v0.36.0 + golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 + golang.org/x/net v0.37.0 + golang.org/x/oauth2 v0.28.0 + golang.org/x/sync v0.12.0 + google.golang.org/api v0.226.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - k8s.io/apimachinery v0.32.1 + k8s.io/apimachinery v0.32.3 ) require ( - cloud.google.com/go/auth v0.14.0 // indirect + cloud.google.com/go/auth v0.15.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.7 // indirect github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 // indirect github.com/beorn7/perks v1.0.1 // indirect @@ -53,18 +53,18 @@ require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/go-jose/go-jose/v4 v4.0.4 // indirect + github.com/go-jose/go-jose/v4 v4.0.5 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect github.com/google/s2a-go v0.1.9 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.5 // indirect github.com/googleapis/gax-go/v2 v2.14.1 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/klauspost/compress v1.17.11 // indirect github.com/kylelemons/godebug v1.1.0 // indirect - github.com/magiconair/properties v1.8.9 // indirect + github.com/magiconair/properties v1.8.7 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect @@ -79,17 +79,18 @@ require ( github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 // indirect go.opentelemetry.io/otel v1.34.0 // indirect go.opentelemetry.io/otel/metric v1.34.0 // indirect go.opentelemetry.io/otel/trace v1.34.0 // indirect - go.uber.org/multierr v1.11.0 // indirect - golang.org/x/sys v0.30.0 // indirect - golang.org/x/text v0.22.0 // indirect - golang.org/x/tools v0.29.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47 // indirect - google.golang.org/grpc v1.70.0 // indirect - google.golang.org/protobuf v1.36.4 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.9.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect + golang.org/x/tools v0.31.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb // indirect + google.golang.org/grpc v1.71.0 // indirect + google.golang.org/protobuf v1.36.5 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index 1c66057a..85b4d444 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -cloud.google.com/go/auth v0.14.0 h1:A5C4dKV/Spdvxcl0ggWwWEzzP7AZMJSEIgrkngwhGYM= -cloud.google.com/go/auth v0.14.0/go.mod h1:CYsoRL1PdiDuqeQpZE0bP2pnPrGqFcOkI0nldEQis+A= +cloud.google.com/go/auth v0.15.0 h1:Ly0u4aA5vG/fsSsxu98qCQBemXtAtJf+95z9HK+cxps= +cloud.google.com/go/auth v0.15.0/go.mod h1:WJDGqZ1o9E9wKIL+IwStfyn/+s59zl4Bi+1KQNVXLZ8= cloud.google.com/go/auth/oauth2adapt v0.2.7 h1:/Lc7xODdqcEw8IrZ9SvwnlLX6j9FHQM74z6cBk9Rw6M= cloud.google.com/go/auth/oauth2adapt v0.2.7/go.mod h1:NTbTTzfvPl1Y3V1nPpOgl2w6d/FjO7NNUQaWSox6ZMc= cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= @@ -35,8 +35,8 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/coreos/go-oidc/v3 v3.12.0 h1:sJk+8G2qq94rDI6ehZ71Bol3oUHy63qNYmkiSjrc/Jo= -github.com/coreos/go-oidc/v3 v3.12.0/go.mod h1:gE3LgjOgFoHi9a4ce4/tJczr0Ai2/BoDhf0r5lltWI0= +github.com/coreos/go-oidc/v3 v3.13.0 h1:M66zd0pcc5VxvBNM4pB331Wrsanby+QomQYjN8HamW8= +github.com/coreos/go-oidc/v3 v3.13.0/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -53,12 +53,10 @@ github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/ github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= -github.com/go-jose/go-jose/v3 v3.0.3 h1:fFKWeig/irsp7XD2zBxvnmA/XaRWp5V3CBsZXJF7G7k= -github.com/go-jose/go-jose/v3 v3.0.3/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= -github.com/go-jose/go-jose/v4 v4.0.4 h1:VsjPI33J0SB9vQM6PLmNjoHqMQNGPiZ0rHL7Ni7Q6/E= -github.com/go-jose/go-jose/v4 v4.0.4/go.mod h1:NKb5HO1EZccyMpiZNbdUw/14tiXNyUJh188dfnMCAfc= +github.com/go-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE= +github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -73,8 +71,8 @@ github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6 github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY= github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad h1:a6HEuzUHeKH6hwfN/ZoQgRgVIWFJljSWa/zetS2WTvg= github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= @@ -82,8 +80,8 @@ github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0 github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.4 h1:XYIDZApgAnrN1c855gTgghdIA6Stxb52D5RnLI1SLyw= -github.com/googleapis/enterprise-certificate-proxy v0.3.4/go.mod h1:YKe7cfqYXjKGpGvmSg28/fFvhNzinZQm8DGnaburhGA= +github.com/googleapis/enterprise-certificate-proxy v0.3.5 h1:VgzTY2jogw3xt39CusEnFJWm7rlsq5yL5q9XdLOuP5g= +github.com/googleapis/enterprise-certificate-proxy v0.3.5/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= @@ -100,8 +98,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/magiconair/properties v1.8.9 h1:nWcCbLq1N2v/cpNsy5WvQ37Fb+YElfq20WJ/a8RkpQM= -github.com/magiconair/properties v1.8.9/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa h1:hI1uC2A3vJFjwvBn0G0a7QBRdBUp6Y048BtLAHRTKPo= @@ -112,8 +110,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/onsi/ginkgo/v2 v2.22.2 h1:/3X8Panh8/WwhU/3Ssa6rCKqPLuAkVY2I0RoyDLySlU= -github.com/onsi/ginkgo/v2 v2.22.2/go.mod h1:oeMosUL+8LtarXBHu/c0bx2D/K9zyQ6uX3cTyztHwsk= +github.com/onsi/ginkgo/v2 v2.23.1 h1:Ox0cOPv/t8RzKJUfDo9ZKtRvBOJY369sFJnl00CjqwY= +github.com/onsi/ginkgo/v2 v2.23.1/go.mod h1:zXTP6xIp3U8aVuXN8ENK9IXRaTjFnpVB9mGmaSRvxnM= github.com/onsi/gomega v1.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8= github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY= github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= @@ -123,16 +121,16 @@ github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFu github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y= -github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= +github.com/prometheus/client_golang v1.21.1 h1:DOvXXTqVzvkIewV/CDPFdejpMCGeMcbGCQ8YOmu+Ibk= +github.com/prometheus/client_golang v1.21.1/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= -github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E= -github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw= +github.com/redis/go-redis/v9 v9.7.1 h1:4LhKRCIduqXqtvCUlaq9c8bdHOkICjDMrr1+Zb3osAc= +github.com/redis/go-redis/v9 v9.7.1/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo= @@ -150,6 +148,7 @@ github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= @@ -166,29 +165,31 @@ github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0 h1:r6I7RJCN86bpD/FQwedZ0vSixDpwuWREjW9oRMsmqDc= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0/go.mod h1:B9yO6b04uB80CzjedvewuqDhxJxi11s7/GtiGa8bAjI= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 h1:yd02MEjBdJkG3uabWP9apV+OuWRIXGDuJEUJbOHmCFU= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0/go.mod h1:umTcuxiv1n/s/S6/c2AT/g2CQ7u5C59sHDNmfSwgz7Q= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0 h1:rgMkmiGfix9vFJDcDi1PK8WEQP4FLQwLDfhp5ZLpFeE= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0/go.mod h1:ijPqXp5P6IRRByFVVg9DY8P5HkxkHE5ARIa+86aXPf4= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 h1:CV7UdSGJt/Ao6Gp4CXckLxVRRsRgDHoI8XjbL3PDl8s= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0/go.mod h1:FRmFuRJfag1IZ2dPkHnEoSFVgTVPUd2qf5Vi69hLb8I= go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ= go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE= -go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4= -go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU= -go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU= -go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ= +go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= +go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU= +go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= +go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= -go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= -go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= +go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs= -golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ= -golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c h1:KL/ZBHXgKGVmuZBZ01Lt57yE5ws8ZPSkkihmEyq7FXc= -golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= +golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw= +golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -196,15 +197,15 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.36.0 h1:vWF2fRbw4qslQsQzgFqZff+BItCvGFQqKzKIzx1rmoA= -golang.org/x/net v0.36.0/go.mod h1:bFmbeoIPfrw4sMHNhb4J9f6+tPziuGjq7Jk/38fxi1I= -golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= -golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= +golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= +golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= +golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= -golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= +golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -214,8 +215,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= -golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -227,28 +228,28 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= -golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= -golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= -golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0= +golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.29.0 h1:Xx0h3TtM9rzQpQuR4dKLrdglAmCEN5Oi+P74JdhdzXE= -golang.org/x/tools v0.29.0/go.mod h1:KMQVMRsVxU6nHCFXrBPhDB8XncLNLM0lIy/F14RP588= +golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU= +golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.219.0 h1:nnKIvxKs/06jWawp2liznTBnMRQBEPpGo7I+oEypTX0= -google.golang.org/api v0.219.0/go.mod h1:K6OmjGm+NtLrIkHxv1U3a0qIf/0JOvAHd5O/6AoyKYE= +google.golang.org/api v0.226.0 h1:9A29y1XUD+YRXfnHkO66KggxHBZWg9LsTGqm7TkUvtQ= +google.golang.org/api v0.226.0/go.mod h1:WP/0Xm4LVvMOCldfvOISnWquSRWbG2kArDZcg+W2DbY= google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 h1:ToEetK57OidYuqD4Q5w+vfEnPvPpuTwedCNVohYJfNk= -google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576 h1:CkkIfIt50+lT6NHAVoRYEyAvQGFM7xEwXUUywFvEb3Q= -google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576/go.mod h1:1R3kvZ1dtP3+4p4d3G8uJ8rFk/fWlScl38vanWACI08= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47 h1:91mG8dNTpkC0uChJUQ9zCiRqx3GEEFOWaRZ0mI6Oj2I= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50= -google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ= -google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw= -google.golang.org/protobuf v1.36.4 h1:6A3ZDJHn/eNqc1i+IdefRzy/9PokBTPvcqMySR7NNIM= -google.golang.org/protobuf v1.36.4/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24= +google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb h1:TLPQVbx1GJ8VKZxz52VAxl1EBgKXXbTiU9Fc5fZeLn4= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I= +google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= +google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= +google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= +google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -262,5 +263,5 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/apimachinery v0.32.1 h1:683ENpaCBjma4CYqsmZyhEzrGz6cjn1MY/X2jB2hkZs= -k8s.io/apimachinery v0.32.1/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= +k8s.io/apimachinery v0.32.3 h1:JmDuDarhDmA/Li7j3aPrwhpNBA94Nvk5zLeOge9HH1U= +k8s.io/apimachinery v0.32.3/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= From 669acb98112aa300cbbbc450ecac2aada252b800 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 25 Mar 2025 19:57:40 +0100 Subject: [PATCH 013/130] chore(deps): update module github.com/golang-jwt/jwt/v5 to v5.2.2 [security] (#3003) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 03b0f1f3..45782732 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,7 @@ require ( github.com/fsnotify/fsnotify v1.8.0 github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/go-jose/go-jose/v3 v3.0.4 - github.com/golang-jwt/jwt/v5 v5.2.1 + github.com/golang-jwt/jwt/v5 v5.2.2 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 diff --git a/go.sum b/go.sum index 85b4d444..8111b4f6 100644 --- a/go.sum +++ b/go.sum @@ -66,6 +66,8 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= +github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY= From 46554b5bffbedfa157054ddd71631a45ec3ec4b4 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 25 Mar 2025 20:22:56 +0100 Subject: [PATCH 014/130] chore(deps): update golang dependencies and pin to latest golang v1.23.x release (#3011) Signed-off-by: Jan Larwig --- CHANGELOG.md | 3 ++- go.mod | 18 +++++++++--------- go.sum | 34 ++++++++++++++++------------------ 3 files changed, 27 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db8b5728..c549c598 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,8 @@ - [#2697](https://github.com/oauth2-proxy/oauth2-proxy/pull/2697) Use `Max-Age` instead of `Expires` for cookie expiration (@matpen-wi) - [#2969](https://github.com/oauth2-proxy/oauth2-proxy/pull/2969) Update golang.org/x/oauth2 to v0.27.0 to address CVE-2025-22868 (@dsymonds) - [#2977](https://github.com/oauth2-proxy/oauth2-proxy/pull/2977) Update golang.org/x/net to v0.36.0 to address CVE-2025-22870 (@dsymonds) -- [#2982](https://github.com/oauth2-proxy/oauth2-proxy/pull/2982) chore(deps): remove go:generate tool from go.mod +- [#2982](https://github.com/oauth2-proxy/oauth2-proxy/pull/2982) chore(deps): remove go:generate tool from go.mod (@dolmen) +- [#3011](https://github.com/oauth2-proxy/oauth2-proxy/pull/3011) chore(deps): update golang dependencies and pin to latest golang v1.23.x release (@tuunit) # V7.8.1 diff --git a/go.mod b/go.mod index 45782732..2c8bfd26 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.23.0 +go 1.23.7 require ( cloud.google.com/go/compute/metadata v0.6.0 @@ -23,11 +23,11 @@ require ( github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa github.com/mitchellh/mapstructure v1.5.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.23.1 - github.com/onsi/gomega v1.36.2 + github.com/onsi/ginkgo/v2 v2.23.3 + github.com/onsi/gomega v1.36.3 github.com/pierrec/lz4/v4 v4.1.22 github.com/prometheus/client_golang v1.21.1 - github.com/redis/go-redis/v9 v9.7.1 + github.com/redis/go-redis/v9 v9.7.3 github.com/spf13/cast v1.7.1 github.com/spf13/pflag v1.0.6 github.com/spf13/viper v1.19.0 @@ -38,14 +38,14 @@ require ( golang.org/x/net v0.37.0 golang.org/x/oauth2 v0.28.0 golang.org/x/sync v0.12.0 - google.golang.org/api v0.226.0 + google.golang.org/api v0.228.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 k8s.io/apimachinery v0.32.3 ) require ( cloud.google.com/go/auth v0.15.0 // indirect - cloud.google.com/go/auth/oauth2adapt v0.2.7 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect @@ -59,7 +59,7 @@ require ( github.com/go-task/slim-sprig/v3 v3.0.0 // indirect github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect github.com/google/s2a-go v0.1.9 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.5 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect github.com/googleapis/gax-go/v2 v2.14.1 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/klauspost/compress v1.17.11 // indirect @@ -88,9 +88,9 @@ require ( golang.org/x/sys v0.31.0 // indirect golang.org/x/text v0.23.0 // indirect golang.org/x/tools v0.31.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 // indirect google.golang.org/grpc v1.71.0 // indirect - google.golang.org/protobuf v1.36.5 // indirect + google.golang.org/protobuf v1.36.6 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index 8111b4f6..2c0ada2a 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ cloud.google.com/go/auth v0.15.0 h1:Ly0u4aA5vG/fsSsxu98qCQBemXtAtJf+95z9HK+cxps= cloud.google.com/go/auth v0.15.0/go.mod h1:WJDGqZ1o9E9wKIL+IwStfyn/+s59zl4Bi+1KQNVXLZ8= -cloud.google.com/go/auth/oauth2adapt v0.2.7 h1:/Lc7xODdqcEw8IrZ9SvwnlLX6j9FHQM74z6cBk9Rw6M= -cloud.google.com/go/auth/oauth2adapt v0.2.7/go.mod h1:NTbTTzfvPl1Y3V1nPpOgl2w6d/FjO7NNUQaWSox6ZMc= +cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= +cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb h1:ZVN4Iat3runWOFLaBCDVU5a9X/XikSRBosye++6gojw= @@ -64,8 +64,6 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= -github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= @@ -82,8 +80,8 @@ github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0 github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.5 h1:VgzTY2jogw3xt39CusEnFJWm7rlsq5yL5q9XdLOuP5g= -github.com/googleapis/enterprise-certificate-proxy v0.3.5/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= +github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= @@ -112,10 +110,10 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/onsi/ginkgo/v2 v2.23.1 h1:Ox0cOPv/t8RzKJUfDo9ZKtRvBOJY369sFJnl00CjqwY= -github.com/onsi/ginkgo/v2 v2.23.1/go.mod h1:zXTP6xIp3U8aVuXN8ENK9IXRaTjFnpVB9mGmaSRvxnM= -github.com/onsi/gomega v1.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8= -github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY= +github.com/onsi/ginkgo/v2 v2.23.3 h1:edHxnszytJ4lD9D5Jjc4tiDkPBZ3siDeJJkUZJJVkp0= +github.com/onsi/ginkgo/v2 v2.23.3/go.mod h1:zXTP6xIp3U8aVuXN8ENK9IXRaTjFnpVB9mGmaSRvxnM= +github.com/onsi/gomega v1.36.3 h1:hID7cr8t3Wp26+cYnfcjR6HpJ00fdogN6dqZ1t6IylU= +github.com/onsi/gomega v1.36.3/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= @@ -131,8 +129,8 @@ github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= -github.com/redis/go-redis/v9 v9.7.1 h1:4LhKRCIduqXqtvCUlaq9c8bdHOkICjDMrr1+Zb3osAc= -github.com/redis/go-redis/v9 v9.7.1/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw= +github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= +github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo= @@ -241,17 +239,17 @@ golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU= golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.226.0 h1:9A29y1XUD+YRXfnHkO66KggxHBZWg9LsTGqm7TkUvtQ= -google.golang.org/api v0.226.0/go.mod h1:WP/0Xm4LVvMOCldfvOISnWquSRWbG2kArDZcg+W2DbY= +google.golang.org/api v0.228.0 h1:X2DJ/uoWGnY5obVjewbp8icSL5U4FzuCfy9OjbLSnLs= +google.golang.org/api v0.228.0/go.mod h1:wNvRS1Pbe8r4+IfBIniV8fwCpGwTrYa+kMUDiC5z5a4= google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 h1:ToEetK57OidYuqD4Q5w+vfEnPvPpuTwedCNVohYJfNk= google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24= google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb h1:TLPQVbx1GJ8VKZxz52VAxl1EBgKXXbTiU9Fc5fZeLn4= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 h1:iK2jbkWL86DXjEx0qiHcRE9dE4/Ahua5k6V8OWFb//c= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I= google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= -google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= -google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= +google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= From 2ab22bd9f19a47762a4686222bb8bd18bdf79837 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 25 Mar 2025 20:45:16 +0100 Subject: [PATCH 015/130] release v7.8.2 (#3012) * update to release version v7.8.2 * docs: release letter --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 22 +++++++++++++++++++ .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- .../version-7.8.x/installation.md | 2 +- 9 files changed, 30 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c549c598..a87bad36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,28 @@ ## Breaking Changes +## Changes since v7.8.2 + +# V7.8.2 + +## Release Highlights +- 🐛 Cookie Expiration bug has been squashed +- 🔵 Golang version upgrade to v1.23.7 +- 🕵️‍♀️ Vulnerabilities have been addressed + - CVE-2025-30204 + - CVE-2025-27144 + - CVE-2024-45336 + - CVE-2025-22866 + - CVE-2025-22870 + - CVE-2024-45341 + - CVE-2025-29923 + - CVE-2025-22866 + - CVE-2024-34156 + +## Important Notes + +## Breaking Changes + ## Changes since v7.8.1 - [#2927](https://github.com/oauth2-proxy/oauth2-proxy/pull/2927) chore(deps/build): bump golang to 1.23 and use go.mod as single point of truth for all build files (@tuunit) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index f433ba23..c994326f 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 7e1480a5..7f949d5b 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 6be06700..334bed2e 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index a9c79ec9..5ec5c680 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 531267d0..27615ae7 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 6b428e57..4286c8d3 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 81bf169b..77e0437a 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.8.1`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.8.2`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.8.x/installation.md b/docs/versioned_docs/version-7.8.x/installation.md index 81bf169b..77e0437a 100644 --- a/docs/versioned_docs/version-7.8.x/installation.md +++ b/docs/versioned_docs/version-7.8.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.8.1`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.8.2`) b. Using Go to install the latest release ```bash From 44d035c32c9cb737d8ac9311df3b40b2ded1ae9a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 25 Mar 2025 21:03:35 +0100 Subject: [PATCH 016/130] chore(deps): update dependency golangci/golangci-lint to v1.64.8 (#3004) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7c9f2a29..f9e4a377 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v1.64.7 + GOLANGCI_LINT_VERSION: v1.64.8 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 4d65ce65..2bdca60f 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v1.64.7 + GOLANGCI_LINT_VERSION: v1.64.8 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter From b2c69e25eb7ed3a1fd9ba085ba1dd6047979de8d Mon Sep 17 00:00:00 2001 From: Evan Gibler <20933572+egibs@users.noreply.github.com> Date: Tue, 25 Mar 2025 15:12:37 -0500 Subject: [PATCH 017/130] feat: update HashNonce to use crypto/sha256 (#2967) Signed-off-by: egibs <20933572+egibs@users.noreply.github.com> --- CHANGELOG.md | 1 + pkg/encryption/nonce.go | 17 ++++++++--------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a87bad36..54518f75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ - [#2977](https://github.com/oauth2-proxy/oauth2-proxy/pull/2977) Update golang.org/x/net to v0.36.0 to address CVE-2025-22870 (@dsymonds) - [#2982](https://github.com/oauth2-proxy/oauth2-proxy/pull/2982) chore(deps): remove go:generate tool from go.mod (@dolmen) - [#3011](https://github.com/oauth2-proxy/oauth2-proxy/pull/3011) chore(deps): update golang dependencies and pin to latest golang v1.23.x release (@tuunit) +- [#2967](https://github.com/oauth2-proxy/oauth2-proxy/pull/2967) Update HashNonce to use crypto/sha256 (@egibs) # V7.8.1 diff --git a/pkg/encryption/nonce.go b/pkg/encryption/nonce.go index b0ce68d4..67cf4465 100644 --- a/pkg/encryption/nonce.go +++ b/pkg/encryption/nonce.go @@ -3,9 +3,8 @@ package encryption import ( "crypto/hmac" "crypto/rand" + "crypto/sha256" "encoding/base64" - - "golang.org/x/crypto/blake2b" ) // Nonce generates a random n-byte slice @@ -18,16 +17,16 @@ func Nonce(length int) ([]byte, error) { return b, nil } -// HashNonce returns the BLAKE2b 256-bit hash of a nonce -// NOTE: Error checking (G104) is purposefully skipped: -// - `blake2b.New256` has no error path with a nil signing key -// - `hash.Hash` interface's `Write` has an error signature, but -// `blake2b.digest.Write` does not use it. -/* #nosec G104 */ +// HashNonce returns the SHA256 hash of a nonce func HashNonce(nonce []byte) string { - hasher, _ := blake2b.New256(nil) + if nonce == nil { + return "" + } + + hasher := sha256.New() hasher.Write(nonce) sum := hasher.Sum(nil) + return base64.RawURLEncoding.EncodeToString(sum) } From 99c4c654d97fa10c9800434bea81d368f5c5d96e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 25 Mar 2025 21:14:00 +0100 Subject: [PATCH 018/130] chore(deps): update docker-compose (#3005) --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 7f949d5b..922a0520 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -42,7 +42,7 @@ services: - httpbin.localtest.me gitea: - image: gitea/gitea:1.23.5 + image: gitea/gitea:1.23.6 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 5ec5c680..507dfc7d 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -81,7 +81,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.5.19 + image: gcr.io/etcd-development/etcd:v3.5.20 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 4286c8d3..53a56e9b 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -55,7 +55,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.5.19 + image: gcr.io/etcd-development/etcd:v3.5.20 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From b34b617aad849759e52f76ab3a858a31804519b2 Mon Sep 17 00:00:00 2001 From: Copolycube Date: Sat, 29 Mar 2025 05:47:54 -0400 Subject: [PATCH 019/130] docs: fix gitlab docs url for oauth2 integration (#3002) * Update gitlab.md with correct url for creating an application * docs: fix gitlab docs url for oauth2 integration --------- Co-authored-by: Jan Larwig --- docs/docs/configuration/providers/gitlab.md | 2 +- .../version-7.6.x/configuration/providers/gitlab.md | 2 +- .../version-7.7.x/configuration/providers/gitlab.md | 2 +- .../version-7.8.x/configuration/providers/gitlab.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/configuration/providers/gitlab.md b/docs/docs/configuration/providers/gitlab.md index 92cbdb6b..4cdbbbe1 100644 --- a/docs/docs/configuration/providers/gitlab.md +++ b/docs/docs/configuration/providers/gitlab.md @@ -16,7 +16,7 @@ This auth provider has been tested against Gitlab version 12.X. Due to Gitlab AP prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). Whether you are using GitLab.com or self-hosting GitLab, follow -[these steps to add an application](https://docs.gitlab.com/ce/integration/oauth_provider.html). Make sure to enable at +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. https://myapp.com/oauth2/callback. diff --git a/docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md index 92cbdb6b..4cdbbbe1 100644 --- a/docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md @@ -16,7 +16,7 @@ This auth provider has been tested against Gitlab version 12.X. Due to Gitlab AP prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). Whether you are using GitLab.com or self-hosting GitLab, follow -[these steps to add an application](https://docs.gitlab.com/ce/integration/oauth_provider.html). Make sure to enable at +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. https://myapp.com/oauth2/callback. diff --git a/docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md index 92cbdb6b..4cdbbbe1 100644 --- a/docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md @@ -16,7 +16,7 @@ This auth provider has been tested against Gitlab version 12.X. Due to Gitlab AP prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). Whether you are using GitLab.com or self-hosting GitLab, follow -[these steps to add an application](https://docs.gitlab.com/ce/integration/oauth_provider.html). Make sure to enable at +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. https://myapp.com/oauth2/callback. diff --git a/docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md index 92cbdb6b..4cdbbbe1 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md @@ -16,7 +16,7 @@ This auth provider has been tested against Gitlab version 12.X. Due to Gitlab AP prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). Whether you are using GitLab.com or self-hosting GitLab, follow -[these steps to add an application](https://docs.gitlab.com/ce/integration/oauth_provider.html). Make sure to enable at +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. https://myapp.com/oauth2/callback. From f6b95c0df85ab114059e66ffb7d6f2bdb8b2d5ec Mon Sep 17 00:00:00 2001 From: Michael Cornel Date: Mon, 31 Mar 2025 10:04:19 +0200 Subject: [PATCH 020/130] feat: allow to set non-default authorization request response mode (#3001) * Update Go version in devcontainer * Add option to change response mode in authorization request * Fix option name * Update docs and changelog * Rename config value to underscore * Add unit tests for added parameter * Move change to upcoming release * Generate alpha config --------- Co-authored-by: Michael Cornel --- .devcontainer/Dockerfile | 2 +- CHANGELOG.md | 2 ++ docs/docs/configuration/alpha_config.md | 1 + docs/docs/configuration/overview.md | 1 + pkg/apis/options/legacy_options.go | 3 +++ pkg/apis/options/providers.go | 2 ++ providers/provider_data.go | 2 ++ providers/provider_default.go | 5 +++++ providers/provider_default_test.go | 27 +++++++++++++++++++++++++ providers/providers.go | 9 +++++---- 10 files changed, 49 insertions(+), 5 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 3189ab66..89d97f30 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/vscode/devcontainers/go:1-1.22 +FROM mcr.microsoft.com/vscode/devcontainers/go:1-1.23 SHELL ["/bin/bash", "-o", "pipefail", "-c"] diff --git a/CHANGELOG.md b/CHANGELOG.md index 54518f75..a51aa773 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.8.2 +- [#3001](https://github.com/oauth2-proxy/oauth2-proxy/pull/3001) Allow to set non-default authorization request response mode (@stieler-it) + # V7.8.2 ## Release Highlights diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index e833f53c..732100ed 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -445,6 +445,7 @@ Provider holds all configuration for a single provider | `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | | `loginURL` | _string_ | LoginURL is the authentication endpoint | | `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | | `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | | `profileURL` | _string_ | ProfileURL is the profile access endpoint | | `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 69f218bf..52ead105 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -91,6 +91,7 @@ Provider specific options can be found on their respective subpages. | flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | | flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | | flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | | flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | | flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | | flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 163aaa2c..a2c5f4e3 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -524,6 +524,7 @@ type LegacyProvider struct { 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"` @@ -586,6 +587,7 @@ func legacyProviderFlagSet() *pflag.FlagSet { 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") @@ -684,6 +686,7 @@ func (l *LegacyProvider) convert() (Providers, error) { 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 diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 94c23ce1..0aa9d15a 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -68,6 +68,8 @@ type Provider struct { LoginURL string `json:"loginURL,omitempty"` // LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL LoginURLParameters []LoginURLParameter `json:"loginURLParameters,omitempty"` + // AuthRequestResponseMode defines the response mode to request during authorization request + AuthRequestResponseMode string `json:"authRequestResponseMode,omitempty"` // RedeemURL is the token redemption endpoint RedeemURL string `json:"redeemURL,omitempty"` // ProfileURL is the profile access endpoint diff --git a/providers/provider_data.go b/providers/provider_data.go index 3c59c6da..95de5c50 100644 --- a/providers/provider_data.go +++ b/providers/provider_data.go @@ -37,6 +37,8 @@ type ProviderData struct { ClientSecret string ClientSecretFile string Scope string + // The response mode requested from the provider or empty for default ("query") + AuthRequestResponseMode string // The picked CodeChallenge Method or empty if none. CodeChallengeMethod string // Code challenge methods supported by the Provider diff --git a/providers/provider_default.go b/providers/provider_default.go index 756b5f69..1735ddd3 100644 --- a/providers/provider_default.go +++ b/providers/provider_default.go @@ -36,6 +36,11 @@ var ( // codeChallenge and codeChallengeMethod are the PKCE challenge and method to append to the URL params. // they will be empty strings if no code challenge should be presented func (p *ProviderData) GetLoginURL(redirectURI, state, _ string, extraParams url.Values) string { + // Response mode should only be set if a non default mode is requested + if p.AuthRequestResponseMode != "" { + extraParams.Add("response_mode", p.AuthRequestResponseMode) + } + loginURL := makeLoginURL(p, redirectURI, state, extraParams) return loginURL.String() } diff --git a/providers/provider_default_test.go b/providers/provider_default_test.go index 80d5b4ce..f678d13d 100644 --- a/providers/provider_default_test.go +++ b/providers/provider_default_test.go @@ -119,3 +119,30 @@ func TestProviderDataAuthorize(t *testing.T) { }) } } + +func TestResponseModeConfigured(t *testing.T) { + p := &ProviderData{ + LoginURL: &url.URL{ + Scheme: "http", + Host: "my.test.idp", + Path: "/oauth/authorize", + }, + AuthRequestResponseMode: "form_post", + } + + result := p.GetLoginURL("https://my.test.app/oauth", "", "", url.Values{}) + assert.Contains(t, result, "response_mode=form_post") +} + +func TestResponseModeNotConfigured(t *testing.T) { + p := &ProviderData{ + LoginURL: &url.URL{ + Scheme: "http", + Host: "my.test.idp", + Path: "/oauth/authorize", + }, + } + + result := p.GetLoginURL("https://my.test.app/oauth", "", "", url.Values{}) + assert.NotContains(t, result, "response_mode") +} diff --git a/providers/providers.go b/providers/providers.go index 1e2d4044..3a125a24 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -74,10 +74,11 @@ func NewProvider(providerConfig options.Provider) (Provider, error) { func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, error) { p := &ProviderData{ - Scope: providerConfig.Scope, - ClientID: providerConfig.ClientID, - ClientSecret: providerConfig.ClientSecret, - ClientSecretFile: providerConfig.ClientSecretFile, + Scope: providerConfig.Scope, + ClientID: providerConfig.ClientID, + ClientSecret: providerConfig.ClientSecret, + ClientSecretFile: providerConfig.ClientSecretFile, + AuthRequestResponseMode: providerConfig.AuthRequestResponseMode, } needsVerifier, err := providerRequiresOIDCProviderVerifier(providerConfig.Type) From 3325dcb2bde97b552c9e99da489e73ed3a4da149 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 31 Mar 2025 22:19:36 +0000 Subject: [PATCH 021/130] chore(deps): update docker-compose --- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 507dfc7d..893d5e71 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -81,7 +81,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.5.20 + image: gcr.io/etcd-development/etcd:v3.5.21 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 27615ae7..9e314f5e 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.21 + image: traefik:v2.11.22 volumes: - "./traefik:/etc/traefik" ports: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 53a56e9b..0cdf352f 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -55,7 +55,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.5.20 + image: gcr.io/etcd-development/etcd:v3.5.21 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From bb6ff4ed147ec12e054b2e283676901943a0a4cb Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Apr 2025 19:53:12 +0200 Subject: [PATCH 022/130] chore(deps): update gitea/gitea docker tag to v1.23.7 (#3030) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 922a0520..2f4b1a01 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -42,7 +42,7 @@ services: - httpbin.localtest.me gitea: - image: gitea/gitea:1.23.6 + image: gitea/gitea:1.23.7 container_name: gitea environment: - USER_UID=1000 From 8abdbb5a18c6bef481d7b35fc6d90762cf8d7fec Mon Sep 17 00:00:00 2001 From: Justin Ryan Date: Mon, 21 Apr 2025 08:40:39 -0400 Subject: [PATCH 023/130] Add --bearer-token-login-fallback option (#2924) * add --deny-invalid-bearer-tokens * update changelog * PR feedback, update api-routes description * update --api-routes description * revert load_test fix that I needed locally --------- Co-authored-by: Justin Ryan --- CHANGELOG.md | 1 + docs/docs/configuration/overview.md | 3 +- oauthproxy.go | 6 ++- pkg/apis/options/load_test.go | 21 ++++---- pkg/apis/options/options.go | 47 +++++++++-------- pkg/middleware/jwt_session.go | 19 ++++--- pkg/middleware/jwt_session_test.go | 81 ++++++++++++++++++++++++++++- 7 files changed, 137 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a51aa773..f131c6c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ ## Changes since v7.8.1 +- [#2918](https://github.com/oauth2-proxy/oauth2-proxy/issues/2918) feat: add --bearer-token-login-fallback (@carillonator) - [#2927](https://github.com/oauth2-proxy/oauth2-proxy/pull/2927) chore(deps/build): bump golang to 1.23 and use go.mod as single point of truth for all build files (@tuunit) - [#2697](https://github.com/oauth2-proxy/oauth2-proxy/pull/2697) Use `Max-Age` instead of `Expires` for cookie expiration (@matpen-wi) - [#2969](https://github.com/oauth2-proxy/oauth2-proxy/pull/2969) Update golang.org/x/oauth2 to v0.27.0 to address CVE-2025-22868 (@dsymonds) diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 52ead105..33f87072 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -191,8 +191,9 @@ Provider specific options can be found on their respective subpages. | Flag / Config Field | Type | Description | Default | | ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | -| flag: `--api-route`
toml: `api_routes` | string \| list | return HTTP 401 instead of redirecting to authentication server if token is not valid. Format: path_regex | | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | | flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | | flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | | flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | | flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | diff --git a/oauthproxy.go b/oauthproxy.go index ca9d4e97..b85c89b4 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -163,6 +163,10 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr for _, issuer := range opts.ExtraJwtIssuers { logger.Printf("Skipping JWT tokens from extra JWT issuer: %q", issuer) } + if !opts.BearerTokenLoginFallback { + logger.Println("Denying requests with invalid JWT tokens") + } + } redirectURL := opts.GetRedirectURL() if redirectURL.Path == "" { @@ -402,7 +406,7 @@ func buildSessionChain(opts *options.Options, provider providers.Provider, sessi middlewareapi.CreateTokenToSessionFunc(verifier.Verify)) } - chain = chain.Append(middleware.NewJwtSessionLoader(sessionLoaders)) + chain = chain.Append(middleware.NewJwtSessionLoader(sessionLoaders, opts.BearerTokenLoginFallback)) } if validator != nil { diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 32d52fb8..4265156f 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -47,16 +47,17 @@ var _ = Describe("Load", func() { }, Options: Options{ - ProxyPrefix: "/oauth2", - PingPath: "/ping", - ReadyPath: "/ready", - RealClientIPHeader: "X-Real-IP", - ForceHTTPS: false, - Cookie: cookieDefaults(), - Session: sessionOptionsDefaults(), - Templates: templatesDefaults(), - SkipAuthPreflight: false, - Logging: loggingDefaults(), + BearerTokenLoginFallback: true, + ProxyPrefix: "/oauth2", + PingPath: "/ping", + ReadyPath: "/ready", + RealClientIPHeader: "X-Real-IP", + ForceHTTPS: false, + Cookie: cookieDefaults(), + Session: sessionOptionsDefaults(), + Templates: templatesDefaults(), + SkipAuthPreflight: false, + Logging: loggingDefaults(), }, } diff --git a/pkg/apis/options/options.go b/pkg/apis/options/options.go index 2982ca74..8fa72c7c 100644 --- a/pkg/apis/options/options.go +++ b/pkg/apis/options/options.go @@ -52,17 +52,18 @@ type Options struct { Providers Providers `cfg:",internal"` - APIRoutes []string `flag:"api-route" cfg:"api_routes"` - SkipAuthRegex []string `flag:"skip-auth-regex" cfg:"skip_auth_regex"` - SkipAuthRoutes []string `flag:"skip-auth-route" cfg:"skip_auth_routes"` - SkipJwtBearerTokens bool `flag:"skip-jwt-bearer-tokens" cfg:"skip_jwt_bearer_tokens"` - ExtraJwtIssuers []string `flag:"extra-jwt-issuers" cfg:"extra_jwt_issuers"` - SkipProviderButton bool `flag:"skip-provider-button" cfg:"skip_provider_button"` - SSLInsecureSkipVerify bool `flag:"ssl-insecure-skip-verify" cfg:"ssl_insecure_skip_verify"` - SkipAuthPreflight bool `flag:"skip-auth-preflight" cfg:"skip_auth_preflight"` - ForceJSONErrors bool `flag:"force-json-errors" cfg:"force_json_errors"` - EncodeState bool `flag:"encode-state" cfg:"encode_state"` - AllowQuerySemicolons bool `flag:"allow-query-semicolons" cfg:"allow_query_semicolons"` + APIRoutes []string `flag:"api-route" cfg:"api_routes"` + SkipAuthRegex []string `flag:"skip-auth-regex" cfg:"skip_auth_regex"` + SkipAuthRoutes []string `flag:"skip-auth-route" cfg:"skip_auth_routes"` + SkipJwtBearerTokens bool `flag:"skip-jwt-bearer-tokens" cfg:"skip_jwt_bearer_tokens"` + BearerTokenLoginFallback bool `flag:"bearer-token-login-fallback" cfg:"bearer_token_login_fallback"` + ExtraJwtIssuers []string `flag:"extra-jwt-issuers" cfg:"extra_jwt_issuers"` + SkipProviderButton bool `flag:"skip-provider-button" cfg:"skip_provider_button"` + SSLInsecureSkipVerify bool `flag:"ssl-insecure-skip-verify" cfg:"ssl_insecure_skip_verify"` + SkipAuthPreflight bool `flag:"skip-auth-preflight" cfg:"skip_auth_preflight"` + ForceJSONErrors bool `flag:"force-json-errors" cfg:"force_json_errors"` + EncodeState bool `flag:"encode-state" cfg:"encode_state"` + AllowQuerySemicolons bool `flag:"allow-query-semicolons" cfg:"allow_query_semicolons"` SignatureKey string `flag:"signature-key" cfg:"signature_key"` GCPHealthChecks bool `flag:"gcp-healthchecks" cfg:"gcp_healthchecks"` @@ -97,17 +98,18 @@ func (o *Options) SetRealClientIPParser(s ipapi.RealClientIPParser) { o.re // NewOptions constructs a new Options with defaulted values func NewOptions() *Options { return &Options{ - ProxyPrefix: "/oauth2", - Providers: providerDefaults(), - PingPath: "/ping", - ReadyPath: "/ready", - RealClientIPHeader: "X-Real-IP", - ForceHTTPS: false, - Cookie: cookieDefaults(), - Session: sessionOptionsDefaults(), - Templates: templatesDefaults(), - SkipAuthPreflight: false, - Logging: loggingDefaults(), + BearerTokenLoginFallback: true, + ProxyPrefix: "/oauth2", + Providers: providerDefaults(), + PingPath: "/ping", + ReadyPath: "/ready", + RealClientIPHeader: "X-Real-IP", + ForceHTTPS: false, + Cookie: cookieDefaults(), + Session: sessionOptionsDefaults(), + Templates: templatesDefaults(), + SkipAuthPreflight: false, + Logging: loggingDefaults(), } } @@ -128,6 +130,7 @@ func NewFlagSet() *pflag.FlagSet { flagSet.Bool("skip-auth-preflight", false, "will skip authentication for OPTIONS requests") flagSet.Bool("ssl-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS providers") flagSet.Bool("skip-jwt-bearer-tokens", false, "will skip requests that have verified JWT bearer tokens (default false)") + flagSet.Bool("bearer-token-login-fallback", true, "if skip-jwt-bearer-tokens is set, fall back to normal login redirect with an invalid JWT. If false, 403 instead") flagSet.Bool("force-json-errors", false, "will force JSON errors instead of HTTP error pages or redirects") flagSet.Bool("encode-state", false, "will encode oauth state with base64") flagSet.Bool("allow-query-semicolons", false, "allow the use of semicolons in query args") diff --git a/pkg/middleware/jwt_session.go b/pkg/middleware/jwt_session.go index 026b6ad8..790eb8b2 100644 --- a/pkg/middleware/jwt_session.go +++ b/pkg/middleware/jwt_session.go @@ -15,10 +15,11 @@ import ( const jwtRegexFormat = `^ey[a-zA-Z0-9_-]*\.ey[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]+$` -func NewJwtSessionLoader(sessionLoaders []middlewareapi.TokenToSessionFunc) alice.Constructor { +func NewJwtSessionLoader(sessionLoaders []middlewareapi.TokenToSessionFunc, bearerTokenLoginFallback bool) alice.Constructor { js := &jwtSessionLoader{ - jwtRegex: regexp.MustCompile(jwtRegexFormat), - sessionLoaders: sessionLoaders, + jwtRegex: regexp.MustCompile(jwtRegexFormat), + sessionLoaders: sessionLoaders, + denyInvalidJWTs: !bearerTokenLoginFallback, } return js.loadSession } @@ -26,14 +27,16 @@ func NewJwtSessionLoader(sessionLoaders []middlewareapi.TokenToSessionFunc) alic // jwtSessionLoader is responsible for loading sessions from JWTs in // Authorization headers. type jwtSessionLoader struct { - jwtRegex *regexp.Regexp - sessionLoaders []middlewareapi.TokenToSessionFunc + jwtRegex *regexp.Regexp + sessionLoaders []middlewareapi.TokenToSessionFunc + denyInvalidJWTs bool } // loadSession attempts to load a session from a JWT stored in an Authorization // header within the request. // If no authorization header is found, or the header is invalid, no session // will be loaded and the request will be passed to the next handler. +// Or if the JWT is invalid and denyInvalidJWTs, return 403 now. // If a session was loaded by a previous handler, it will not be replaced. func (j *jwtSessionLoader) loadSession(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { @@ -49,6 +52,10 @@ func (j *jwtSessionLoader) loadSession(next http.Handler) http.Handler { session, err := j.getJwtSession(req) if err != nil { logger.Errorf("Error retrieving session from token in Authorization header: %v", err) + if j.denyInvalidJWTs { + http.Error(rw, http.StatusText(http.StatusForbidden), http.StatusForbidden) + return + } } // Add the session to the scope if it was found @@ -58,7 +65,7 @@ func (j *jwtSessionLoader) loadSession(next http.Handler) http.Handler { } // getJwtSession loads a session based on a JWT token in the authorization header. -// (see the config options skip-jwt-bearer-tokens and extra-jwt-issuers) +// (see the config options skip-jwt-bearer-tokens, extra-jwt-issuers, and bearer-token-login-fallback) func (j *jwtSessionLoader) getJwtSession(req *http.Request) (*sessionsapi.SessionState, error) { auth := req.Header.Get("Authorization") if auth == "" { diff --git a/pkg/middleware/jwt_session_test.go b/pkg/middleware/jwt_session_test.go index f7051a64..12f30f5c 100644 --- a/pkg/middleware/jwt_session_test.go +++ b/pkg/middleware/jwt_session_test.go @@ -92,6 +92,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=` authorizationHeader string existingSession *sessionsapi.SessionState expectedSession *sessionsapi.SessionState + expectedStatus int } DescribeTable("with an authorization header", @@ -114,12 +115,13 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=` // Create the handler with a next handler that will capture the session // from the scope var gotSession *sessionsapi.SessionState - handler := NewJwtSessionLoader(sessionLoaders)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + handler := NewJwtSessionLoader(sessionLoaders, true)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotSession = middlewareapi.GetRequestScope(r).Session })) handler.ServeHTTP(rw, req) Expect(gotSession).To(Equal(in.expectedSession)) + Expect(rw.Code).To(Equal(200)) }, Entry("", jwtSessionLoaderTableInput{ authorizationHeader: "", @@ -163,6 +165,83 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=` }), ) + DescribeTable("with an authorization header, denyInvalidJWTs", + func(in jwtSessionLoaderTableInput) { + scope := &middlewareapi.RequestScope{ + Session: in.existingSession, + } + + // Set up the request with the authorization header and a request scope + req := httptest.NewRequest("", "/", nil) + req.Header.Set("Authorization", in.authorizationHeader) + req = middlewareapi.AddRequestScope(req, scope) + + rw := httptest.NewRecorder() + + sessionLoaders := []middlewareapi.TokenToSessionFunc{ + middlewareapi.CreateTokenToSessionFunc(verifier), + } + + // Create the handler with a next handler that will capture the session + // from the scope + var gotSession *sessionsapi.SessionState + handler := NewJwtSessionLoader(sessionLoaders, false)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotSession = middlewareapi.GetRequestScope(r).Session + })) + handler.ServeHTTP(rw, req) + + Expect(gotSession).To(Equal(in.expectedSession)) + Expect(rw.Code).To(Equal(in.expectedStatus)) + }, + Entry("", jwtSessionLoaderTableInput{ + authorizationHeader: "", + existingSession: nil, + expectedSession: nil, + expectedStatus: 200, + }), + Entry("abcdef", jwtSessionLoaderTableInput{ + authorizationHeader: "abcdef", + existingSession: nil, + expectedSession: nil, + expectedStatus: 403, + }), + Entry("abcdef (with existing session)", jwtSessionLoaderTableInput{ + authorizationHeader: "abcdef", + existingSession: &sessionsapi.SessionState{User: "user"}, + expectedSession: &sessionsapi.SessionState{User: "user"}, + expectedStatus: 200, + }), + Entry("Bearer ", jwtSessionLoaderTableInput{ + authorizationHeader: fmt.Sprintf("Bearer %s", verifiedToken), + existingSession: nil, + expectedSession: verifiedSession, + expectedStatus: 200, + }), + Entry("Bearer ", jwtSessionLoaderTableInput{ + authorizationHeader: fmt.Sprintf("Bearer %s", nonVerifiedToken), + existingSession: nil, + expectedSession: nil, + expectedStatus: 403, + }), + Entry("Bearer (with existing session)", jwtSessionLoaderTableInput{ + authorizationHeader: fmt.Sprintf("Bearer %s", verifiedToken), + existingSession: &sessionsapi.SessionState{User: "user"}, + expectedSession: &sessionsapi.SessionState{User: "user"}, + expectedStatus: 200, + }), + Entry("Basic Base64(:) (No password)", jwtSessionLoaderTableInput{ + authorizationHeader: "Basic ZXlKZm9vYmFyLmV5SmZvb2Jhci4xMjM0NWFzZGY6", + existingSession: nil, + expectedSession: nil, + expectedStatus: 403, + }), + Entry("Basic Base64(:x-oauth-basic) (Sentinel password)", jwtSessionLoaderTableInput{ + authorizationHeader: fmt.Sprintf("Basic %s", verifiedTokenXOAuthBasicBase64), + existingSession: nil, + expectedSession: verifiedSession, + expectedStatus: 200, + }), + ) }) Context("getJWTSession", func() { From 16e453e9f61f650be3b3c1fe1af92a6839467d33 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 21 Apr 2025 15:59:57 +0200 Subject: [PATCH 024/130] chore(deps): update module golang.org/x/net to v0.38.0 [security] (#3035) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 2c8bfd26..160d22e4 100644 --- a/go.mod +++ b/go.mod @@ -35,7 +35,7 @@ require ( github.com/vmihailenco/msgpack/v5 v5.4.1 golang.org/x/crypto v0.36.0 golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 - golang.org/x/net v0.37.0 + golang.org/x/net v0.38.0 golang.org/x/oauth2 v0.28.0 golang.org/x/sync v0.12.0 google.golang.org/api v0.228.0 diff --git a/go.sum b/go.sum index 2c0ada2a..4a0da2a0 100644 --- a/go.sum +++ b/go.sum @@ -199,6 +199,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= +golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= From 07b60b1553916a22a8c4d9ca11f5cf6a5e6489ff Mon Sep 17 00:00:00 2001 From: Enrico Date: Thu, 24 Apr 2025 12:47:48 +0100 Subject: [PATCH 025/130] chore(deps): upgrade to latest golang v1.23.x release (#3041) --- CHANGELOG.md | 1 + go.mod | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f131c6c2..050bd0c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.8.2 - [#3001](https://github.com/oauth2-proxy/oauth2-proxy/pull/3001) Allow to set non-default authorization request response mode (@stieler-it) +- [#3041](https://github.com/oauth2-proxy/oauth2-proxy/pull/3041) chore(deps): upgrade to latest golang v1.23.x release (@TheImplementer) # V7.8.2 diff --git a/go.mod b/go.mod index 160d22e4..c0bc2dc4 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.23.7 +go 1.23.8 require ( cloud.google.com/go/compute/metadata v0.6.0 From 3afae76103801e82b7752dd7f4081d01afa911c8 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 24 Apr 2025 14:01:29 +0200 Subject: [PATCH 026/130] chore(deps): update docker-compose (#3038) --- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 893d5e71..32a566a8 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -41,7 +41,7 @@ services: depends_on: - oauth2-proxy container_name: nginx - image: nginx:1.27 + image: nginx:1.28 restart: unless-stopped ports: - 80:80/tcp diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 9e314f5e..6c7813bd 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.22 + image: traefik:v2.11.24 volumes: - "./traefik:/etc/traefik" ports: From 7d85c99d8e510043c05ed34d3e8ee6ac3f0887c2 Mon Sep 17 00:00:00 2001 From: Richard Hagen Date: Fri, 25 Apr 2025 09:59:09 +0200 Subject: [PATCH 027/130] fix(entra-id): use federated credentials for refresh token (#3031) * fix: use federated credentials to refresh token in entra id * fix: add some error handling * chore: update changelog * chore: update comments * chore: update comments * doc: reference entra id docs and clearer phrasing of comments Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + providers/ms_entra_id.go | 115 ++++++++++++++++++++++++++++++++------- 2 files changed, 96 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 050bd0c2..2c460410 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ ## Changes since v7.8.2 +- [#3031](https://github.com/oauth2-proxy/oauth2-proxy/pull/3031) Fixes Refresh Token bug with Entra ID and Workload Identity (#3027)[https://github.com/oauth2-proxy/oauth2-proxy/issues/3028] by using client assertion when redeeming the token (@richard87) - [#3001](https://github.com/oauth2-proxy/oauth2-proxy/pull/3001) Allow to set non-default authorization request response mode (@stieler-it) - [#3041](https://github.com/oauth2-proxy/oauth2-proxy/pull/3041) chore(deps): upgrade to latest golang v1.23.x release (@TheImplementer) diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go index 330c7875..df1f38a4 100644 --- a/providers/ms_entra_id.go +++ b/providers/ms_entra_id.go @@ -8,7 +8,9 @@ import ( "net/url" "os" "regexp" + "time" + "github.com/coreos/go-oidc/v3/oidc" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" @@ -114,7 +116,8 @@ func (p *MicrosoftEntraIDProvider) redeemWithFederatedToken(ctx context.Context, params := url.Values{} - // create custom exchange parameters + // Exchange parameters for token federation + // https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-certificate-credential if codeVerifier != "" { params.Add("code_verifier", codeVerifier) } @@ -125,29 +128,78 @@ func (p *MicrosoftEntraIDProvider) redeemWithFederatedToken(ctx context.Context, params.Add("code", code) params.Add("grant_type", "authorization_code") - // perform exchange - resp := requests.New(p.RedeemURL.String()). - WithContext(ctx). - WithMethod("POST"). - WithBody(bytes.NewBufferString(params.Encode())). - SetHeader("Content-Type", "application/x-www-form-urlencoded"). - Do() - - // prepare token of type *oauth2.Token - var token *oauth2.Token - var rawResponse interface{} - - body := resp.Body() - if err := json.Unmarshal(body, &rawResponse); err != nil { - return nil, err + token, err := p.fetchToken(ctx, params) + if err != nil { + return nil, fmt.Errorf("error fetching token: %w", err) } - if err := json.Unmarshal(body, &token); err != nil { - return nil, err + return p.OIDCProvider.createSession(ctx, token, false) +} + +// RefreshSession uses the RefreshToken to fetch new Access and ID Tokens +func (p *MicrosoftEntraIDProvider) RefreshSession(ctx context.Context, s *sessions.SessionState) (bool, error) { + if s == nil || s.RefreshToken == "" { + return false, nil } - // create session using new token and generic OIDC provider - return p.OIDCProvider.createSession(ctx, token.WithExtra(rawResponse), false) + var err error + ctx = oidc.ClientContext(ctx, requests.DefaultHTTPClient) + if p.federatedTokenAuth { + err = p.redeemRefreshTokenWithFederatedToken(ctx, s) + } else { + err = p.redeemRefreshToken(ctx, s) + } + + if err != nil { + return false, fmt.Errorf("unable to redeem refresh token: %v", err) + } + + return true, nil +} + +// redeemRefreshTokenWithFederatedToken uses a RefreshToken and federated credentials with the RedeemURL to refresh the +// Refresh Token, Access Token and ID Token +func (p *MicrosoftEntraIDProvider) redeemRefreshTokenWithFederatedToken(ctx context.Context, s *sessions.SessionState) error { + federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") + federatedToken, err := os.ReadFile(federatedTokenPath) + if err != nil { + return fmt.Errorf("error reading federated token file %s: %s", federatedTokenPath, err) + } + + params := url.Values{} + params.Add("client_id", p.ClientID) + params.Add("client_assertion", string(federatedToken)) + params.Add("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") + params.Add("refresh_token", s.RefreshToken) + params.Add("grant_type", "refresh_token") + params.Add("expiry", time.Now().Add(-time.Hour).Format(time.RFC3339)) + + token, err := p.fetchToken(ctx, params) + if err != nil { + return fmt.Errorf("error fetching token: %w", err) + } + + newSession, err := p.OIDCProvider.createSession(ctx, token, true) + if err != nil { + return fmt.Errorf("unable create new session state from response: %v", err) + } + + // Update the ID Token and user details if returned as part of the refresh response + // ref. https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse + if newSession.IDToken != "" { + s.IDToken = newSession.IDToken + s.Email = newSession.Email + s.User = newSession.User + s.Groups = newSession.Groups + s.PreferredUsername = newSession.PreferredUsername + } + + s.AccessToken = newSession.AccessToken + s.RefreshToken = newSession.RefreshToken + s.CreatedAt = newSession.CreatedAt + s.ExpiresOn = newSession.ExpiresOn + + return nil } // checkGroupOverage checks ID token's group membership claims for the group overage @@ -245,3 +297,26 @@ func (p *MicrosoftEntraIDProvider) checkTenantMatchesTenantList(tenant string, a } return false } + +func (p *MicrosoftEntraIDProvider) fetchToken(ctx context.Context, params url.Values) (*oauth2.Token, error) { + resp := requests.New(p.RedeemURL.String()). + WithContext(ctx). + WithMethod("POST"). + WithBody(bytes.NewBufferString(params.Encode())). + SetHeader("Content-Type", "application/x-www-form-urlencoded"). + Do() + + var token *oauth2.Token + var rawResponse interface{} + + body := resp.Body() + if err := json.Unmarshal(body, &rawResponse); err != nil { + return nil, fmt.Errorf("unable to unmarshal raw response body: %w", err) + } + + if err := json.Unmarshal(body, &token); err != nil { + return nil, fmt.Errorf("unable to unmarshal token response body: %w", err) + } + + return token.WithExtra(rawResponse), nil +} From fc6ca1dde62dfb98935e3dba0f3fbc9d343c0bf1 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 27 Apr 2025 19:08:33 +0200 Subject: [PATCH 028/130] chore(deps): update ghcr.io/dexidp/dex docker tag to v2.42.1 (#3044) --- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 32a566a8..a8039f59 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -55,7 +55,7 @@ services: httpbin: {} dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.42.0 + image: ghcr.io/dexidp/dex:v2.42.1 command: dex serve /dex.yaml hostname: dex volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 0cdf352f..fb815cef 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -29,7 +29,7 @@ services: - httpbin dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.42.0 + image: ghcr.io/dexidp/dex:v2.42.1 command: dex serve /dex.yaml hostname: dex volumes: From 4237358ac3ebc5ae1c2359c71f1562bd03112f69 Mon Sep 17 00:00:00 2001 From: Michael Niksa Date: Sun, 27 Apr 2025 10:36:16 -0700 Subject: [PATCH 029/130] doc(entra-id): correct toml field in sample (#2946) --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- docs/docs/configuration/providers/ms_entra_id.md | 2 +- .../version-7.8.x/configuration/providers/ms_entra_id.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/configuration/providers/ms_entra_id.md b/docs/docs/configuration/providers/ms_entra_id.md index ca9fc850..c5d9594e 100644 --- a/docs/docs/configuration/providers/ms_entra_id.md +++ b/docs/docs/configuration/providers/ms_entra_id.md @@ -192,6 +192,6 @@ client_id="" client_secret="" insecure_oidc_skip_issuer_verification=true scope="openid profile email User.Read" -entra_id_allowed_tenant=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant email_domains="*" ``` diff --git a/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md index ca9fc850..c5d9594e 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md @@ -192,6 +192,6 @@ client_id="" client_secret="" insecure_oidc_skip_issuer_verification=true scope="openid profile email User.Read" -entra_id_allowed_tenant=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant email_domains="*" ``` From 367183d7b8d82be2fba2722c79e469cafdec1418 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 27 Apr 2025 20:09:52 +0200 Subject: [PATCH 030/130] chore(build): refactoring makefile for better usability and introducing a default help target (#2930) --- .github/workflows/ci.yml | 4 +- .github/workflows/nightly.yml | 4 +- .github/workflows/publish-release.yml | 4 +- Makefile | 116 ++++++++++++------ README.md | 2 +- RELEASE.md | 4 +- docs/docs/community/contribution.md | 21 +++- .../version-7.8.x/community/contribution.md | 21 +++- 8 files changed, 121 insertions(+), 55 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f9e4a377..0d98d90b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,10 +72,10 @@ jobs: - name: Docker Build if: (!startsWith(github.head_ref, 'release')) run: | - make docker + make build-docker # For release testing - name: Docker Build All if: github.base_ref == 'master' && startsWith(github.head_ref, 'release') run: | - make docker-all + make build-docker-all diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 9693ba3e..b2a69d95 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -34,8 +34,8 @@ jobs: - name: Build images run: | - make docker-nightly-build + make nightly-build - name: Push images run: | - make docker-nightly-push + make nightly-push diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 2bdca60f..5e23d8ad 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -122,8 +122,8 @@ jobs: - name: Build images run: | - make docker-all + make build-docker-all - name: Push images run: | - make docker-push-all + make push-docker-all diff --git a/Makefile b/Makefile index 280ac6c6..870f1d2d 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,29 @@ +#!/usr/bin/env bash + +# +# Makefile with some common workflow for dev, build and test +# + +##@ General + +# The help target prints out all targets with their descriptions organized +# beneath their categories. The categories are represented by '##@' and the +# target descriptions by '##'. The awk command is responsible for reading the +# entire set of makefiles included in this invocation, looking for lines of the +# file as xyz: ## something, and then pretty-format the target and help. Then, +# if there's a line with ##@ something, that gets pretty-printed as a category. +# More info on the usage of ANSI control characters for terminal formatting: +# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters +# More info on the awk command: +# http://linuxcommand.org/lc3_adv_awk.php + +# The following help command is Licensed under the Apache License, Version 2.0 (the "License") +# Copyright 2023 The Kubernetes Authors. +.PHONY: help +help: ## Display this help + @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) + + GO ?= go GOLANGCILINT ?= golangci-lint @@ -22,24 +48,10 @@ ifeq ($(COVER),true) TESTCOVER ?= -coverprofile c.out endif -.PHONY: all -all: lint $(BINARY) - -.PHONY: clean -clean: - -rm -rf release - -rm -f $(BINARY) - -.PHONY: distclean -distclean: clean - rm -rf vendor - -.PHONY: lint -lint: validate-go-version - GO111MODULE=on $(GOLANGCILINT) run +##@ Build .PHONY: build -build: validate-go-version clean $(BINARY) +build: validate-go-version clean $(BINARY) ## Build and create oauth2-proxy binary from current source code $(BINARY): CGO_ENABLED=0 $(GO) build -a -installsuffix cgo -ldflags="-X github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version.VERSION=${VERSION}" -o $@ github.com/oauth2-proxy/oauth2-proxy/v7 @@ -60,60 +72,92 @@ DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push -.PHONY: docker -docker: +.PHONY: build-docker +build-docker: build-distroless build-alpine ## Build multi architecture docker images in both flavours (distroless / alpine) + +.PHONY: build-distroless +build-distroless: ## Build multi architecture distroless based docker image $(DOCKER_BUILDX_X_PLATFORM) -t $(REGISTRY)/$(REPOSITORY):latest -t $(REGISTRY)/$(REPOSITORY):${VERSION} . + +.PHONY: build-alpine +build-alpine: ## Build multi architecture alpine based docker image $(DOCKER_BUILDX_X_PLATFORM_ALPINE) -t $(REGISTRY)/$(REPOSITORY):latest-alpine -t $(REGISTRY)/$(REPOSITORY):${VERSION}-alpine . -.PHONY: docker-push -docker-push: - $(DOCKER_BUILDX_PUSH_X_PLATFORM) -t $(REGISTRY)/$(REPOSITORY):latest -t $(REGISTRY)/$(REPOSITORY):${VERSION} . - $(DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE) -t $(REGISTRY)/$(REPOSITORY):latest-alpine -t $(REGISTRY)/$(REPOSITORY):${VERSION}-alpine . - -.PHONY: docker-all -docker-all: docker +.PHONY: build-docker-all +build-docker-all: build-docker ## Build docker images for all supported architectures in both flavours (distroless / alpine) $(DOCKER_BUILDX) --platform linux/amd64 -t $(REGISTRY)/$(REPOSITORY):latest-amd64 -t $(REGISTRY)/$(REPOSITORY):${VERSION}-amd64 . $(DOCKER_BUILDX) --platform linux/arm64 -t $(REGISTRY)/$(REPOSITORY):latest-arm64 -t $(REGISTRY)/$(REPOSITORY):${VERSION}-arm64 . $(DOCKER_BUILDX) --platform linux/ppc64le -t $(REGISTRY)/$(REPOSITORY):latest-ppc64le -t $(REGISTRY)/$(REPOSITORY):${VERSION}-ppc64le . $(DOCKER_BUILDX) --platform linux/arm/v7 -t $(REGISTRY)/$(REPOSITORY):latest-armv7 -t $(REGISTRY)/$(REPOSITORY):${VERSION}-armv7 . $(DOCKER_BUILDX) --platform linux/s390x -t $(REGISTRY)/$(REPOSITORY):latest-s390x -t $(REGISTRY)/$(REPOSITORY):${VERSION}-s390x . -.PHONY: docker-push-all -docker-push-all: docker-push + +##@ Publish + +.PHONY: push-docker +push-docker: push-distroless push-alpine ## Push multi architecture docker images for both flavours (distroless / alpine) + +.PHONY: push-distroless +push-distroless: ## Push multi architecture distroless based docker image + $(DOCKER_BUILDX_PUSH_X_PLATFORM) -t $(REGISTRY)/$(REPOSITORY):latest -t $(REGISTRY)/$(REPOSITORY):${VERSION} . + +.PHONY: push-alpine +push-alpine: ## Push multi architecture alpine based docker image + $(DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE) -t $(REGISTRY)/$(REPOSITORY):latest-alpine -t $(REGISTRY)/$(REPOSITORY):${VERSION}-alpine . + +.PHONY: push-docker-all +push-docker-all: push-docker ## Push docker images for all supported architectures for both flavours (distroless / alpine) $(DOCKER_BUILDX_PUSH) --platform linux/amd64 -t $(REGISTRY)/$(REPOSITORY):latest-amd64 -t $(REGISTRY)/$(REPOSITORY):${VERSION}-amd64 . $(DOCKER_BUILDX_PUSH) --platform linux/arm64 -t $(REGISTRY)/$(REPOSITORY):latest-arm64 -t $(REGISTRY)/$(REPOSITORY):${VERSION}-arm64 . $(DOCKER_BUILDX_PUSH) --platform linux/ppc64le -t $(REGISTRY)/$(REPOSITORY):latest-ppc64le -t $(REGISTRY)/$(REPOSITORY):${VERSION}-ppc64le . $(DOCKER_BUILDX_PUSH) --platform linux/arm/v7 -t $(REGISTRY)/$(REPOSITORY):latest-armv7 -t $(REGISTRY)/$(REPOSITORY):${VERSION}-armv7 . $(DOCKER_BUILDX_PUSH) --platform linux/s390x -t $(REGISTRY)/$(REPOSITORY):latest-s390x -t $(REGISTRY)/$(REPOSITORY):${VERSION}-s390x . -.PHONY: docker-nightly-build -docker-nightly-build: + +##@ Nightly scheduling + +.PHONY: nightly-build +nightly-build: ## Nightly build command for docker images in both flavours (distroless / alpine) $(DOCKER_BUILDX_X_PLATFORM) -t $(REGISTRY)/$(REPOSITORY)-nightly:latest -t $(REGISTRY)/$(REPOSITORY)-nightly:${DATE} . $(DOCKER_BUILDX_X_PLATFORM_ALPINE) -t ${REGISTRY}/$(REPOSITORY)-nightly:latest-alpine -t $(REGISTRY)/$(REPOSITORY)-nightly:${DATE}-alpine . -.PHONY: docker-nightly-push -docker-nightly-push: +.PHONY: nightly-push +nightly-push: ## Nightly push command for docker images in both flavours (distroless / alpine) $(DOCKER_BUILDX_PUSH_X_PLATFORM) -t $(REGISTRY)/$(REPOSITORY)-nightly:latest -t $(REGISTRY)/$(REPOSITORY)-nightly:${DATE} . $(DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE) -t ${REGISTRY}/$(REPOSITORY)-nightly:latest-alpine -t $(REGISTRY)/$(REPOSITORY)-nightly:${DATE}-alpine . + +##@ Docs + .PHONY: generate -generate: +generate: ## Generate alpha config docs from golang structs go generate ./pkg/... .PHONY: verify-generate -verify-generate: generate +verify-generate: generate ## Verify command to check if alpha config docs are in line with golang struct changes git diff --exit-code +##@ Miscellaneous + .PHONY: test -test: lint +test: lint ## Run all Go tests GO111MODULE=on $(GO) test $(TESTCOVER) -v -race ./... .PHONY: release -release: validate-go-version lint test +release: validate-go-version lint test ## Create a full release for all architectures (binaries and checksums) BINARY=${BINARY} VERSION=${VERSION} ./dist.sh +.PHONY: clean +clean: ## Cleanup release and build files + -rm -rf release + -rm -f $(BINARY) + +.PHONY: lint +lint: validate-go-version ## Lint all files using golangci-lint + GO111MODULE=on $(GOLANGCILINT) run + .PHONY: validate-go-version -validate-go-version: +validate-go-version: ## Validate Go environment requirements @if [ $(GO_MAJOR_VERSION) -gt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \ exit 0 ;\ elif [ $(GO_MAJOR_VERSION) -lt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \ diff --git a/README.md b/README.md index 33849682..dfcdc7aa 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![Continuous Integration](https://github.com/oauth2-proxy/oauth2-proxy/actions/workflows/ci.yaml/badge.svg)](https://github.com/oauth2-proxy/oauth2-proxy/actions/workflows/ci.yaml) +[![Continuous Integration](https://github.com/oauth2-proxy/oauth2-proxy/actions/workflows/ci.yml/badge.svg)](https://github.com/oauth2-proxy/oauth2-proxy/actions/workflows/ci.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/oauth2-proxy/oauth2-proxy)](https://goreportcard.com/report/github.com/oauth2-proxy/oauth2-proxy) [![GoDoc](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy?status.svg)](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy) [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE) diff --git a/RELEASE.md b/RELEASE.md index 92a25ebc..0e629457 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -41,8 +41,8 @@ Note this uses `v4.1.0` as an example release number. 10. Publish release in Github 11. Make and push docker images to Quay ``` - make docker-all - make docker-push-all + make build-docker-all + make push-docker-all ``` Note: Ensure the docker tags don't include `-dirty`. This means you have uncommitted changes. diff --git a/docs/docs/community/contribution.md b/docs/docs/community/contribution.md index a6e8674c..2cd330ac 100644 --- a/docs/docs/community/contribution.md +++ b/docs/docs/community/contribution.md @@ -68,11 +68,22 @@ For starting oauth2-proxy locally open the debugging tab and create the `launch. Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. -Open a terminal and switch to the `contrib/local-environment` directory. +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: -- Dex as your IdP: `docker compose -f docker-compose.yaml up dex etcd httpbin` -- Keycloak as your IdP: `docker compose -f docker-compose-keycloak.yaml up keycloak httpbin` +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... -The username for both is `admin@example.com` and password is `password`. +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:4190 -Start oauth2-proxy from the debug tab and open http://oauth2-proxy.localtest.me:4180/ for testing. diff --git a/docs/versioned_docs/version-7.8.x/community/contribution.md b/docs/versioned_docs/version-7.8.x/community/contribution.md index a6e8674c..2cd330ac 100644 --- a/docs/versioned_docs/version-7.8.x/community/contribution.md +++ b/docs/versioned_docs/version-7.8.x/community/contribution.md @@ -68,11 +68,22 @@ For starting oauth2-proxy locally open the debugging tab and create the `launch. Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. -Open a terminal and switch to the `contrib/local-environment` directory. +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: -- Dex as your IdP: `docker compose -f docker-compose.yaml up dex etcd httpbin` -- Keycloak as your IdP: `docker compose -f docker-compose-keycloak.yaml up keycloak httpbin` +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... -The username for both is `admin@example.com` and password is `password`. +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:4190 -Start oauth2-proxy from the debug tab and open http://oauth2-proxy.localtest.me:4180/ for testing. From 7b41c8e98761ab54f00d0228caadd43f519e6f7d Mon Sep 17 00:00:00 2001 From: "Guillaume \"Elektordi\" Genty" Date: Mon, 28 Apr 2025 11:23:19 +0200 Subject: [PATCH 031/130] fix: role extraction from access token in keycloak oidc (#1916) * Fix wrong token used in Keycloak OIDC provider * Update CHANGELOG for PR #1916 * Update tests * fix: keycloak oidc role extraction --------- Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + providers/keycloak_oidc.go | 33 ++++++++++++++--------- providers/keycloak_oidc_test.go | 47 +++++++++++++++++++++------------ 3 files changed, 51 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c460410..001dbe6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#3031](https://github.com/oauth2-proxy/oauth2-proxy/pull/3031) Fixes Refresh Token bug with Entra ID and Workload Identity (#3027)[https://github.com/oauth2-proxy/oauth2-proxy/issues/3028] by using client assertion when redeeming the token (@richard87) - [#3001](https://github.com/oauth2-proxy/oauth2-proxy/pull/3001) Allow to set non-default authorization request response mode (@stieler-it) - [#3041](https://github.com/oauth2-proxy/oauth2-proxy/pull/3041) chore(deps): upgrade to latest golang v1.23.x release (@TheImplementer) +- [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) fix: role extraction from access token in keycloak oidc (@Elektordi / @tuunit) # V7.8.2 diff --git a/providers/keycloak_oidc.go b/providers/keycloak_oidc.go index ab613752..6b949f45 100644 --- a/providers/keycloak_oidc.go +++ b/providers/keycloak_oidc.go @@ -2,7 +2,10 @@ package providers import ( "context" + "encoding/base64" + "encoding/json" "fmt" + "strings" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" @@ -51,7 +54,7 @@ func (p *KeycloakOIDCProvider) CreateSessionFromToken(ctx context.Context, token } // Extract custom keycloak roles and enrich session - if err := p.extractRoles(ctx, ss); err != nil { + if err := p.extractRoles(ss); err != nil { return nil, err } @@ -65,7 +68,7 @@ func (p *KeycloakOIDCProvider) EnrichSession(ctx context.Context, s *sessions.Se if err != nil { return fmt.Errorf("could not enrich oidc session: %v", err) } - return p.extractRoles(ctx, s) + return p.extractRoles(s) } // RefreshSession adds role extraction logic to the refresh flow @@ -77,11 +80,11 @@ func (p *KeycloakOIDCProvider) RefreshSession(ctx context.Context, s *sessions.S return refreshed, err } - return true, p.extractRoles(ctx, s) + return true, p.extractRoles(s) } -func (p *KeycloakOIDCProvider) extractRoles(ctx context.Context, s *sessions.SessionState) error { - claims, err := p.getAccessClaims(ctx, s) +func (p *KeycloakOIDCProvider) extractRoles(s *sessions.SessionState) error { + claims, err := p.getAccessClaims(s) if err != nil { return err } @@ -106,18 +109,22 @@ type accessClaims struct { ResourceAccess map[string]interface{} `json:"resource_access"` } -func (p *KeycloakOIDCProvider) getAccessClaims(ctx context.Context, s *sessions.SessionState) (*accessClaims, error) { - // HACK: This isn't an ID Token, but has similar structure & signing - token, err := p.Verifier.Verify(ctx, s.AccessToken) - if err != nil { - return nil, err +func (p *KeycloakOIDCProvider) getAccessClaims(s *sessions.SessionState) (*accessClaims, error) { + parts := strings.Split(s.AccessToken, ".") + if len(parts) < 2 { + return nil, fmt.Errorf("malformed access token, expected 3 parts got %d", len(parts)) } - var claims *accessClaims - if err = token.Claims(&claims); err != nil { + payload, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return nil, fmt.Errorf("malformed access token, couldn't extract jwt payload: %v", err) + } + + var claims accessClaims + if err := json.Unmarshal(payload, &claims); err != nil { return nil, err } - return claims, nil + return &claims, nil } // getClientRoles extracts client roles from the `resource_access` claim with diff --git a/providers/keycloak_oidc_test.go b/providers/keycloak_oidc_test.go index 699309fc..2e60b0d2 100644 --- a/providers/keycloak_oidc_test.go +++ b/providers/keycloak_oidc_test.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http/httptest" "net/url" + "strings" "github.com/coreos/go-oidc/v3/oidc" @@ -18,28 +19,40 @@ import ( ) const ( + idTokenHeader = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJjV1IteTRzRVU1MjZVelk1SFd6UEZJbWdMMWRKUllfQ0gyY1FFRXh4UGN3In0" + idTokenSignature = "Rh0zQGhWAm-2hn5JTWB3Lzuk9Ahpzs7As7ks-1VInl4" accessTokenHeader = "ewogICJhbGciOiAiUlMyNTYiLAogICJ0eXAiOiAiSldUIgp9" accessTokenSignature = "dyt0CoTl4WoVjAHI9Q_CwSKhl6d_9rhM3NrXuJttkao" defaultAudienceClaim = "aud" mockClientID = "cd6d4fae-f6a6-4a34-8454-2c6b598e9532" ) -var accessTokenPayload = base64.StdEncoding.EncodeToString([]byte( - fmt.Sprintf(`{"%s": "%s", "realm_access": {"roles": ["write"]}, "resource_access": {"default": {"roles": ["read"]}}}`, defaultAudienceClaim, mockClientID))) +var ( + accessTokenPayload = base64.RawURLEncoding.EncodeToString([]byte( + fmt.Sprintf(`{"%s": "%s", "realm_access": {"roles": ["write"]}, "resource_access": {"default": {"roles": ["read"]}}}`, defaultAudienceClaim, mockClientID))) + + idTokenPayload = base64.RawURLEncoding.EncodeToString([]byte( + fmt.Sprintf(`{"%s": "%s"}`, defaultAudienceClaim, mockClientID))) +) type DummyKeySet struct{} -func (DummyKeySet) VerifySignature(_ context.Context, _ string) (payload []byte, err error) { - p, _ := base64.RawURLEncoding.DecodeString(accessTokenPayload) +func (DummyKeySet) VerifySignature(_ context.Context, jwt string) (payload []byte, err error) { + parts := strings.Split(jwt, ".") + p, _ := base64.RawURLEncoding.DecodeString(parts[1]) return p, nil } -func getAccessToken() string { +func makeIDToken() string { + return fmt.Sprintf("%s.%s.%s", idTokenHeader, idTokenPayload, idTokenSignature) +} + +func makeAccessToken() string { return fmt.Sprintf("%s.%s.%s", accessTokenHeader, accessTokenPayload, accessTokenSignature) } func newTestKeycloakOIDCSetup() (*httptest.Server, *KeycloakOIDCProvider) { - redeemURL, server := newOIDCServer([]byte(fmt.Sprintf(`{"email": "new@thing.com", "expires_in": 300, "access_token": "%v"}`, getAccessToken()))) + redeemURL, server := newOIDCServer([]byte(fmt.Sprintf(`{"email": "new@thing.com", "expires_in": 300, "id_token": "%v", "access_token": "%v"}`, makeIDToken(), makeAccessToken()))) provider := newKeycloakOIDCProvider(redeemURL, options.Provider{}) return server, provider } @@ -134,16 +147,16 @@ var _ = Describe("Keycloak OIDC Provider Tests", func() { User: "already", Email: "a@b.com", Groups: nil, - IDToken: idToken, - AccessToken: getAccessToken(), + IDToken: makeIDToken(), + AccessToken: makeAccessToken(), RefreshToken: refreshToken, } expectedSession := &sessions.SessionState{ User: "already", Email: "a@b.com", Groups: []string{"role:write", "role:default:read"}, - IDToken: idToken, - AccessToken: getAccessToken(), + IDToken: makeIDToken(), + AccessToken: makeAccessToken(), RefreshToken: refreshToken, } @@ -164,16 +177,16 @@ var _ = Describe("Keycloak OIDC Provider Tests", func() { User: "already", Email: "a@b.com", Groups: []string{"existing", "group"}, - IDToken: idToken, - AccessToken: getAccessToken(), + IDToken: makeIDToken(), + AccessToken: makeAccessToken(), RefreshToken: refreshToken, } expectedSession := &sessions.SessionState{ User: "already", Email: "a@b.com", Groups: []string{"existing", "group", "role:write", "role:default:read"}, - IDToken: idToken, - AccessToken: getAccessToken(), + IDToken: makeIDToken(), + AccessToken: makeAccessToken(), RefreshToken: refreshToken, } @@ -196,8 +209,8 @@ var _ = Describe("Keycloak OIDC Provider Tests", func() { User: "already", Email: "a@b.com", Groups: nil, - IDToken: idToken, - AccessToken: getAccessToken(), + IDToken: makeIDToken(), + AccessToken: makeAccessToken(), RefreshToken: refreshToken, } @@ -219,7 +232,7 @@ var _ = Describe("Keycloak OIDC Provider Tests", func() { provider.ProfileURL = url - session, err := provider.CreateSessionFromToken(context.Background(), getAccessToken()) + session, err := provider.CreateSessionFromToken(context.Background(), makeAccessToken()) Expect(err).To(BeNil()) Expect(session.ExpiresOn).ToNot(BeNil()) Expect(session.CreatedAt).ToNot(BeNil()) From b7ff804506c9529d7636e809e1023143d3dd2e14 Mon Sep 17 00:00:00 2001 From: ikarius Date: Mon, 28 Apr 2025 16:39:09 +0200 Subject: [PATCH 032/130] feat: ability to parse JWT encoded profile claims (#3014) * fix: parse JWT profile claims * Comment with OIDC specs reference * fix: formatting * Updated changelog --------- Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/providers/util/claim_extractor.go | 21 ++++++++-- pkg/providers/util/claim_extractor_test.go | 48 ++++++++++++++++++++++ 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 001dbe6c..2c2fde8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - [#3001](https://github.com/oauth2-proxy/oauth2-proxy/pull/3001) Allow to set non-default authorization request response mode (@stieler-it) - [#3041](https://github.com/oauth2-proxy/oauth2-proxy/pull/3041) chore(deps): upgrade to latest golang v1.23.x release (@TheImplementer) - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) fix: role extraction from access token in keycloak oidc (@Elektordi / @tuunit) +- [#3014](https://github.com/oauth2-proxy/oauth2-proxy/pull/3014) feat: ability to parse JWT encoded profile claims (@ikarius) # V7.8.2 diff --git a/pkg/providers/util/claim_extractor.go b/pkg/providers/util/claim_extractor.go index ec2fac90..9ab7a8c8 100644 --- a/pkg/providers/util/claim_extractor.go +++ b/pkg/providers/util/claim_extractor.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "encoding/json" "fmt" + "mime" "net/http" "net/url" "strings" @@ -94,11 +95,25 @@ func (c *claimExtractor) loadProfileClaims() (*simplejson.Json, error) { return simplejson.New(), nil } - claims, err := requests.New(c.profileURL.String()). + builder := requests.New(c.profileURL.String()). WithContext(c.ctx). WithHeaders(c.requestHeaders). - Do(). - UnmarshalSimpleJSON() + Do() + + // We first check if the result is a JWT token + // https://openid.net/specs/openid-connect-core-1_0-final.html#UserInfoResponse + mediaType, _, parseErr := mime.ParseMediaType(builder.Headers().Get("Content-Type")) + + if parseErr == nil && mediaType == "application/jwt" { + // Decode and use JWT payload as profile claims + if pl, err := parseJWT(string(builder.Body())); err == nil { + return simplejson.NewJson(pl) + } + } + + // Otherwise, process as normal JSON payload + claims, err := builder.UnmarshalSimpleJSON() + if err != nil { return nil, fmt.Errorf("error making request to profile URL: %v", err) } diff --git a/pkg/providers/util/claim_extractor_test.go b/pkg/providers/util/claim_extractor_test.go index b6d0b513..4ce4606f 100644 --- a/pkg/providers/util/claim_extractor_test.go +++ b/pkg/providers/util/claim_extractor_test.go @@ -497,6 +497,54 @@ var _ = Describe("Claim Extractor Suite", func() { expectedDst: stringPointer("{\"foo\":[\"bar\",\"baz\"]}"), }), ) + + It("should extract claims from a JWT response", func() { + jwtResponsePayload := `{ + "user": "jwtUser", + "email": "jwtEmail", + "groups": [ + "jwtGroup1", + "jwtGroup2" + ] + }` + + jwtResponseHandler := func(rw http.ResponseWriter, req *http.Request) { + if !hasAuthorizedHeader(req.Header) { + rw.WriteHeader(403) + rw.Write([]byte("Unauthorized")) + return + } + + rw.Header().Set("Content-Type", "application/jwt; charset=utf-8") + rw.Write([]byte(createJWTFromPayload(jwtResponsePayload))) + } + + claimExtractor, serverClose, err := newTestClaimExtractor(testClaimExtractorOpts{ + idTokenPayload: emptyJSON, + setProfileURL: true, + profileRequestHeaders: newAuthorizedHeader(), + profileRequestHandler: jwtResponseHandler, + }) + Expect(err).ToNot(HaveOccurred()) + if serverClose != nil { + defer serverClose() + } + + value, exists, err := claimExtractor.GetClaim("user") + Expect(err).ToNot(HaveOccurred()) + Expect(exists).To(BeTrue()) + Expect(value).To(Equal("jwtUser")) + + value, exists, err = claimExtractor.GetClaim("email") + Expect(err).ToNot(HaveOccurred()) + Expect(exists).To(BeTrue()) + Expect(value).To(Equal("jwtEmail")) + + value, exists, err = claimExtractor.GetClaim("groups") + Expect(err).ToNot(HaveOccurred()) + Expect(exists).To(BeTrue()) + Expect(value).To(Equal([]interface{}{"jwtGroup1", "jwtGroup2"})) + }) }) // ****************************************** From 2ecb2c64aa9717f3d3819d170277b417cb72f878 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 28 Apr 2025 18:22:58 +0200 Subject: [PATCH 033/130] release: v7.9.0 (#3047) * add new docs version 7.9.x * update to release version v7.9.0 * doc: add changelog summary --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 16 + .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- .../versioned_docs/version-7.9.x/behaviour.md | 11 + .../version-7.9.x/community/contribution.md | 89 +++ .../version-7.9.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 560 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 318 ++++++++++ .../version-7.9.x/configuration/overview.md | 402 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 67 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 76 +++ .../configuration/providers/index.md | 43 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 ++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../version-7.9.x/configuration/sessions.md | 99 ++++ .../configuration/systemd_socket.md | 43 ++ .../version-7.9.x/configuration/tls.md | 85 +++ .../version-7.9.x/features/endpoints.md | 47 ++ .../version-7.9.x/installation.md | 32 + docs/versioned_docs/version-7.9.x/welcome.md | 23 + .../version-7.9.x-sidebars.json | 83 +++ docs/versions.json | 1 + 40 files changed, 3044 insertions(+), 7 deletions(-) create mode 100644 docs/versioned_docs/version-7.9.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.9.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.9.x/community/security.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.9.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.9.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.9.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.9.x/installation.md create mode 100644 docs/versioned_docs/version-7.9.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.9.x-sidebars.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c2fde8d..dca9694a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ ## Breaking Changes +## Changes since v7.9.0 + +# V7.9.0 + +## Release Highlights +- 📨 OAuth 2.0 Multiple Response Type Encoding +- 📦️ Support for JWT encoded profile claims +- 🔵 Golang version upgrade to v1.23.8 +- 🕵️‍♀️ Vulnerabilities have been addressed + - [CVE-2025-22871](https://github.com/advisories/GHSA-g9pc-8g42-g6vq) +- 🐛 Squashed some bugs + +## Important Notes + +## Breaking Changes + ## Changes since v7.8.2 - [#3031](https://github.com/oauth2-proxy/oauth2-proxy/pull/3031) Fixes Refresh Token bug with Entra ID and Workload Identity (#3027)[https://github.com/oauth2-proxy/oauth2-proxy/issues/3028] by using client assertion when redeeming the token (@richard87) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index c994326f..35608eb8 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 2f4b1a01..d9f445dc 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 334bed2e..7d99a1e2 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index a8039f59..6d534a18 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 6c7813bd..bdfdf785 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index fb815cef..54e6d379 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.8.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 77e0437a..3b6919d8 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.8.2`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.9.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.9.x/behaviour.md b/docs/versioned_docs/version-7.9.x/behaviour.md new file mode 100644 index 00000000..e063d4f9 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/behaviour.md @@ -0,0 +1,11 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) +3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set +4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) + +Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). diff --git a/docs/versioned_docs/version-7.9.x/community/contribution.md b/docs/versioned_docs/version-7.9.x/community/contribution.md new file mode 100644 index 00000000..2cd330ac --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/community/contribution.md @@ -0,0 +1,89 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +This project is currently still using go 1.22. You can follow the installation guide for go [here.](https://go.dev/doc/install) And you can find go version 1.22 in the archived section [here.](https://go.dev/dl/) + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:4190 + diff --git a/docs/versioned_docs/version-7.9.x/community/security.md b/docs/versioned_docs/version-7.9.x/community/security.md new file mode 100644 index 00000000..c24b57d9 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md new file mode 100644 index 00000000..732100ed --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md @@ -0,0 +1,560 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure multiple providers. | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### Duration +#### (`string` alias) + +(**Appears on:** [Upstream](#upstream)) + +Duration is as string representation of a period of time. +A duration string is a is a possibly signed sequence of decimal numbers, +each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Providers is a collection of definitions for providers. + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md.tmpl new file mode 100644 index 00000000..8258201f --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.9.x/configuration/integration.md b/docs/versioned_docs/version-7.9.x/configuration/integration.md new file mode 100644 index 00000000..05d39281 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/integration.md @@ -0,0 +1,318 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. +Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. +Note that `nginxinc/kubernetes-ingress` does not include the Lua module. + +```yaml +nginx.ingress.kubernetes.io/auth-response-headers: Authorization +nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri +nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth +nginx.ingress.kubernetes.io/configuration-snippet: | + auth_request_set $name_upstream_1 $upstream_cookie_name_1; + + access_by_lua_block { + if ngx.var.name_upstream_1 ~= "" then + ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") + end + } +``` +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.9.x/configuration/overview.md b/docs/versioned_docs/version-7.9.x/configuration/overview.md new file mode 100644 index 00000000..33f87072 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/overview.md @@ -0,0 +1,402 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| -------------------------------------------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.9.x/configuration/providers/adfs.md new file mode 100644 index 00000000..ec8d72d2 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.9.x/configuration/providers/bitbucket.md new file mode 100644 index 00000000..e31de752 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.9.x/configuration/providers/digitalocean.md new file mode 100644 index 00000000..f6a1e891 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.9.x/configuration/providers/facebook.md new file mode 100644 index 00000000..352c95ce --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.9.x/configuration/providers/gitea.md new file mode 100644 index 00000000..996a5ddb --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea +--- + +:::note +This is not actually its own provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/github.md b/docs/versioned_docs/version-7.9.x/configuration/providers/github.md new file mode 100644 index 00000000..04c3a4ef --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/github.md @@ -0,0 +1,67 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug), separated by a comma | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict by organization only, include the following flag: + +```shell + --github-org="" # restrict logins to members of this organisation +``` + +To restrict within an organization to specific teams, include the following flag in addition to `-github-org`: + +```shell + --github-team="" # restrict logins to members of any of these teams (slug), separated by a comma +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + --github-repo="" # restrict logins to collaborators of this repository formatted as orgname/repo +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + --github-token="" # the token to use when verifying repository collaborators +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators, +separated by a comma + +```shell + --github-user="" #allow logins by username, separated by a comma +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md new file mode 100644 index 00000000..4cdbbbe1 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/google.md b/docs/versioned_docs/version-7.9.x/configuration/providers/google.md new file mode 100644 index 00000000..e3e819ad --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/google.md @@ -0,0 +1,76 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.readonly + https://www.googleapis.com/auth/admin.directory.user.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/index.md b/docs/versioned_docs/version-7.9.x/configuration/providers/index.md new file mode 100644 index 00000000..9159aa33 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/index.md @@ -0,0 +1,43 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) + +The provider can be selected using the `provider` configuration value. + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.9.x/configuration/providers/keycloak.md new file mode 100644 index 00000000..11a1abca --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.9.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 00000000..b29096e3 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.9.x/configuration/providers/linkedin.md new file mode 100644 index 00000000..7d26ec43 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.9.x/configuration/providers/login_gov.md new file mode 100644 index 00000000..badbe48e --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.9.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 00000000..4feefc68 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md new file mode 100644 index 00000000..c5d9594e --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.9.x/configuration/providers/nextcloud.md new file mode 100644 index 00000000..85ebff03 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.9.x/configuration/providers/openid_connect.md new file mode 100644 index 00000000..de170058 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.9.x/configuration/sessions.md b/docs/versioned_docs/version-7.9.x/configuration/sessions.md new file mode 100644 index 00000000..e2037817 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.9.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.9.x/configuration/systemd_socket.md new file mode 100644 index 00000000..642e6f3f --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.9.x/configuration/tls.md b/docs/versioned_docs/version-7.9.x/configuration/tls.md new file mode 100644 index 00000000..68344b22 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.9.x/features/endpoints.md b/docs/versioned_docs/version-7.9.x/features/endpoints.md new file mode 100644 index 00000000..3ec1e2aa --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/features/endpoints.md @@ -0,0 +1,47 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.9.x/installation.md b/docs/versioned_docs/version-7.9.x/installation.md new file mode 100644 index 00000000..3b6919d8 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.9.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.9.x/welcome.md b/docs/versioned_docs/version-7.9.x/welcome.md new file mode 100644 index 00000000..7bceadd8 --- /dev/null +++ b/docs/versioned_docs/version-7.9.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.9.x-sidebars.json b/docs/versioned_sidebars/version-7.9.x-sidebars.json new file mode 100644 index 00000000..0dbf04bd --- /dev/null +++ b/docs/versioned_sidebars/version-7.9.x-sidebars.json @@ -0,0 +1,83 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index 970a545c..bdabb049 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.9.x", "7.8.x", "7.7.x", "7.6.x", From bae509d2ecde533ffa32a6a72159eb948cabd1d3 Mon Sep 17 00:00:00 2001 From: Evan Carroll Date: Mon, 28 Apr 2025 16:52:27 -0500 Subject: [PATCH 034/130] docs: clear up multiple-providers is unimplemented (#3046) * docs: clear up multiple-providers is unimplemented Currently this configuration option is held up by #926. So users don't assume this solution will work for them, and later find the feature is not yet implemented -- own the shortcoming clearly. * doc: add note about missing multi provider implementation to versioned docs --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- docs/docs/configuration/alpha_config.md | 8 ++++++-- docs/docs/configuration/providers/index.md | 2 +- .../version-7.8.x/configuration/alpha_config.md | 8 ++++++-- .../version-7.8.x/configuration/providers/index.md | 2 +- .../version-7.9.x/configuration/alpha_config.md | 8 ++++++-- .../version-7.9.x/configuration/providers/index.md | 2 +- pkg/apis/options/alpha_options.go | 4 +++- pkg/apis/options/providers.go | 6 +++++- 8 files changed, 29 insertions(+), 11 deletions(-) diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 732100ed..018a2941 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -168,7 +168,7 @@ They may change between releases without notice. | `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | | `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | | `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `providers` | _[Providers](#providers)_ | Providers is used to configure multiple providers. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | ### AzureOptions @@ -472,7 +472,11 @@ and oidc. (**Appears on:** [AlphaOptions](#alphaoptions)) -Providers is a collection of definitions for providers. +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). ### SecretSource diff --git a/docs/docs/configuration/providers/index.md b/docs/docs/configuration/providers/index.md index 9159aa33..b947c09b 100644 --- a/docs/docs/configuration/providers/index.md +++ b/docs/docs/configuration/providers/index.md @@ -25,7 +25,7 @@ Valid providers are : - [Nextcloud](nextcloud.md) - [OpenID Connect](openid_connect.md) -The provider can be selected using the `provider` configuration value. +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the OpenID Connect provider. diff --git a/docs/versioned_docs/version-7.8.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.8.x/configuration/alpha_config.md index e833f53c..c1b6c5af 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/alpha_config.md +++ b/docs/versioned_docs/version-7.8.x/configuration/alpha_config.md @@ -168,7 +168,7 @@ They may change between releases without notice. | `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | | `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | | `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `providers` | _[Providers](#providers)_ | Providers is used to configure multiple providers. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | ### AzureOptions @@ -471,7 +471,11 @@ and oidc. (**Appears on:** [AlphaOptions](#alphaoptions)) -Providers is a collection of definitions for providers. +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). ### SecretSource diff --git a/docs/versioned_docs/version-7.8.x/configuration/providers/index.md b/docs/versioned_docs/version-7.8.x/configuration/providers/index.md index 9159aa33..b947c09b 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/providers/index.md +++ b/docs/versioned_docs/version-7.8.x/configuration/providers/index.md @@ -25,7 +25,7 @@ Valid providers are : - [Nextcloud](nextcloud.md) - [OpenID Connect](openid_connect.md) -The provider can be selected using the `provider` configuration value. +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the OpenID Connect provider. diff --git a/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md index 732100ed..018a2941 100644 --- a/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md +++ b/docs/versioned_docs/version-7.9.x/configuration/alpha_config.md @@ -168,7 +168,7 @@ They may change between releases without notice. | `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | | `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | | `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `providers` | _[Providers](#providers)_ | Providers is used to configure multiple providers. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | ### AzureOptions @@ -472,7 +472,11 @@ and oidc. (**Appears on:** [AlphaOptions](#alphaoptions)) -Providers is a collection of definitions for providers. +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). ### SecretSource diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/index.md b/docs/versioned_docs/version-7.9.x/configuration/providers/index.md index 9159aa33..b947c09b 100644 --- a/docs/versioned_docs/version-7.9.x/configuration/providers/index.md +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/index.md @@ -25,7 +25,7 @@ Valid providers are : - [Nextcloud](nextcloud.md) - [OpenID Connect](openid_connect.md) -The provider can be selected using the `provider` configuration value. +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the OpenID Connect provider. diff --git a/pkg/apis/options/alpha_options.go b/pkg/apis/options/alpha_options.go index 04769d7f..a438518c 100644 --- a/pkg/apis/options/alpha_options.go +++ b/pkg/apis/options/alpha_options.go @@ -41,7 +41,9 @@ type AlphaOptions struct { // To use the secure server you must configure a TLS certificate and key. MetricsServer Server `json:"metricsServer,omitempty"` - // Providers is used to configure multiple providers. + // Providers is used to configure your provider. **Multiple-providers is not + // yet working.** [This feature is tracked in + // #925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) Providers Providers `json:"providers,omitempty"` } diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 0aa9d15a..280b1ce0 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -11,7 +11,11 @@ const ( // OIDCAudienceClaims is the generic audience claim list used by the OIDC provider. var OIDCAudienceClaims = []string{"aud"} -// Providers is a collection of definitions for providers. +// The provider can be selected using the `provider` configuration value, or +// set in the [`providers` array using +// AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +// However, [**the feature to implement multiple providers is not +// complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). type Providers []Provider // Provider holds all configuration for a single provider From 14d5355655070ab83d6064e8d4bd7ec475ed83ba Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 3 May 2025 21:44:30 +0200 Subject: [PATCH 035/130] docs: add note about version obfuscation to footer option (#3051) Signed-off-by: Jan Larwig --- docs/docs/configuration/overview.md | 2 +- docs/versioned_docs/version-7.6.x/configuration/overview.md | 2 +- docs/versioned_docs/version-7.7.x/configuration/overview.md | 2 +- docs/versioned_docs/version-7.8.x/configuration/overview.md | 2 +- docs/versioned_docs/version-7.9.x/configuration/overview.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 33f87072..bea70617 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -174,7 +174,7 @@ Provider specific options can be found on their respective subpages. | flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | | flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | | flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | -| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. | | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | | flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | ### Probe Options diff --git a/docs/versioned_docs/version-7.6.x/configuration/overview.md b/docs/versioned_docs/version-7.6.x/configuration/overview.md index e43a71c4..b7891156 100644 --- a/docs/versioned_docs/version-7.6.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.6.x/configuration/overview.md @@ -172,7 +172,7 @@ Provider specific options can be found on their respective subpages. | flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | | flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | | flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | -| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. | | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | | flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | ### Probe Options diff --git a/docs/versioned_docs/version-7.7.x/configuration/overview.md b/docs/versioned_docs/version-7.7.x/configuration/overview.md index d43e86ce..7c7b396f 100644 --- a/docs/versioned_docs/version-7.7.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.7.x/configuration/overview.md @@ -172,7 +172,7 @@ Provider specific options can be found on their respective subpages. | flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | | flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | | flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | -| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. | | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | | flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | ### Probe Options diff --git a/docs/versioned_docs/version-7.8.x/configuration/overview.md b/docs/versioned_docs/version-7.8.x/configuration/overview.md index 69f218bf..97b166df 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.8.x/configuration/overview.md @@ -173,7 +173,7 @@ Provider specific options can be found on their respective subpages. | flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | | flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | | flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | -| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. | | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | | flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | ### Probe Options diff --git a/docs/versioned_docs/version-7.9.x/configuration/overview.md b/docs/versioned_docs/version-7.9.x/configuration/overview.md index 33f87072..bea70617 100644 --- a/docs/versioned_docs/version-7.9.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.9.x/configuration/overview.md @@ -174,7 +174,7 @@ Provider specific options can be found on their respective subpages. | flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | | flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | | flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | -| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. | | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | | flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | ### Probe Options From f82e90426a1881d36bf995f25de9b7b1db4c2564 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 23 May 2025 16:49:24 +0200 Subject: [PATCH 036/130] chore(deps): update docker-compose (#3074) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 4 ++-- contrib/local-environment/docker-compose.yaml | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index d9f445dc..8097a186 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -42,7 +42,7 @@ services: - httpbin.localtest.me gitea: - image: gitea/gitea:1.23.7 + image: gitea/gitea:1.23.8 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 6d534a18..d814739c 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -55,7 +55,7 @@ services: httpbin: {} dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.42.1 + image: ghcr.io/dexidp/dex:v2.43.1 command: dex serve /dex.yaml hostname: dex volumes: @@ -81,7 +81,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.5.21 + image: gcr.io/etcd-development/etcd:v3.6.0 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 54e6d379..ed79eab5 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -29,7 +29,7 @@ services: - httpbin dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.42.1 + image: ghcr.io/dexidp/dex:v2.43.1 command: dex serve /dex.yaml hostname: dex volumes: @@ -55,7 +55,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.5.21 + image: gcr.io/etcd-development/etcd:v3.6.0 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From 09f6252ebfebd83bd3e1b595d4fb9b6162053c91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olivier=20Mengu=C3=A9?= Date: Mon, 26 May 2025 12:20:49 +0200 Subject: [PATCH 037/130] chore(deps): drop golang.org/x/exp/{slices,maps} (#3065) Use Go 1.23 stdlib instead: slices, maps. --- go.mod | 2 +- go.sum | 2 -- providers/azure.go | 3 +-- providers/github.go | 2 +- 4 files changed, 3 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index c0bc2dc4..9d7079c1 100644 --- a/go.mod +++ b/go.mod @@ -34,7 +34,6 @@ require ( github.com/stretchr/testify v1.10.0 github.com/vmihailenco/msgpack/v5 v5.4.1 golang.org/x/crypto v0.36.0 - golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 golang.org/x/net v0.38.0 golang.org/x/oauth2 v0.28.0 golang.org/x/sync v0.12.0 @@ -85,6 +84,7 @@ require ( go.opentelemetry.io/otel/trace v1.34.0 // indirect go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.9.0 // indirect + golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect golang.org/x/sys v0.31.0 // indirect golang.org/x/text v0.23.0 // indirect golang.org/x/tools v0.31.0 // indirect diff --git a/go.sum b/go.sum index 4a0da2a0..77e185eb 100644 --- a/go.sum +++ b/go.sum @@ -197,8 +197,6 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= -golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= diff --git a/providers/azure.go b/providers/azure.go index 5ae68d93..0eafdf6b 100644 --- a/providers/azure.go +++ b/providers/azure.go @@ -6,11 +6,10 @@ import ( "fmt" "net/http" "net/url" + "slices" "strings" "time" - "golang.org/x/exp/slices" - "github.com/bitly/go-simplejson" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" diff --git a/providers/github.go b/providers/github.go index 27c5cdf6..f85578fc 100644 --- a/providers/github.go +++ b/providers/github.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "maps" "net/http" "net/url" "path" @@ -15,7 +16,6 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" - "golang.org/x/exp/maps" ) // GitHubProvider represents an GitHub based Identity Provider From 1225d611e9979f4f37f63adf66df18f70cf700ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olivier=20Mengu=C3=A9?= Date: Mon, 26 May 2025 12:29:34 +0200 Subject: [PATCH 038/130] chore(lint): fix staticcheck issues (#3061) * chores: fix staticcheck QF1012 Fix use of fmt.Sprintf when writing to a writer. https://staticcheck.dev/docs/checks/#QF1012 https://github.com/oauth2-proxy/oauth2-proxy/issues/3060 * chores: fix staticcheck QF1003 Use switch instead of multiple if/else. https://staticcheck.dev/docs/checks/#QF1003 https://github.com/oauth2-proxy/oauth2-proxy/issues/3060 * chores: exclude staticcheck QF1008 for now We aim to migrate golangci-lint to v2 Let's disable QF1008 (Omit embedded fields from selector expression) for now. https://staticcheck.dev/docs/checks/#QF1008 * chores: fix golangci config: run.deadline -> timeout Rename config option to match v1 documentation: deadline -> timeout. https://golangci.github.io/legacy-v1-doc/usage/configuration/#run-configuration This error has been spotted by golangci-lint v2 migration tool. * chores: fix staticcheck QF1012 --- .golangci.yml | 6 +++++- pkg/app/pagewriter/pagewriter_test.go | 6 +++--- providers/google_test.go | 13 +++++++------ providers/ms_entra_id_test.go | 4 ++-- 4 files changed, 17 insertions(+), 12 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 9c56aa9c..5d82ab91 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,5 @@ run: - deadline: 120s + timeout: 120s linters: enable: - govet @@ -24,6 +24,10 @@ linters: - revive disable-all: true issues: + exclude: + # To ease migration to golangci-lint v2.1 + # https://staticcheck.dev/docs/checks/#QF1008 + - QF1008 exclude-rules: - path: _test\.go linters: diff --git a/pkg/app/pagewriter/pagewriter_test.go b/pkg/app/pagewriter/pagewriter_test.go index 7780ab35..1eb37c38 100644 --- a/pkg/app/pagewriter/pagewriter_test.go +++ b/pkg/app/pagewriter/pagewriter_test.go @@ -167,7 +167,7 @@ var _ = Describe("Writer", func() { writer: &WriterFuncs{ SignInPageFunc: func(rw http.ResponseWriter, req *http.Request, redirectURL string, statusCode int) { rw.WriteHeader(202) - rw.Write([]byte(fmt.Sprintf("%s %s", req.URL.Path, redirectURL))) + fmt.Fprintf(rw, "%s %s", req.URL.Path, redirectURL) }, }, expectedStatus: 202, @@ -200,7 +200,7 @@ var _ = Describe("Writer", func() { writer: &WriterFuncs{ ErrorPageFunc: func(rw http.ResponseWriter, opts ErrorPageOpts) { rw.WriteHeader(503) - rw.Write([]byte(fmt.Sprintf("%s %s", opts.RequestID, opts.RedirectURL))) + fmt.Fprintf(rw, "%s %s", opts.RequestID, opts.RedirectURL) }, }, expectedStatus: 503, @@ -230,7 +230,7 @@ var _ = Describe("Writer", func() { writer: &WriterFuncs{ ProxyErrorFunc: func(rw http.ResponseWriter, req *http.Request, proxyErr error) { rw.WriteHeader(503) - rw.Write([]byte(fmt.Sprintf("%s %v", req.URL.Path, proxyErr))) + fmt.Fprintf(rw, "%s %v", req.URL.Path, proxyErr) }, }, expectedStatus: 503, diff --git a/providers/google_test.go b/providers/google_test.go index 22c3800e..23bca7ea 100644 --- a/providers/google_test.go +++ b/providers/google_test.go @@ -237,30 +237,31 @@ func TestGoogleProviderGetEmailAddressEmailMissing(t *testing.T) { func TestGoogleProvider_userInGroup(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/admin/directory/v1/groups/group@example.com/hasMember/member-in-domain@example.com" { + switch r.URL.Path { + case "/admin/directory/v1/groups/group@example.com/hasMember/member-in-domain@example.com": fmt.Fprintln(w, `{"isMember":true}`) - } else if r.URL.Path == "/admin/directory/v1/groups/group@example.com/hasMember/non-member-in-domain@example.com" { + case "/admin/directory/v1/groups/group@example.com/hasMember/non-member-in-domain@example.com": fmt.Fprintln(w, `{"isMember":false}`) - } else if r.URL.Path == "/admin/directory/v1/groups/group@example.com/hasMember/member-out-of-domain@otherexample.com" { + case "/admin/directory/v1/groups/group@example.com/hasMember/member-out-of-domain@otherexample.com": http.Error( w, `{"error":{"errors":[{"domain":"global","reason":"invalid","message":"Invalid Input: memberKey"}],"code":400,"message":"Invalid Input: memberKey"}}`, http.StatusBadRequest, ) - } else if r.URL.Path == "/admin/directory/v1/groups/group@example.com/hasMember/non-member-out-of-domain@otherexample.com" { + case "/admin/directory/v1/groups/group@example.com/hasMember/non-member-out-of-domain@otherexample.com": http.Error( w, `{"error":{"errors":[{"domain":"global","reason":"invalid","message":"Invalid Input: memberKey"}],"code":400,"message":"Invalid Input: memberKey"}}`, http.StatusBadRequest, ) - } else if r.URL.Path == "/admin/directory/v1/groups/group@example.com/members/non-member-out-of-domain@otherexample.com" { + case "/admin/directory/v1/groups/group@example.com/members/non-member-out-of-domain@otherexample.com": // note that the client currently doesn't care what this response text or code is - any error here results in failure to match the group http.Error( w, `{"kind":"admin#directory#member","etag":"12345","id":"1234567890","email":"member-out-of-domain@otherexample.com","role":"MEMBER","type":"USER","status":"ACTIVE","delivery_settings":"ALL_MAIL"}`, http.StatusNotFound, ) - } else if r.URL.Path == "/admin/directory/v1/groups/group@example.com/members/member-out-of-domain@otherexample.com" { + case "/admin/directory/v1/groups/group@example.com/members/member-out-of-domain@otherexample.com": fmt.Fprintln(w, `{"kind":"admin#directory#member","etag":"12345","id":"1234567890","email":"member-out-of-domain@otherexample.com","role":"MEMBER","type":"USER","status":"ACTIVE","delivery_settings":"ALL_MAIL"}`, ) diff --git a/providers/ms_entra_id_test.go b/providers/ms_entra_id_test.go index b54163f0..dfd1ef99 100644 --- a/providers/ms_entra_id_test.go +++ b/providers/ms_entra_id_test.go @@ -149,7 +149,7 @@ func mockGraphAPI(noGroupMemberPermissions bool) *httptest.Server { } else if r.URL.Path == groupsPath && r.Method == http.MethodGet { // First page (pagination) - w.Write([]byte(fmt.Sprintf(`{ + fmt.Fprintf(w, `{ "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects(id)", "@odata.nextLink": "http://%s/v1.0/me/transitiveMemberOf?$select=id&$top=2&$skiptoken=TEST_TOKEN", "value": [ @@ -162,7 +162,7 @@ func mockGraphAPI(noGroupMemberPermissions bool) *httptest.Server { "id": "916f0604-8a3b-4a69-bda9-06db11a8f0cd" } ] - }`, r.Host))) + }`, r.Host) } }, )) From fb7e33519a59e0da203d50750e5fca214f5ee204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olivier=20Mengu=C3=A9?= Date: Mon, 26 May 2025 21:12:58 +0200 Subject: [PATCH 039/130] chores: major upgrade of golangci-lint from v1.64.8 to v2.1.6 (#3062) .golangci.yml migrated with "golangci-lint migrated" and then tweaked to add comments back. --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- .golangci.yml | 101 +++++++++++++++----------- 3 files changed, 60 insertions(+), 45 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d98d90b..b4061f91 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v1.64.8 + GOLANGCI_LINT_VERSION: v2.1.6 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 5e23d8ad..61c61e32 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v1.64.8 + GOLANGCI_LINT_VERSION: v2.1.6 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.golangci.yml b/.golangci.yml index 5d82ab91..0ebecab6 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,50 +1,65 @@ -run: - timeout: 120s +version: "2" linters: + default: none enable: + - bodyclose + - copyloopvar + - dogsled + - goconst + - gocritic + - goprintffuncname + - gosec - govet - ineffassign - - goconst - - gofmt - - goimports - - gosec - - gosimple - - staticcheck - - typecheck - - unused - - bodyclose - - dogsled - - goprintffuncname - misspell - prealloc - - copyloopvar - - stylecheck - - unconvert - - gocritic - revive - disable-all: true -issues: - exclude: - # To ease migration to golangci-lint v2.1 - # https://staticcheck.dev/docs/checks/#QF1008 - - QF1008 - exclude-rules: - - path: _test\.go - linters: - - scopelint - - bodyclose - - unconvert - - gocritic - - gosec - - goconst - - revive - - path: _test\.go - linters: - - revive - text: "dot-imports:" - # If we have tests in shared test folders, these can be less strictly linted - - path: tests/.*_tests\.go - linters: - - revive - - bodyclose - - stylecheck + - staticcheck + - unconvert + - unused + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - linters: + - bodyclose + - goconst + - gocritic + - gosec + - revive + - scopelint + - unconvert + path: _test\.go + - linters: + - revive + path: _test\.go + text: 'dot-imports:' + # # If we have tests in shared test folders, these can be less strictly linted + - linters: + - bodyclose + - revive + - staticcheck + path: tests/.*_tests\.go + # See https://github.com/oauth2-proxy/oauth2-proxy/issues/3060 + # https://staticcheck.dev/docs/checks/#QF1008 + - linters: + - staticcheck + text: QF1008 + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ From 7731437af49c2767dac211694b2eec70f71b799c Mon Sep 17 00:00:00 2001 From: Daniel Mersch <94058351+daniel-mersch@users.noreply.github.com> Date: Thu, 29 May 2025 18:11:07 +0200 Subject: [PATCH 040/130] feat: support for multiple github orgs (#3072) * fix for github teams * Update github.go * added errorhandling * Update github.md * refactored GitHub provider refactored hasOrg, hasOrgAndTeams and hasTeam into hasAccess to stay within function limit * reverted Refactoring * refactored github.go - joined hasOrgAndTeamAccess into checkRestrictions * refactored github.go - reduced number of returns of function checkRestrictions to 4 * updated GitHub provider to accept legacy team ids * GoFmt and golangci-lint Formatted with GoFmt and followed recommendations of GoLint * added Tests added Tests for checkRestrictions. * refactored in maintainer feedback * Removed code, documentation and tests for legacy ids * add changelog and update docs --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 2 + docs/docs/configuration/providers/github.md | 34 ++++-- providers/github.go | 62 +++++++--- providers/github_test.go | 129 ++++++++++++++++++++ 4 files changed, 201 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dca9694a..eb7b3e2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.9.0 +- [#3072](https://github.com/oauth2-proxy/oauth2-proxy/pull/3072) feat: support for multiple github orgs #3072 (@daniel-mersch) + # V7.9.0 ## Release Highlights diff --git a/docs/docs/configuration/providers/github.md b/docs/docs/configuration/providers/github.md index 04c3a4ef..cebca314 100644 --- a/docs/docs/configuration/providers/github.md +++ b/docs/docs/configuration/providers/github.md @@ -8,7 +8,7 @@ title: GitHub | Flag | Toml Field | Type | Description | Default | | ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | | `--github-org` | `github_org` | string | restrict logins to members of this organisation | | -| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug), separated by a comma | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | | `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | | `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | | `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | @@ -24,23 +24,36 @@ team level access, or to collaborators of a repository. Restricting by these opt NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified org and team or collaborators. -To restrict by organization only, include the following flag: +To restrict access to your organization: ```shell - --github-org="" # restrict logins to members of this organisation + # restrict logins to members of this organisation + --github-org="your-org" ``` -To restrict within an organization to specific teams, include the following flag in addition to `-github-org`: +To restrict access to specific teams within an organization: ```shell - --github-team="" # restrict logins to members of any of these teams (slug), separated by a comma + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" ``` If you would rather restrict access to collaborators of a repository, those users must either have push access to a public repository or any access to a private repository: ```shell - --github-repo="" # restrict logins to collaborators of this repository formatted as orgname/repo + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" ``` If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a @@ -48,14 +61,15 @@ If you'd like to allow access to users with **read only** access to a **public** created with at least the `public_repo` scope: ```shell - --github-token="" # the token to use when verifying repository collaborators + # the token to use when verifying repository collaborators + --github-token="" ``` -To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators, -separated by a comma +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: ```shell - --github-user="" #allow logins by username, separated by a comma + # allow logins by username, comma separated + --github-user="" ``` If you are using GitHub enterprise, make sure you set the following to the appropriate url: diff --git a/providers/github.go b/providers/github.go index f85578fc..749fcc03 100644 --- a/providers/github.go +++ b/providers/github.go @@ -200,6 +200,7 @@ func (p *GitHubProvider) hasOrgAndTeam(s *sessions.SessionState) error { if strings.EqualFold(p.Org, ot.Org) { hasOrg = true + teams := strings.Split(p.Team, ",") for _, team := range teams { if strings.EqualFold(strings.TrimSpace(team), ot.Team) { @@ -220,6 +221,37 @@ func (p *GitHubProvider) hasOrgAndTeam(s *sessions.SessionState) error { return errors.New("user is missing required organization") } +func (p *GitHubProvider) hasTeam(s *sessions.SessionState) error { + var teams []string + + for _, group := range s.Groups { + if strings.Contains(group, orgTeamSeparator) { + teams = append(teams, strings.TrimSpace(group)) + } + } + + var presentTeams = make([]string, 0, len(teams)) + + for _, ot := range teams { + allowedTeams := strings.Split(p.Team, ",") + for _, team := range allowedTeams { + if !strings.Contains(team, orgTeamSeparator) { + logger.Printf("Please use fully qualified team names (org:team-slug) if you omit the organisation. Current Team name: %s", team) + return errors.New("team name is invalid") + } + + if strings.EqualFold(strings.TrimSpace(team), ot) { + logger.Printf("Found Github Organization/Team:%s", ot) + return nil + } + } + presentTeams = append(presentTeams, ot) + } + + logger.Printf("Missing Team:%q in teams: %v", p.Team, presentTeams) + return errors.New("user is missing required team") +} + func (p *GitHubProvider) hasRepoAccess(ctx context.Context, accessToken string) error { // https://developer.github.com/v3/repos/#get-a-repository @@ -378,12 +410,22 @@ func (p *GitHubProvider) checkRestrictions(ctx context.Context, s *sessions.Sess return err } - if err := p.hasOrgAndTeamAccess(s); err != nil { + var err error + switch { + case p.Org != "" && p.Team != "": + err = p.hasOrgAndTeam(s) + case p.Org != "": + err = p.hasOrg(s) + case p.Team != "": + err = p.hasTeam(s) + } + + if err != nil { return err } if p.Org == "" && p.Repo != "" && p.Token == "" { - // If we have a token we'll do the collaborator check in GetUserName + // If we have a token we'll do the collaborator check return p.hasRepoAccess(ctx, s.AccessToken) } @@ -408,18 +450,6 @@ func (p *GitHubProvider) checkUserRestriction(ctx context.Context, s *sessions.S return verifiedUser, nil } -func (p *GitHubProvider) hasOrgAndTeamAccess(s *sessions.SessionState) error { - if p.Org != "" && p.Team != "" { - return p.hasOrgAndTeam(s) - } - - if p.Org != "" { - return p.hasOrg(s) - } - - return nil -} - func (p *GitHubProvider) getOrgAndTeam(ctx context.Context, s *sessions.SessionState) error { err := p.getOrgs(ctx, s) if err != nil { @@ -503,8 +533,8 @@ func (p *GitHubProvider) getTeams(ctx context.Context, s *sessions.SessionState) } for _, team := range teams { - logger.Printf("Member of Github Organization/Team:%q/%q", team.Org.Login, team.Slug) - s.Groups = append(s.Groups, team.Org.Login+orgTeamSeparator+team.Slug) + logger.Printf("Member of Github Organization/Team: %q/%q", team.Org.Login, team.Slug) + s.Groups = append(s.Groups, fmt.Sprintf("%s%s%s", team.Org.Login, orgTeamSeparator, team.Slug)) } pn++ diff --git a/providers/github_test.go b/providers/github_test.go index 8dfb943f..e86f5d7b 100644 --- a/providers/github_test.go +++ b/providers/github_test.go @@ -39,6 +39,7 @@ func testGitHubBackend(payloads map[string][]string) *httptest.Server { "/repos/oauth2-proxy/oauth2-proxy/collaborators/mbland": {""}, "/user": {""}, "/user/emails": {""}, + "/user/teams": {"page=1&per_page=100", "page=2&per_page=100", "page=3&per_page=100"}, "/user/orgs": {"page=1&per_page=100", "page=2&per_page=100", "page=3&per_page=100"}, // GitHub Enterprise Server API "/api/v3": {""}, @@ -168,6 +169,134 @@ func TestGitHubProvider_getEmailWithOrg(t *testing.T) { assert.Equal(t, "michael.bland@gsa.gov", session.Email) } +func TestGitHubProvider_checkRestrictionsOrg(t *testing.T) { + b := testGitHubBackend(map[string][]string{ + "/user/emails": {`[ {"email": "john.doe@example", "verified": true, "primary": true} ]`}, + "/user/orgs": { + `[ { "login": "test-org-1" } ]`, + `[ { "login": "test-org-2" } ]`, + `[ ]`, + }, + "/user/teams": { + `[ { "name":"test-team-1", "slug":"test-team-1", "organization": { "login": "test-org-1" } } ]`, + `[ { "name":"test-team-2", "slug":"test-team-2", "organization": { "login": "test-org-2" } } ]`, + `[ ]`, + }, + }) + defer b.Close() + + // This test should succeed, because of the valid organization. + bURL, _ := url.Parse(b.URL) + p := testGitHubProvider(bURL.Host, + options.GitHubOptions{ + Org: "test-org-1", + }, + ) + + var err error + session := CreateAuthorizedSession() + err = p.getOrgAndTeam(context.Background(), session) + assert.NoError(t, err) + err = p.checkRestrictions(context.Background(), session) + assert.NoError(t, err) + + // This part should fail, because user is not part of the organization + p = testGitHubProvider(bURL.Host, + options.GitHubOptions{ + Org: "test-org-1-fail", + }, + ) + + err = p.checkRestrictions(context.Background(), session) + assert.Error(t, err) +} + +func TestGitHubProvider_checkRestrictionsOrgTeam(t *testing.T) { + b := testGitHubBackend(map[string][]string{ + "/user/emails": {`[ {"email": "john.doe@example", "verified": true, "primary": true} ]`}, + "/user/orgs": { + `[ { "login": "test-org-1" } ]`, + `[ { "login": "test-org-2" } ]`, + `[ ]`, + }, + "/user/teams": { + `[ { "name":"test-team-1", "slug":"test-team-1", "organization": { "login": "test-org-1" } } ]`, + `[ { "name":"test-team-2", "slug":"test-team-2", "organization": { "login": "test-org-2" } } ]`, + `[ ]`, + }, + }) + defer b.Close() + + // This test should succeed, because of the valid Org and Team combination. + bURL, _ := url.Parse(b.URL) + p := testGitHubProvider(bURL.Host, + options.GitHubOptions{ + Org: "test-org-1", + Team: "test-team-1", + }, + ) + + var err error + session := CreateAuthorizedSession() + err = p.getOrgAndTeam(context.Background(), session) + assert.NoError(t, err) + err = p.checkRestrictions(context.Background(), session) + assert.NoError(t, err) + + // This part should fail, because user is not part of the organization and the team + p = testGitHubProvider(bURL.Host, + options.GitHubOptions{ + Org: "test-org-1-fail", + Team: "test-team-1-fail", + }, + ) + + err = p.checkRestrictions(context.Background(), session) + assert.Error(t, err) +} + +func TestGitHubProvider_checkRestrictionsTeam(t *testing.T) { + b := testGitHubBackend(map[string][]string{ + "/user/emails": {`[ {"email": "john.doe@example", "verified": true, "primary": true} ]`}, + "/user/orgs": { + `[ { "login": "test-org-1" } ]`, + `[ { "login": "test-org-2" } ]`, + `[ ]`, + }, + "/user/teams": { + `[ { "name":"test-team-1", "slug":"test-team-1", "organization": { "login": "test-org-1" } } ]`, + `[ { "name":"test-team-2", "slug":"test-team-2", "organization": { "login": "test-org-2" } } ]`, + `[ ]`, + }, + }) + defer b.Close() + + // This test should succeed, because of the valid org:slug combination. + bURL, _ := url.Parse(b.URL) + p := testGitHubProvider(bURL.Host, + options.GitHubOptions{ + Team: "test-org-1:test-team-1, test-org-2:test-team-2-fail", + }, + ) + + var err error + session := CreateAuthorizedSession() + err = p.getOrgAndTeam(context.Background(), session) + assert.NoError(t, err) + err = p.checkRestrictions(context.Background(), session) + assert.NoError(t, err) + + // This part should fail, because user is not part of the organization:team combination + p = testGitHubProvider(bURL.Host, + options.GitHubOptions{ + Team: "test-org-1-fail:test-team-1-fail, test-org-2-fail:test-team-2-fail", + }, + ) + + err = p.checkRestrictions(context.Background(), session) + assert.Error(t, err) +} + func TestGitHubProvider_getEmailWithWriteAccessToPublicRepo(t *testing.T) { b := testGitHubBackend(map[string][]string{ "/repo/oauth2-proxy/oauth2-proxy": {`{"permissions": {"pull": true, "push": true}, "private": false}`}, From c8c160da79436068f246fcdc80e3aed73c1c3002 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 11 Jul 2025 09:58:16 +0200 Subject: [PATCH 041/130] Create FUNDING.yml --- .github/FUNDING.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..dd450980 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,15 @@ +# These are supported funding model platforms + +github: tuunit # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: oauth2-proxy # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +polar: # Replace with a single Polar username +buy_me_a_coffee: # Replace with a single Buy Me a Coffee username +thanks_dev: # Replace with a single thanks.dev username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] From abb0a35bf33fb6c17312a849ef57d113c5c01f60 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Sun, 13 Jul 2025 14:55:57 -0500 Subject: [PATCH 042/130] feat: bump to go1.24.5 and full dependency update (#3116) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * upgrade to go1.24.5 dependency updates lint fixes chore(deps): upgrade github.com/spf13/viper to v1.20.1 Note that this upgrade also implied to upgrade github.com/mitchellh/mapstructure (nowadays unmaintained: https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc) to github.com/go-viper/mapstructure/v2. fix: adapt tests to match mapstructure v2 error messages pkg/apis/options/load_test.go: skip tests on Go 1.23 Add a compile guard for Go < 1.24 for the pkg/apis/options/load_test.go because the LoadYAML test depends on error messages produced by encoding/json that changed slightly (names of embedded structs are now reported). As we updated the test for go1.24, the test now fails on 1.23, but just for a slight difference, so we disable the test there. fix: adapt tests to match mapstructure v2 error messages remove pre 1.24 disclaimer add changelog entry Signed-off-by: Jan Larwig Co-Authored-By: Olivier Mengué * add exclusion for 'avoid meaningless package names' in .golangci.yml * chore(dep): upgrade all dependencies Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Olivier Mengué Co-authored-by: Jan Larwig --- .golangci.yml | 4 + CHANGELOG.md | 1 + go.mod | 90 ++++++------- go.sum | 227 +++++++++++++++++--------------- main_test.go | 4 +- pkg/apis/options/load.go | 2 +- pkg/apis/options/load_test.go | 4 +- pkg/encryption/cipher.go | 4 +- pkg/validation/sessions_test.go | 8 +- 9 files changed, 177 insertions(+), 167 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 0ebecab6..edab12d0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -49,6 +49,10 @@ linters: - linters: - staticcheck text: QF1008 + - linters: + - revive + path: util/.*\.go$ + text: "var-naming: avoid meaningless package names" paths: - third_party$ - builtin$ diff --git a/CHANGELOG.md b/CHANGELOG.md index eb7b3e2b..013f32b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.9.0 - [#3072](https://github.com/oauth2-proxy/oauth2-proxy/pull/3072) feat: support for multiple github orgs #3072 (@daniel-mersch) +- [#3116](https://github.com/oauth2-proxy/oauth2-proxy/pull/3116) feat: bump to go1.24.5 and full dependency update (@wardviaene / @dolmen) # V7.9.0 diff --git a/go.mod b/go.mod index 9d7079c1..087dad8a 100644 --- a/go.mod +++ b/go.mod @@ -1,97 +1,91 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.23.8 +go 1.24.5 require ( - cloud.google.com/go/compute/metadata v0.6.0 + cloud.google.com/go/compute/metadata v0.7.0 github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb - github.com/a8m/envsubst v1.4.2 - github.com/alicebob/miniredis/v2 v2.34.0 + github.com/a8m/envsubst v1.4.3 + github.com/alicebob/miniredis/v2 v2.35.0 github.com/benbjohnson/clock v1.3.5 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 - github.com/coreos/go-oidc/v3 v3.13.0 + github.com/coreos/go-oidc/v3 v3.14.1 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf - github.com/fsnotify/fsnotify v1.8.0 + github.com/fsnotify/fsnotify v1.9.0 github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/go-jose/go-jose/v3 v3.0.4 + github.com/go-viper/mapstructure/v2 v2.3.0 github.com/golang-jwt/jwt/v5 v5.2.2 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa - github.com/mitchellh/mapstructure v1.5.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.23.3 - github.com/onsi/gomega v1.36.3 + github.com/onsi/ginkgo/v2 v2.23.4 + github.com/onsi/gomega v1.37.0 github.com/pierrec/lz4/v4 v4.1.22 - github.com/prometheus/client_golang v1.21.1 - github.com/redis/go-redis/v9 v9.7.3 - github.com/spf13/cast v1.7.1 + github.com/prometheus/client_golang v1.22.0 + github.com/redis/go-redis/v9 v9.11.0 + github.com/spf13/cast v1.9.2 github.com/spf13/pflag v1.0.6 - github.com/spf13/viper v1.19.0 + github.com/spf13/viper v1.20.1 github.com/stretchr/testify v1.10.0 github.com/vmihailenco/msgpack/v5 v5.4.1 - golang.org/x/crypto v0.36.0 - golang.org/x/net v0.38.0 - golang.org/x/oauth2 v0.28.0 - golang.org/x/sync v0.12.0 - google.golang.org/api v0.228.0 + golang.org/x/crypto v0.40.0 + golang.org/x/net v0.42.0 + golang.org/x/oauth2 v0.30.0 + golang.org/x/sync v0.16.0 + google.golang.org/api v0.241.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - k8s.io/apimachinery v0.32.3 + k8s.io/apimachinery v0.33.2 ) require ( - cloud.google.com/go/auth v0.15.0 // indirect + cloud.google.com/go/auth v0.16.2 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect - github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/go-jose/go-jose/v4 v4.0.5 // indirect - github.com/go-logr/logr v1.4.2 // indirect + github.com/go-jose/go-jose/v4 v4.1.1 // indirect + github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect + github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect - github.com/googleapis/gax-go/v2 v2.14.1 // indirect - github.com/hashicorp/hcl v1.0.0 // indirect - github.com/klauspost/compress v1.17.11 // indirect + github.com/googleapis/gax-go/v2 v2.15.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect - github.com/magiconair/properties v1.8.7 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/client_model v0.6.1 // indirect - github.com/prometheus/common v0.62.0 // indirect - github.com/prometheus/procfs v0.15.1 // indirect - github.com/sagikazarmark/locafero v0.7.0 // indirect - github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.65.0 // indirect + github.com/prometheus/procfs v0.17.0 // indirect + github.com/rogpeppe/go-internal v1.14.1 // indirect + github.com/sagikazarmark/locafero v0.9.0 // indirect github.com/sourcegraph/conc v0.3.0 // indirect - github.com/spf13/afero v1.12.0 // indirect + github.com/spf13/afero v1.14.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 // indirect - go.opentelemetry.io/otel v1.34.0 // indirect - go.opentelemetry.io/otel/metric v1.34.0 // indirect - go.opentelemetry.io/otel/trace v1.34.0 // indirect - go.uber.org/atomic v1.9.0 // indirect - go.uber.org/multierr v1.9.0 // indirect - golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect - golang.org/x/sys v0.31.0 // indirect - golang.org/x/text v0.23.0 // indirect - golang.org/x/tools v0.31.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 // indirect - google.golang.org/grpc v1.71.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 // indirect + go.opentelemetry.io/otel v1.37.0 // indirect + go.opentelemetry.io/otel/metric v1.37.0 // indirect + go.opentelemetry.io/otel/trace v1.37.0 // indirect + go.uber.org/automaxprocs v1.6.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/sys v0.34.0 // indirect + golang.org/x/text v0.27.0 // indirect + golang.org/x/tools v0.35.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 // indirect + google.golang.org/grpc v1.73.0 // indirect google.golang.org/protobuf v1.36.6 // indirect - gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 77e185eb..22548221 100644 --- a/go.sum +++ b/go.sum @@ -1,21 +1,19 @@ -cloud.google.com/go/auth v0.15.0 h1:Ly0u4aA5vG/fsSsxu98qCQBemXtAtJf+95z9HK+cxps= -cloud.google.com/go/auth v0.15.0/go.mod h1:WJDGqZ1o9E9wKIL+IwStfyn/+s59zl4Bi+1KQNVXLZ8= +cloud.google.com/go/auth v0.16.2 h1:QvBAGFPLrDeoiNjyfVunhQ10HKNYuOwZ5noee0M5df4= +cloud.google.com/go/auth v0.16.2/go.mod h1:sRBas2Y1fB1vZTdurouM0AzuYQBMZinrUYL8EufhtEA= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= -cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= -cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= +cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU= +cloud.google.com/go/compute/metadata v0.7.0/go.mod h1:j5MvL9PprKL39t166CoB1uVHfQMs4tFQZZcKwksXUjo= github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb h1:ZVN4Iat3runWOFLaBCDVU5a9X/XikSRBosye++6gojw= github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb/go.mod h1:WsAABbY4HQBgd3mGuG4KMNTbHJCPvx9IVBHzysbknss= github.com/FZambia/sentinel v1.0.0 h1:KJ0ryjKTZk5WMp0dXvSdNqp3lFaW1fNFuEYfrkLOYIc= github.com/FZambia/sentinel v1.0.0/go.mod h1:ytL1Am/RLlAoAXG6Kj5LNuw/TRRQrv2rt2FT26vP5gI= -github.com/a8m/envsubst v1.4.2 h1:4yWIHXOLEJHQEFd4UjrWDrYeYlV7ncFWJOCBRLOZHQg= -github.com/a8m/envsubst v1.4.2/go.mod h1:MVUTQNGQ3tsjOOtKCNd+fl8RzhsXcDvvAEzkhGtlsbY= +github.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY= +github.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU= github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= -github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 h1:uvdUDbHQHO85qeSydJtItA4T55Pw6BtAejd0APRJOCE= -github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= github.com/alicebob/miniredis/v2 v2.11.1/go.mod h1:UA48pmi7aSazcGAvcdKcBB49z521IC9VjTTRz2nIaJE= -github.com/alicebob/miniredis/v2 v2.34.0 h1:mBFWMaJSNL9RwdGRyEDoAAv8OQc5UlEhLDQggTglU/0= -github.com/alicebob/miniredis/v2 v2.34.0/go.mod h1:kWShP4b58T1CW0Y5dViCd5ztzrDqRWqM3nksiyXk5s8= +github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI= +github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -35,12 +33,11 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/coreos/go-oidc/v3 v3.13.0 h1:M66zd0pcc5VxvBNM4pB331Wrsanby+QomQYjN8HamW8= -github.com/coreos/go-oidc/v3 v3.13.0/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= +github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk= +github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= @@ -49,21 +46,23 @@ github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2 github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= -github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= -github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= -github.com/go-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE= -github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA= +github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI= +github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk= +github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= @@ -73,8 +72,8 @@ github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85q github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad h1:a6HEuzUHeKH6hwfN/ZoQgRgVIWFJljSWa/zetS2WTvg= -github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= +github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 h1:xhMrHhTJ6zxu3gA4enFM9MLn9AY7613teCdFnlUVbSQ= +github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5/go.mod h1:5hDyRhoBCxViHszMt12TnOpEI4VVi+U8Gm9iphldiMA= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -82,73 +81,68 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= -github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= -github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= +github.com/googleapis/gax-go/v2 v2.14.2 h1:eBLnkZ9635krYIPD+ag1USrOAI0Nr0QYF3+/3GqO0k0= +github.com/googleapis/gax-go/v2 v2.14.2/go.mod h1:ON64QhlJkhVtSqp4v1uaK92VyZ2gmvDQsweuyLV+8+w= +github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= +github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo= github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA= -github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= -github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= -github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa h1:hI1uC2A3vJFjwvBn0G0a7QBRdBUp6Y048BtLAHRTKPo= github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa/go.mod h1:8vxFeeg++MqgCHwehSuwTlYCF0ALyDJbYJ1JsKi7v6s= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/onsi/ginkgo/v2 v2.23.3 h1:edHxnszytJ4lD9D5Jjc4tiDkPBZ3siDeJJkUZJJVkp0= -github.com/onsi/ginkgo/v2 v2.23.3/go.mod h1:zXTP6xIp3U8aVuXN8ENK9IXRaTjFnpVB9mGmaSRvxnM= -github.com/onsi/gomega v1.36.3 h1:hID7cr8t3Wp26+cYnfcjR6HpJ00fdogN6dqZ1t6IylU= -github.com/onsi/gomega v1.36.3/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= -github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= -github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus= +github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8= +github.com/onsi/gomega v1.37.0 h1:CdEG8g0S133B4OswTDC/5XPSzE1OeP29QOioj2PID2Y= +github.com/onsi/gomega v1.37.0/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.21.1 h1:DOvXXTqVzvkIewV/CDPFdejpMCGeMcbGCQ8YOmu+Ibk= -github.com/prometheus/client_golang v1.21.1/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= -github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= -github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= -github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= -github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= -github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= -github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= -github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= -github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= -github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= -github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= -github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo= -github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k= -github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= -github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g= +github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= +github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= +github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE= +github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8= +github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0= +github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw= +github.com/redis/go-redis/v9 v9.11.0 h1:E3S08Gl/nJNn5vkxd2i78wZxWAPNZgUNTp8WIJUAiIs= +github.com/redis/go-redis/v9 v9.11.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k= +github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs= -github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4= -github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y= -github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA= +github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo= +github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= +github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= -github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= +github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= +github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= @@ -165,31 +159,31 @@ github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0 h1:rgMkmiGfix9vFJDcDi1PK8WEQP4FLQwLDfhp5ZLpFeE= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0/go.mod h1:ijPqXp5P6IRRByFVVg9DY8P5HkxkHE5ARIa+86aXPf4= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 h1:CV7UdSGJt/Ao6Gp4CXckLxVRRsRgDHoI8XjbL3PDl8s= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0/go.mod h1:FRmFuRJfag1IZ2dPkHnEoSFVgTVPUd2qf5Vi69hLb8I= -go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= -go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= -go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ= -go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE= -go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= -go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU= -go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= -go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= -go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= -go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= -go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= -go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= -go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 h1:Hf9xI/XLML9ElpiHVDNwvqI0hIFlzV8dgIr35kV1kRU= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0/go.mod h1:NfchwuyNoMcZ5MLHwPrODwUF1HWCXWrL31s8gSAdIKY= +go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ= +go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I= +go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE= +go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E= +go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI= +go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg= +go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc= +go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps= +go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4= +go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0= +go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= +go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= -golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= -golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw= -golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM= +golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= +golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= +golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= +golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -197,15 +191,19 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= -golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= -golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= -golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= +golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= +golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= +golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= +golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= +golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= +golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= -golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8= +golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= +golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -215,8 +213,10 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= -golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= +golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -228,33 +228,42 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= -golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= -golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0= -golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= +golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= +golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= +golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU= -golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ= +golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo= +golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg= +golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= +golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.228.0 h1:X2DJ/uoWGnY5obVjewbp8icSL5U4FzuCfy9OjbLSnLs= -google.golang.org/api v0.228.0/go.mod h1:wNvRS1Pbe8r4+IfBIniV8fwCpGwTrYa+kMUDiC5z5a4= -google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 h1:ToEetK57OidYuqD4Q5w+vfEnPvPpuTwedCNVohYJfNk= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 h1:iK2jbkWL86DXjEx0qiHcRE9dE4/Ahua5k6V8OWFb//c= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I= -google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= -google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= +google.golang.org/api v0.240.0 h1:PxG3AA2UIqT1ofIzWV2COM3j3JagKTKSwy7L6RHNXNU= +google.golang.org/api v0.240.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= +google.golang.org/api v0.241.0 h1:QKwqWQlkc6O895LchPEDUSYr22Xp3NCxpQRiWTB6avE= +google.golang.org/api v0.241.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= +google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 h1:1tXaIXCracvtsRxSBsYDiSBN0cuJvM7QYW+MrpIRY78= +google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:49MsLSx0oWMOZqcpB3uL8ZOkAh1+TndpJ8ONoCBWiZk= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= +google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2 h1:vPV0tzlsK6EzEDHNNH5sa7Hs9bd7iXR7B1tSiPepkV0= +google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:pKLAc5OolXC3ViWGI62vvC0n10CpwAtRcTNCFwTKBEw= +google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 h1:fc6jSaCT0vBduLYZHYrBBNY4dsWuvgyff9noRNDdBeE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 h1:pFyd6EwwL2TqFf8emdthzeX+gZE1ElRq3iM8pui4KBY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/grpc v1.73.0 h1:VIWSmpI2MegBtTuFt5/JWy2oXxtjJ/e89Z70ImfD2ok= +google.golang.org/grpc v1.73.0/go.mod h1:50sbHOUqWoCQGI8V2HQLJM0B+LMlIUjNSZmow7EVBQc= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -263,5 +272,5 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/apimachinery v0.32.3 h1:JmDuDarhDmA/Li7j3aPrwhpNBA94Nvk5zLeOge9HH1U= -k8s.io/apimachinery v0.32.3/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= +k8s.io/apimachinery v0.33.2 h1:IHFVhqg59mb8PJWTLi8m1mAoepkUNYmptHsV+Z1m5jY= +k8s.io/apimachinery v0.33.2/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= diff --git a/main_test.go b/main_test.go index 761c0c0b..8e40fe7f 100644 --- a/main_test.go +++ b/main_test.go @@ -245,7 +245,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Entry("with bad legacy configuration", loadConfigurationTableInput{ configContent: testCoreConfig + "unknown_field=\"something\"", expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load config: error unmarshalling config: 1 error(s) decoding:\n\n* '' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), }), Entry("with bad alpha configuration", loadConfigurationTableInput{ configContent: testCoreConfig, @@ -257,7 +257,7 @@ redirect_url="http://localhost:4180/oauth2/callback" configContent: testCoreConfig + "unknown_field=\"something\"", alphaConfigContent: testAlphaConfig, expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load core options: failed to load config: error unmarshalling config: 1 error(s) decoding:\n\n* '' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load core options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), }), ) }) diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 1f22dfbc..b198c4ff 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -9,7 +9,7 @@ import ( "github.com/a8m/envsubst" "github.com/ghodss/yaml" - "github.com/mitchellh/mapstructure" + "github.com/go-viper/mapstructure/v2" "github.com/spf13/pflag" "github.com/spf13/viper" ) diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 4265156f..fefbc2e7 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -329,7 +329,7 @@ var _ = Describe("Load", func() { Entry("with an unknown option in the config file", &testOptionsTableInput{ configFile: []byte(`unknown_option="foo"`), flagSet: func() *pflag.FlagSet { return testOptionsFlagSet }, - expectedErr: fmt.Errorf("error unmarshalling config: 1 error(s) decoding:\n\n* '' has invalid keys: unknown_option"), + expectedErr: fmt.Errorf("error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_option"), // Viper will unmarshal before returning the error, so this is the default output expectedOutput: &TestOptions{ StringOption: "default", @@ -471,7 +471,7 @@ sub: configFile: []byte(`stringSliceOption: "a"`), input: &TestOptions{}, expectedOutput: &TestOptions{}, - expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go struct field TestOptions.StringSliceOption of type []string"), + expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go struct field TestOptions.TestOptionSubStruct.StringSliceOption of type []string"), }), Entry("with a config file containing environment variable references", loadYAMLTableInput{ configFile: []byte("stringOption: ${TESTUSER}"), diff --git a/pkg/encryption/cipher.go b/pkg/encryption/cipher.go index 37e08ba8..300bba3a 100644 --- a/pkg/encryption/cipher.go +++ b/pkg/encryption/cipher.go @@ -66,7 +66,7 @@ func (c *cfbCipher) Encrypt(value []byte) ([]byte, error) { return nil, fmt.Errorf("failed to create initialization vector %s", err) } - stream := cipher.NewCFBEncrypter(c.Block, iv) + stream := cipher.NewCFBEncrypter(c.Block, iv) //nolint:staticcheck stream.XORKeyStream(ciphertext[aes.BlockSize:], value) return ciphertext, nil } @@ -79,7 +79,7 @@ func (c *cfbCipher) Decrypt(ciphertext []byte) ([]byte, error) { iv, ciphertext := ciphertext[:aes.BlockSize], ciphertext[aes.BlockSize:] plaintext := make([]byte, len(ciphertext)) - stream := cipher.NewCFBDecrypter(c.Block, iv) + stream := cipher.NewCFBDecrypter(c.Block, iv) //nolint:staticcheck stream.XORKeyStream(plaintext, ciphertext) return plaintext, nil diff --git a/pkg/validation/sessions_test.go b/pkg/validation/sessions_test.go index 4934b649..6f590ac5 100644 --- a/pkg/validation/sessions_test.go +++ b/pkg/validation/sessions_test.go @@ -191,8 +191,10 @@ var _ = Describe("Sessions", func() { invalidPasswordDelMsg = "unable to delete the redis initialization key: WRONGPASS invalid username-password pair" unreachableRedisSetMsg = "unable to set a redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused" unreachableRedisDelMsg = "unable to delete the redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused" - unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable" - unrechableSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable" + unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" + unrechableSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" + refusedSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" + refusedSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" ) type redisStoreTableInput struct { @@ -389,7 +391,7 @@ var _ = Describe("Sessions", func() { }, }, }, - errStrings: []string{unreachableSentinelSetMsg, unrechableSentinelDelMsg}, + errStrings: []string{refusedSentinelSetMsg, refusedSentinelDelMsg}, }), Entry("sentinel and cluster both enabled fails", &redisStoreTableInput{ opts: &options.Options{ From c4a02ecc9538f79e479b9a958becd3cf5cd82aed Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 21:59:56 +0200 Subject: [PATCH 043/130] chore(deps): update dependency golangci/golangci-lint to v2.2.2 (#3111) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b4061f91..906b5eb5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.1.6 + GOLANGCI_LINT_VERSION: v2.2.2 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 61c61e32..9ebf4b6c 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.1.6 + GOLANGCI_LINT_VERSION: v2.2.2 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter From d39087794559409c69e42741efa117656b070e4a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 22:00:12 +0200 Subject: [PATCH 044/130] chore(deps): update dependency @easyops-cn/docusaurus-search-local to ^0.51.0 (#3098) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- docs/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/package.json b/docs/package.json index 17fa4352..33f3394b 100644 --- a/docs/package.json +++ b/docs/package.json @@ -17,7 +17,7 @@ "@docusaurus/core": "^3.3.2", "@docusaurus/preset-classic": "^3.3.2", "@docusaurus/theme-mermaid": "^3.3.2", - "@easyops-cn/docusaurus-search-local": "^0.49.0", + "@easyops-cn/docusaurus-search-local": "^0.51.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.0.0", "prism-react-renderer": "^2.3.0", From 40f3ef1ea5b0a5e78313fb6d4cb1a9aad94a00bd Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 22:04:11 +0200 Subject: [PATCH 045/130] chore(deps): update example docker-compose files (#3096) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 8097a186..ae1047c0 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -42,7 +42,7 @@ services: - httpbin.localtest.me gitea: - image: gitea/gitea:1.23.8 + image: gitea/gitea:1.24.2 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index d814739c..fb90ff28 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -41,7 +41,7 @@ services: depends_on: - oauth2-proxy container_name: nginx - image: nginx:1.28 + image: nginx:1.29 restart: unless-stopped ports: - 80:80/tcp diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index bdfdf785..65df58f0 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.24 + image: traefik:v2.11.27 volumes: - "./traefik:/etc/traefik" ports: From b05bdc0fbd3f36a741326e7d705522016a263c01 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 22:06:39 +0200 Subject: [PATCH 046/130] chore(deps): update helm examples (#2951) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/kubernetes/Chart.lock | 8 ++++---- contrib/local-environment/kubernetes/Chart.yaml | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/local-environment/kubernetes/Chart.lock b/contrib/local-environment/kubernetes/Chart.lock index 8fcaa577..dc2ef242 100644 --- a/contrib/local-environment/kubernetes/Chart.lock +++ b/contrib/local-environment/kubernetes/Chart.lock @@ -1,15 +1,15 @@ dependencies: - name: dex repository: https://charts.dexidp.io - version: 0.20.0 + version: 0.23.0 - name: oauth2-proxy repository: https://oauth2-proxy.github.io/manifests - version: 7.10.2 + version: 7.12.19 - name: httpbin repository: https://conservis.github.io/helm-charts version: 1.1.0 - name: hello-world repository: https://conservis.github.io/helm-charts version: 1.1.0 -digest: sha256:d4c13dc7cfeb95a6a35d481d846fcfec23de5e7f0dc90ad8c66bba1eb8922d13 -generated: "2025-01-30T11:31:39.156062012Z" +digest: sha256:8d1d166c7c1043edd2006bb8e8d2db32a6b876febad2854253570d7ea141f064 +generated: "2025-07-13T20:04:55.152622641Z" diff --git a/contrib/local-environment/kubernetes/Chart.yaml b/contrib/local-environment/kubernetes/Chart.yaml index bc3ddbdd..dd0938b3 100644 --- a/contrib/local-environment/kubernetes/Chart.yaml +++ b/contrib/local-environment/kubernetes/Chart.yaml @@ -3,10 +3,10 @@ description: K8S example based on https://kind.sigs.k8s.io name: kubernetes dependencies: - name: dex - version: 0.20.0 + version: 0.23.0 repository: https://charts.dexidp.io - name: oauth2-proxy - version: &chartVersion 7.10.2 + version: &chartVersion 7.12.19 repository: https://oauth2-proxy.github.io/manifests # https://github.com/postmanlabs/httpbin/issues/549 is still in progress, for now using a non-official chart - name: httpbin From 6c30a3c70b87bb8fdc86af21d3e71b7a16fb9b22 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 22:07:21 +0200 Subject: [PATCH 047/130] chore(deps): update alpine base image to v3.22.0 (#3097) * chore(deps): update alpine docker tag to v3.22.0 * add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + Makefile | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 013f32b5..a9d1f524 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#3072](https://github.com/oauth2-proxy/oauth2-proxy/pull/3072) feat: support for multiple github orgs #3072 (@daniel-mersch) - [#3116](https://github.com/oauth2-proxy/oauth2-proxy/pull/3116) feat: bump to go1.24.5 and full dependency update (@wardviaene / @dolmen) +- [#3097](https://github.com/oauth2-proxy/oauth2-proxy/pull/3097) chore(deps): update alpine base image to v3.22.0 # V7.9.0 diff --git a/Makefile b/Makefile index 870f1d2d..f6128c0c 100644 --- a/Makefile +++ b/Makefile @@ -67,7 +67,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM} DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x -DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.21.3 +DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.0 DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS} DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push From 0e1dc9bb84a63c67d06d19e03779f74e213c0cf0 Mon Sep 17 00:00:00 2001 From: Daniel Givens <1581675+dgivens@users.noreply.github.com> Date: Thu, 17 Jul 2025 02:23:28 -0500 Subject: [PATCH 048/130] fix: return error for empty Redis URL list (#3101) * fix: return error for empty Redis URL list * add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/sessions/redis/redis_store.go | 4 + pkg/sessions/redis/redis_store_test.go | 309 ++++++++++++++----------- 3 files changed, 174 insertions(+), 140 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a9d1f524..72d615e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#3072](https://github.com/oauth2-proxy/oauth2-proxy/pull/3072) feat: support for multiple github orgs #3072 (@daniel-mersch) - [#3116](https://github.com/oauth2-proxy/oauth2-proxy/pull/3116) feat: bump to go1.24.5 and full dependency update (@wardviaene / @dolmen) - [#3097](https://github.com/oauth2-proxy/oauth2-proxy/pull/3097) chore(deps): update alpine base image to v3.22.0 +- [#3101](https://github.com/oauth2-proxy/oauth2-proxy/pull/3101) fix: return error for empty Redis URL list (@dgivens) # V7.9.0 diff --git a/pkg/sessions/redis/redis_store.go b/pkg/sessions/redis/redis_store.go index e41a1e1f..18d79b80 100644 --- a/pkg/sessions/redis/redis_store.go +++ b/pkg/sessions/redis/redis_store.go @@ -218,6 +218,10 @@ func setupTLSConfig(opts options.RedisStoreOptions, opt *redis.Options) error { // parseRedisURLs parses a list of redis urls and returns a list // of addresses in the form of host:port and redis.Options that can be used to connect to Redis func parseRedisURLs(urls []string) ([]string, *redis.Options, error) { + if len(urls) == 0 { + return nil, nil, fmt.Errorf("unable to parse redis urls: no redis urls provided") + } + addrs := []string{} var redisOptions *redis.Options for _, u := range urls { diff --git a/pkg/sessions/redis/redis_store_test.go b/pkg/sessions/redis/redis_store_test.go index 0c0c5106..1bff6855 100644 --- a/pkg/sessions/redis/redis_store_test.go +++ b/pkg/sessions/redis/redis_store_test.go @@ -19,116 +19,41 @@ const ( ) var _ = Describe("Redis SessionStore Tests", func() { - // helper interface to allow us to close client connections - // All non-nil redis clients should implement this - type closer interface { - Close() error - } - - var mr *miniredis.Miniredis - var ss sessionsapi.SessionStore - - BeforeEach(func() { - var err error - mr, err = miniredis.Run() - Expect(err).ToNot(HaveOccurred()) - }) - - AfterEach(func() { - mr.Close() - }) - - JustAfterEach(func() { - // Release any connections immediately after the test ends - if redisManager, ok := ss.(*persistence.Manager); ok { - if redisManager.Store.(*SessionStore).Client != nil { - Expect(redisManager.Store.(*SessionStore).Client.(closer).Close()).To(Succeed()) - } + Describe("Redis SessionStore Creation", func() { + // helper interface to allow us to close client connections + // All non-nil redis clients should implement this + type closer interface { + Close() error } - }) - const redisProtocol = "redis://" - tests.RunSessionStoreTests( - func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - // Set the connection URL - opts.Type = options.RedisSessionStoreType - opts.Redis.ConnectionURL = redisProtocol + mr.Addr() + var mr *miniredis.Miniredis + var ss sessionsapi.SessionStore - // Capture the session store so that we can close the client + BeforeEach(func() { var err error - ss, err = NewRedisSessionStore(opts, cookieOpts) - return ss, err - }, - func(d time.Duration) error { - mr.FastForward(d) - return nil - }, - ) - - Context("with sentinel", func() { - var ms *minisentinel.Sentinel - - BeforeEach(func() { - ms = minisentinel.NewSentinel(mr) - Expect(ms.Start()).To(Succeed()) - }) - - tests.RunSessionStoreTests( - func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - // Set the sentinel connection URL - sentinelAddr := redisProtocol + ms.Addr() - opts.Type = options.RedisSessionStoreType - opts.Redis.SentinelConnectionURLs = []string{sentinelAddr} - opts.Redis.UseSentinel = true - opts.Redis.SentinelMasterName = ms.MasterInfo().Name - - // Capture the session store so that we can close the client - var err error - ss, err = NewRedisSessionStore(opts, cookieOpts) - return ss, err - }, - func(d time.Duration) error { - mr.FastForward(d) - return nil - }, - ) - }) - - Context("with cluster", func() { - tests.RunSessionStoreTests( - func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - clusterAddr := redisProtocol + mr.Addr() - opts.Type = options.RedisSessionStoreType - opts.Redis.ClusterConnectionURLs = []string{clusterAddr} - opts.Redis.UseCluster = true - - // Capture the session store so that we can close the client - var err error - ss, err = NewRedisSessionStore(opts, cookieOpts) - return ss, err - }, - func(d time.Duration) error { - mr.FastForward(d) - return nil - }, - ) - }) - - Context("with a redis password", func() { - BeforeEach(func() { - mr.RequireAuth(redisPassword) + mr, err = miniredis.Run() + Expect(err).ToNot(HaveOccurred()) }) AfterEach(func() { - mr.RequireAuth("") + mr.Close() }) + JustAfterEach(func() { + // Release any connections immediately after the test ends + if redisManager, ok := ss.(*persistence.Manager); ok { + if redisManager.Store.(*SessionStore).Client != nil { + Expect(redisManager.Store.(*SessionStore).Client.(closer).Close()).To(Succeed()) + } + } + }) + + const redisProtocol = "redis://" tests.RunSessionStoreTests( func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { // Set the connection URL opts.Type = options.RedisSessionStoreType opts.Redis.ConnectionURL = redisProtocol + mr.Addr() - opts.Redis.Password = redisPassword // Capture the session store so that we can close the client var err error @@ -157,7 +82,6 @@ var _ = Describe("Redis SessionStore Tests", func() { opts.Redis.SentinelConnectionURLs = []string{sentinelAddr} opts.Redis.UseSentinel = true opts.Redis.SentinelMasterName = ms.MasterInfo().Name - opts.Redis.Password = redisPassword // Capture the session store so that we can close the client var err error @@ -178,6 +102,33 @@ var _ = Describe("Redis SessionStore Tests", func() { opts.Type = options.RedisSessionStoreType opts.Redis.ClusterConnectionURLs = []string{clusterAddr} opts.Redis.UseCluster = true + + // Capture the session store so that we can close the client + var err error + ss, err = NewRedisSessionStore(opts, cookieOpts) + return ss, err + }, + func(d time.Duration) error { + mr.FastForward(d) + return nil + }, + ) + }) + + Context("with a redis password", func() { + BeforeEach(func() { + mr.RequireAuth(redisPassword) + }) + + AfterEach(func() { + mr.RequireAuth("") + }) + + tests.RunSessionStoreTests( + func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { + // Set the connection URL + opts.Type = options.RedisSessionStoreType + opts.Redis.ConnectionURL = redisProtocol + mr.Addr() opts.Redis.Password = redisPassword // Capture the session store so that we can close the client @@ -190,56 +141,134 @@ var _ = Describe("Redis SessionStore Tests", func() { return nil }, ) + + Context("with sentinel", func() { + var ms *minisentinel.Sentinel + + BeforeEach(func() { + ms = minisentinel.NewSentinel(mr) + Expect(ms.Start()).To(Succeed()) + }) + + tests.RunSessionStoreTests( + func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { + // Set the sentinel connection URL + sentinelAddr := redisProtocol + ms.Addr() + opts.Type = options.RedisSessionStoreType + opts.Redis.SentinelConnectionURLs = []string{sentinelAddr} + opts.Redis.UseSentinel = true + opts.Redis.SentinelMasterName = ms.MasterInfo().Name + opts.Redis.Password = redisPassword + + // Capture the session store so that we can close the client + var err error + ss, err = NewRedisSessionStore(opts, cookieOpts) + return ss, err + }, + func(d time.Duration) error { + mr.FastForward(d) + return nil + }, + ) + }) + + Context("with cluster", func() { + tests.RunSessionStoreTests( + func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { + clusterAddr := redisProtocol + mr.Addr() + opts.Type = options.RedisSessionStoreType + opts.Redis.ClusterConnectionURLs = []string{clusterAddr} + opts.Redis.UseCluster = true + opts.Redis.Password = redisPassword + + // Capture the session store so that we can close the client + var err error + ss, err = NewRedisSessionStore(opts, cookieOpts) + return ss, err + }, + func(d time.Duration) error { + mr.FastForward(d) + return nil + }, + ) + }) + }) + + Context("with a redis username and password", func() { + BeforeEach(func() { + mr.RequireUserAuth(redisUsername, redisPassword) + }) + + AfterEach(func() { + mr.RequireUserAuth("", "") + }) + + tests.RunSessionStoreTests( + func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { + // Set the connection URL + opts.Type = options.RedisSessionStoreType + opts.Redis.ConnectionURL = "redis://" + redisUsername + "@" + mr.Addr() + opts.Redis.Password = redisPassword + + // Capture the session store so that we can close the client + var err error + ss, err = NewRedisSessionStore(opts, cookieOpts) + return ss, err + }, + func(d time.Duration) error { + mr.FastForward(d) + return nil + }, + ) + + Context("with cluster", func() { + tests.RunSessionStoreTests( + func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { + clusterAddr := "redis://" + redisUsername + "@" + mr.Addr() + opts.Type = options.RedisSessionStoreType + opts.Redis.ClusterConnectionURLs = []string{clusterAddr} + opts.Redis.UseCluster = true + opts.Redis.Username = redisUsername + opts.Redis.Password = redisPassword + + // Capture the session store so that we can close the client + var err error + ss, err = NewRedisSessionStore(opts, cookieOpts) + return ss, err + }, + func(d time.Duration) error { + mr.FastForward(d) + return nil + }, + ) + }) }) }) - Context("with a redis username and password", func() { - BeforeEach(func() { - mr.RequireUserAuth(redisUsername, redisPassword) + Describe("Redis URL Parsing", func() { + It("should parse valid redis URL", func() { + addrs, opts, err := parseRedisURLs([]string{"redis://localhost:6379"}) + Expect(err).ToNot(HaveOccurred()) + Expect(addrs).To(Equal([]string{"localhost:6379"})) + Expect(opts).ToNot(BeNil()) + Expect(opts.Addr).To(Equal("localhost:6379")) }) - AfterEach(func() { - mr.RequireUserAuth("", "") + It("should return error for invalid redis URL", func() { + addrs, opts, err := parseRedisURLs([]string{"invalid://url"}) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("unable to parse redis url")) + Expect(err.Error()).To(Not(ContainSubstring("no redis urls provided"))) + Expect(addrs).To(BeNil()) + Expect(opts).To(BeNil()) }) - tests.RunSessionStoreTests( - func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - // Set the connection URL - opts.Type = options.RedisSessionStoreType - opts.Redis.ConnectionURL = "redis://" + redisUsername + "@" + mr.Addr() - opts.Redis.Password = redisPassword - - // Capture the session store so that we can close the client - var err error - ss, err = NewRedisSessionStore(opts, cookieOpts) - return ss, err - }, - func(d time.Duration) error { - mr.FastForward(d) - return nil - }, - ) - - Context("with cluster", func() { - tests.RunSessionStoreTests( - func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - clusterAddr := "redis://" + redisUsername + "@" + mr.Addr() - opts.Type = options.RedisSessionStoreType - opts.Redis.ClusterConnectionURLs = []string{clusterAddr} - opts.Redis.UseCluster = true - opts.Redis.Username = redisUsername - opts.Redis.Password = redisPassword - - // Capture the session store so that we can close the client - var err error - ss, err = NewRedisSessionStore(opts, cookieOpts) - return ss, err - }, - func(d time.Duration) error { - mr.FastForward(d) - return nil - }, - ) + It("should return error when no URLs provided", func() { + addrs, opts, err := parseRedisURLs([]string{}) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(Equal("unable to parse redis urls: no redis urls provided")) + Expect(addrs).To(BeNil()) + Expect(opts).To(BeNil()) }) }) }) From 07a388d17e985a3f4836f4df0aec8905e11db02f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 17 Jul 2025 07:56:01 +0000 Subject: [PATCH 049/130] add new docs version 7.10.x --- .../version-7.10.x/behaviour.md | 11 + .../version-7.10.x/community/contribution.md | 89 +++ .../version-7.10.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 564 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 318 ++++++++++ .../version-7.10.x/configuration/overview.md | 402 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 76 +++ .../configuration/providers/index.md | 43 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 ++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../version-7.10.x/configuration/sessions.md | 99 +++ .../configuration/systemd_socket.md | 43 ++ .../version-7.10.x/configuration/tls.md | 85 +++ .../version-7.10.x/features/endpoints.md | 47 ++ .../version-7.10.x/installation.md | 32 + docs/versioned_docs/version-7.10.x/welcome.md | 23 + .../version-7.10.x-sidebars.json | 83 +++ docs/versions.json | 1 + 32 files changed, 3039 insertions(+) create mode 100644 docs/versioned_docs/version-7.10.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.10.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.10.x/community/security.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.10.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.10.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.10.x/installation.md create mode 100644 docs/versioned_docs/version-7.10.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.10.x-sidebars.json diff --git a/docs/versioned_docs/version-7.10.x/behaviour.md b/docs/versioned_docs/version-7.10.x/behaviour.md new file mode 100644 index 00000000..e063d4f9 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/behaviour.md @@ -0,0 +1,11 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) +3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set +4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) + +Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). diff --git a/docs/versioned_docs/version-7.10.x/community/contribution.md b/docs/versioned_docs/version-7.10.x/community/contribution.md new file mode 100644 index 00000000..2cd330ac --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/community/contribution.md @@ -0,0 +1,89 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +This project is currently still using go 1.22. You can follow the installation guide for go [here.](https://go.dev/doc/install) And you can find go version 1.22 in the archived section [here.](https://go.dev/dl/) + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:4190 + diff --git a/docs/versioned_docs/version-7.10.x/community/security.md b/docs/versioned_docs/version-7.10.x/community/security.md new file mode 100644 index 00000000..c24b57d9 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md new file mode 100644 index 00000000..018a2941 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md @@ -0,0 +1,564 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### Duration +#### (`string` alias) + +(**Appears on:** [Upstream](#upstream)) + +Duration is as string representation of a period of time. +A duration string is a is a possibly signed sequence of decimal numbers, +each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md.tmpl new file mode 100644 index 00000000..8258201f --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.10.x/configuration/integration.md b/docs/versioned_docs/version-7.10.x/configuration/integration.md new file mode 100644 index 00000000..05d39281 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/integration.md @@ -0,0 +1,318 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. +Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. +Note that `nginxinc/kubernetes-ingress` does not include the Lua module. + +```yaml +nginx.ingress.kubernetes.io/auth-response-headers: Authorization +nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri +nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth +nginx.ingress.kubernetes.io/configuration-snippet: | + auth_request_set $name_upstream_1 $upstream_cookie_name_1; + + access_by_lua_block { + if ngx.var.name_upstream_1 ~= "" then + ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") + end + } +``` +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.10.x/configuration/overview.md b/docs/versioned_docs/version-7.10.x/configuration/overview.md new file mode 100644 index 00000000..bea70617 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/overview.md @@ -0,0 +1,402 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| -------------------------------------------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.10.x/configuration/providers/adfs.md new file mode 100644 index 00000000..ec8d72d2 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.10.x/configuration/providers/bitbucket.md new file mode 100644 index 00000000..e31de752 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.10.x/configuration/providers/digitalocean.md new file mode 100644 index 00000000..f6a1e891 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.10.x/configuration/providers/facebook.md new file mode 100644 index 00000000..352c95ce --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.10.x/configuration/providers/gitea.md new file mode 100644 index 00000000..996a5ddb --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea +--- + +:::note +This is not actually its own provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/github.md b/docs/versioned_docs/version-7.10.x/configuration/providers/github.md new file mode 100644 index 00000000..cebca314 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md new file mode 100644 index 00000000..4cdbbbe1 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/google.md b/docs/versioned_docs/version-7.10.x/configuration/providers/google.md new file mode 100644 index 00000000..e3e819ad --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/google.md @@ -0,0 +1,76 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.readonly + https://www.googleapis.com/auth/admin.directory.user.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/index.md b/docs/versioned_docs/version-7.10.x/configuration/providers/index.md new file mode 100644 index 00000000..b947c09b --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/index.md @@ -0,0 +1,43 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak.md new file mode 100644 index 00000000..11a1abca --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 00000000..b29096e3 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.10.x/configuration/providers/linkedin.md new file mode 100644 index 00000000..7d26ec43 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.10.x/configuration/providers/login_gov.md new file mode 100644 index 00000000..badbe48e --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 00000000..4feefc68 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md new file mode 100644 index 00000000..c5d9594e --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.10.x/configuration/providers/nextcloud.md new file mode 100644 index 00000000..85ebff03 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.10.x/configuration/providers/openid_connect.md new file mode 100644 index 00000000..de170058 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.10.x/configuration/sessions.md b/docs/versioned_docs/version-7.10.x/configuration/sessions.md new file mode 100644 index 00000000..e2037817 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.10.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.10.x/configuration/systemd_socket.md new file mode 100644 index 00000000..642e6f3f --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.10.x/configuration/tls.md b/docs/versioned_docs/version-7.10.x/configuration/tls.md new file mode 100644 index 00000000..68344b22 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.10.x/features/endpoints.md b/docs/versioned_docs/version-7.10.x/features/endpoints.md new file mode 100644 index 00000000..3ec1e2aa --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/features/endpoints.md @@ -0,0 +1,47 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.10.x/installation.md b/docs/versioned_docs/version-7.10.x/installation.md new file mode 100644 index 00000000..3b6919d8 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.9.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.10.x/welcome.md b/docs/versioned_docs/version-7.10.x/welcome.md new file mode 100644 index 00000000..7bceadd8 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.10.x-sidebars.json b/docs/versioned_sidebars/version-7.10.x-sidebars.json new file mode 100644 index 00000000..0dbf04bd --- /dev/null +++ b/docs/versioned_sidebars/version-7.10.x-sidebars.json @@ -0,0 +1,83 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index bdabb049..2b556795 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.10.x", "7.9.x", "7.8.x", "7.7.x", From 5808f5376a3d141df88ad57e18e341d7d0af5bdc Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 17 Jul 2025 07:56:01 +0000 Subject: [PATCH 050/130] update to release version v7.10.0 --- CHANGELOG.md | 10 ++++++++++ .../local-environment/docker-compose-alpha-config.yaml | 2 +- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-keycloak.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- docs/versioned_docs/version-7.10.x/installation.md | 2 +- 9 files changed, 18 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72d615e0..756f1bf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ ## Breaking Changes +## Changes since v7.10.0 + +# V7.10.0 + +## Release Highlights + +## Important Notes + +## Breaking Changes + ## Changes since v7.9.0 - [#3072](https://github.com/oauth2-proxy/oauth2-proxy/pull/3072) feat: support for multiple github orgs #3072 (@daniel-mersch) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 35608eb8..3acc01bf 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index ae1047c0..66a09b61 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 7d99a1e2..3a5a3914 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index fb90ff28..f9ec9f3d 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 65df58f0..e22c633d 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index ed79eab5..6f2321b7 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 3b6919d8..95da82da 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.9.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.10.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.10.x/installation.md b/docs/versioned_docs/version-7.10.x/installation.md index 3b6919d8..95da82da 100644 --- a/docs/versioned_docs/version-7.10.x/installation.md +++ b/docs/versioned_docs/version-7.10.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.9.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.10.0`) b. Using Go to install the latest release ```bash From e25f9ec9d789e40c032fae9f99a197a4bf144f52 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 17 Jul 2025 10:01:37 +0200 Subject: [PATCH 051/130] add changelog entry Signed-off-by: Jan Larwig --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 756f1bf1..479ab4ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,14 @@ # V7.10.0 ## Release Highlights +- 🏢 Support for multiple orgs using the GitHub / Gitea provider +- 🔵 Golang version upgrade to v1.24.5 +- 🕵️‍♀️ Vulnerabilities have been addressed + - [CVE-2025-4673](https://access.redhat.com/security/cve/CVE-2025-4673) + - [CVE-2025-22872](https://access.redhat.com/security/cve/CVE-2025-22872) + - [CVE-2025-09130](https://nvd.nist.gov/vuln/detail/CVE-2025-09130) + - [CVE-2025-22871](https://access.redhat.com/security/cve/CVE-2025-22871) +- 🐛 Squashed some bugs ## Important Notes From 313a2cb38ba31891fda1e42e7aeb663437662211 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:07:35 +0200 Subject: [PATCH 052/130] chore(deps): update dependency @easyops-cn/docusaurus-search-local to ^0.52.0 (#3131) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- docs/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/package.json b/docs/package.json index 33f3394b..bfedb21e 100644 --- a/docs/package.json +++ b/docs/package.json @@ -17,7 +17,7 @@ "@docusaurus/core": "^3.3.2", "@docusaurus/preset-classic": "^3.3.2", "@docusaurus/theme-mermaid": "^3.3.2", - "@easyops-cn/docusaurus-search-local": "^0.51.0", + "@easyops-cn/docusaurus-search-local": "^0.52.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.0.0", "prism-react-renderer": "^2.3.0", From 658256d5665080ef6ad890481e313ca35e039161 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:08:02 +0200 Subject: [PATCH 053/130] chore(deps): update gomod (#3132) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- go.mod | 10 +++++----- go.sum | 10 ++++++++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 087dad8a..044f2c23 100644 --- a/go.mod +++ b/go.mod @@ -15,8 +15,8 @@ require ( github.com/fsnotify/fsnotify v1.9.0 github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/go-jose/go-jose/v3 v3.0.4 - github.com/go-viper/mapstructure/v2 v2.3.0 - github.com/golang-jwt/jwt/v5 v5.2.2 + github.com/go-viper/mapstructure/v2 v2.4.0 + github.com/golang-jwt/jwt/v5 v5.2.3 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 @@ -29,7 +29,7 @@ require ( github.com/prometheus/client_golang v1.22.0 github.com/redis/go-redis/v9 v9.11.0 github.com/spf13/cast v1.9.2 - github.com/spf13/pflag v1.0.6 + github.com/spf13/pflag v1.0.7 github.com/spf13/viper v1.20.1 github.com/stretchr/testify v1.10.0 github.com/vmihailenco/msgpack/v5 v5.4.1 @@ -37,9 +37,9 @@ require ( golang.org/x/net v0.42.0 golang.org/x/oauth2 v0.30.0 golang.org/x/sync v0.16.0 - google.golang.org/api v0.241.0 + google.golang.org/api v0.242.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - k8s.io/apimachinery v0.33.2 + k8s.io/apimachinery v0.33.3 ) require ( diff --git a/go.sum b/go.sum index 22548221..caa8e2a0 100644 --- a/go.sum +++ b/go.sum @@ -63,8 +63,12 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk= github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang-jwt/jwt/v5 v5.2.3 h1:kkGXqQOBSDDWRhWNXTFpqGSCMyh/PLnqUvMGJPDJDs0= +github.com/golang-jwt/jwt/v5 v5.2.3/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY= @@ -140,6 +144,8 @@ github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M= +github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -247,6 +253,8 @@ google.golang.org/api v0.240.0 h1:PxG3AA2UIqT1ofIzWV2COM3j3JagKTKSwy7L6RHNXNU= google.golang.org/api v0.240.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= google.golang.org/api v0.241.0 h1:QKwqWQlkc6O895LchPEDUSYr22Xp3NCxpQRiWTB6avE= google.golang.org/api v0.241.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= +google.golang.org/api v0.242.0 h1:7Lnb1nfnpvbkCiZek6IXKdJ0MFuAZNAJKQfA1ws62xg= +google.golang.org/api v0.242.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 h1:1tXaIXCracvtsRxSBsYDiSBN0cuJvM7QYW+MrpIRY78= google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:49MsLSx0oWMOZqcpB3uL8ZOkAh1+TndpJ8ONoCBWiZk= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= @@ -274,3 +282,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= k8s.io/apimachinery v0.33.2 h1:IHFVhqg59mb8PJWTLi8m1mAoepkUNYmptHsV+Z1m5jY= k8s.io/apimachinery v0.33.2/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= +k8s.io/apimachinery v0.33.3 h1:4ZSrmNa0c/ZpZJhAgRdcsFcZOw1PQU1bALVQ0B3I5LA= +k8s.io/apimachinery v0.33.3/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= From c403d61d73edb2eb39ec3a9787254b5d0216008a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:08:23 +0200 Subject: [PATCH 054/130] chore(deps): update helm release oauth2-proxy to v7.14.1 (#3133) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/kubernetes/Chart.lock | 6 +++--- contrib/local-environment/kubernetes/Chart.yaml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/local-environment/kubernetes/Chart.lock b/contrib/local-environment/kubernetes/Chart.lock index dc2ef242..e6774fb2 100644 --- a/contrib/local-environment/kubernetes/Chart.lock +++ b/contrib/local-environment/kubernetes/Chart.lock @@ -4,12 +4,12 @@ dependencies: version: 0.23.0 - name: oauth2-proxy repository: https://oauth2-proxy.github.io/manifests - version: 7.12.19 + version: 7.14.1 - name: httpbin repository: https://conservis.github.io/helm-charts version: 1.1.0 - name: hello-world repository: https://conservis.github.io/helm-charts version: 1.1.0 -digest: sha256:8d1d166c7c1043edd2006bb8e8d2db32a6b876febad2854253570d7ea141f064 -generated: "2025-07-13T20:04:55.152622641Z" +digest: sha256:9b18e072db6863053c2967d023929ab4b9c03b6bd84f6529d90fe7a9ec5e315f +generated: "2025-07-20T08:56:43.559585022Z" diff --git a/contrib/local-environment/kubernetes/Chart.yaml b/contrib/local-environment/kubernetes/Chart.yaml index dd0938b3..3d224378 100644 --- a/contrib/local-environment/kubernetes/Chart.yaml +++ b/contrib/local-environment/kubernetes/Chart.yaml @@ -6,7 +6,7 @@ dependencies: version: 0.23.0 repository: https://charts.dexidp.io - name: oauth2-proxy - version: &chartVersion 7.12.19 + version: &chartVersion 7.14.1 repository: https://oauth2-proxy.github.io/manifests # https://github.com/postmanlabs/httpbin/issues/549 is still in progress, for now using a non-official chart - name: httpbin From 20f561cf70a82fba586954b097efe95cc03010f7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:08:44 +0200 Subject: [PATCH 055/130] chore(deps): update docker-compose (#3130) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 66a09b61..454d0123 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -42,7 +42,7 @@ services: - httpbin.localtest.me gitea: - image: gitea/gitea:1.24.2 + image: gitea/gitea:1.24.3 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index f9ec9f3d..45dcad84 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -81,7 +81,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.0 + image: gcr.io/etcd-development/etcd:v3.6.2 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 6f2321b7..d79ee292 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -55,7 +55,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.0 + image: gcr.io/etcd-development/etcd:v3.6.2 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From d5f8507cc863c1ba4d699f635c6340078dda4857 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:37:45 +0200 Subject: [PATCH 056/130] chore(deps): update alpine docker tag to v3.22.1 (#3129) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index f6128c0c..091ca726 100644 --- a/Makefile +++ b/Makefile @@ -67,7 +67,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM} DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x -DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.0 +DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.1 DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS} DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push From b57c82181d8d626d91ab72b42abea01e2049138a Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 20 Jul 2025 16:44:42 +0200 Subject: [PATCH 057/130] feat(cookie) csrf per request limit (#3134) * Allow setting maximum number of csrf cookies, deleting the oldest if necessary * Add a test for multiple CSRF cookies to remove the old cookie * Add docs/changelog * If limit is <=0 do not clear Signed-off-by: test * Better docs Co-authored-by: Jan Larwig * direct check of option value Co-authored-by: Jan Larwig * direct use of option value Co-authored-by: Jan Larwig * sort based on clock compare vs time compare Co-authored-by: Jan Larwig * clock.Clock does not implement Compare, fix csrf cookie extraction after rename Signed-off-by: Bert Helderman * Linter fix * add method signature documentation and slight formatting Signed-off-by: Jan Larwig * fix: test case for csrf cookie limit and flag Signed-off-by: Jan Larwig --------- Signed-off-by: Bert Helderman Signed-off-by: Jan Larwig Co-authored-by: test Co-authored-by: bh-tt <71650427+bh-tt@users.noreply.github.com> --- CHANGELOG.md | 2 + docs/docs/configuration/overview.md | 84 ++++++++++++++-------------- oauthproxy.go | 3 +- pkg/apis/options/cookie.go | 24 ++++---- pkg/cookies/csrf.go | 50 ++++++++++++++++- pkg/cookies/csrf_per_request_test.go | 79 ++++++++++++++++++++++++++ 6 files changed, 186 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 479ab4ce..d8cd1865 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.10.0 +- [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) + # V7.10.0 ## Release Highlights diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index bea70617..6a8f52e5 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -71,6 +71,7 @@ An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/ | `--config` | path to config file | | `--version` | print version string | + ### General Provider Options Provider specific options can be found on their respective subpages. @@ -91,7 +92,7 @@ Provider specific options can be found on their respective subpages. | flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | | flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | | flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | -| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | | flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | | flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | | flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | @@ -114,19 +115,20 @@ Provider specific options can be found on their respective subpages. ### Cookie Options -| Flag / Config Field | Type | Description | Default | -| -------------------------------------------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | -| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | -| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | -| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | -| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | -| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | -| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | -| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | -| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | -| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | -| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | -| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | [^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) @@ -188,33 +190,33 @@ Provider specific options can be found on their respective subpages. ### Proxy Options -| Flag / Config Field | Type | Description | Default | -| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | -| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | -| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | -| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | -| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | -| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | -| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | -| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | -| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | -| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | -| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | -| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | -| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | -| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | -| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | -| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | -| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | -| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | -| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | -| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | -| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | -| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | -| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | [^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. diff --git a/oauthproxy.go b/oauthproxy.go index b85c89b4..a35e08ac 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -845,13 +845,12 @@ func (p *OAuthProxy) doOAuthStart(rw http.ResponseWriter, req *http.Request, ove csrf.HashOIDCNonce(), extraParams, ) - + cookies.ClearExtraCsrfCookies(p.CookieOptions, rw, req) if _, err := csrf.SetCookie(rw, req); err != nil { logger.Errorf("Error setting CSRF cookie: %v", err) p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error()) return } - http.Redirect(rw, req, loginURL, http.StatusFound) } diff --git a/pkg/apis/options/cookie.go b/pkg/apis/options/cookie.go index 6917bdc5..22b74a6c 100644 --- a/pkg/apis/options/cookie.go +++ b/pkg/apis/options/cookie.go @@ -8,17 +8,18 @@ import ( // Cookie contains configuration options relating to Cookie configuration type Cookie struct { - Name string `flag:"cookie-name" cfg:"cookie_name"` - Secret string `flag:"cookie-secret" cfg:"cookie_secret"` - Domains []string `flag:"cookie-domain" cfg:"cookie_domains"` - Path string `flag:"cookie-path" cfg:"cookie_path"` - Expire time.Duration `flag:"cookie-expire" cfg:"cookie_expire"` - Refresh time.Duration `flag:"cookie-refresh" cfg:"cookie_refresh"` - Secure bool `flag:"cookie-secure" cfg:"cookie_secure"` - HTTPOnly bool `flag:"cookie-httponly" cfg:"cookie_httponly"` - SameSite string `flag:"cookie-samesite" cfg:"cookie_samesite"` - CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"` - CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"` + Name string `flag:"cookie-name" cfg:"cookie_name"` + Secret string `flag:"cookie-secret" cfg:"cookie_secret"` + Domains []string `flag:"cookie-domain" cfg:"cookie_domains"` + Path string `flag:"cookie-path" cfg:"cookie_path"` + Expire time.Duration `flag:"cookie-expire" cfg:"cookie_expire"` + Refresh time.Duration `flag:"cookie-refresh" cfg:"cookie_refresh"` + Secure bool `flag:"cookie-secure" cfg:"cookie_secure"` + HTTPOnly bool `flag:"cookie-httponly" cfg:"cookie_httponly"` + SameSite string `flag:"cookie-samesite" cfg:"cookie_samesite"` + CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"` + CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"` + CSRFPerRequestLimit int `flag:"cookie-csrf-per-request-limit" cfg:"cookie_csrf_per_request_limit"` } func cookieFlagSet() *pflag.FlagSet { @@ -34,6 +35,7 @@ func cookieFlagSet() *pflag.FlagSet { flagSet.Bool("cookie-httponly", true, "set HttpOnly cookie flag") flagSet.String("cookie-samesite", "", "set SameSite cookie attribute (ie: \"lax\", \"strict\", \"none\", or \"\"). ") flagSet.Bool("cookie-csrf-per-request", false, "When this property is set to true, then the CSRF cookie name is built based on the state and varies per request. If property is set to false, then CSRF cookie has the same name for all requests.") + flagSet.Int("cookie-csrf-per-request-limit", 0, "Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookies will be removed. Useful if users end up with 431 Request headers too large status codes.") flagSet.Duration("cookie-csrf-expire", time.Duration(15)*time.Minute, "expire timeframe for CSRF cookie") return flagSet } diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go index 698a7c8d..eab87869 100644 --- a/pkg/cookies/csrf.go +++ b/pkg/cookies/csrf.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "net/http" + "slices" + "strings" "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" @@ -151,6 +153,48 @@ func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cooki return cookie, nil } +// ClearExtraCsrfCookies limits the amount of existing CSRF cookies by deleting +// an excess of cookies controlled through the option CSRFPerRequestLimit +func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *http.Request) { + if !opts.CSRFPerRequest || opts.CSRFPerRequestLimit <= 0 { + return + } + + cookies := req.Cookies() + existingCsrfCookies := []*http.Cookie{} + startsWith := fmt.Sprintf("%v_", opts.Name) + + // determine how many csrf cookies we have + for _, cookie := range cookies { + if strings.HasPrefix(cookie.Name, startsWith) && strings.HasSuffix(cookie.Name, "_csrf") { + existingCsrfCookies = append(existingCsrfCookies, cookie) + } + } + + // short circuit return + if len(existingCsrfCookies) <= opts.CSRFPerRequestLimit { + return + } + + decodedCookies := []*csrf{} + for _, cookie := range existingCsrfCookies { + decodedCookie, err := decodeCSRFCookie(cookie, opts) + if err != nil { + continue + } + decodedCookies = append(decodedCookies, decodedCookie) + } + + // delete the X oldest cookies + slices.SortStableFunc(decodedCookies, func(a, b *csrf) int { + return a.time.Now().Compare(b.time.Now()) + }) + + for i := 0; i < len(decodedCookies)-opts.CSRFPerRequestLimit; i++ { + decodedCookies[i].ClearCookie(rw, req) + } +} + // ClearCookie removes the CSRF cookie func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) { http.SetCookie(rw, MakeCookieFromOptions( @@ -181,7 +225,7 @@ func (c *csrf) encodeCookie() (string, error) { // decodeCSRFCookie validates the signature then decrypts and decodes a CSRF // cookie into a CSRF struct func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) { - val, _, ok := encryption.Validate(cookie, opts.Secret, opts.Expire) + val, t, ok := encryption.Validate(cookie, opts.Secret, opts.Expire) if !ok { return nil, errors.New("CSRF cookie failed validation") } @@ -192,7 +236,9 @@ func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) } // Valid cookie, Unmarshal the CSRF - csrf := &csrf{cookieOpts: opts} + clock := clock.Clock{} + clock.Set(t) + csrf := &csrf{cookieOpts: opts, time: clock} err = msgpack.Unmarshal(decrypted, csrf) if err != nil { return nil, fmt.Errorf("error unmarshalling data to CSRF: %v", err) diff --git a/pkg/cookies/csrf_per_request_test.go b/pkg/cookies/csrf_per_request_test.go index 28e2e296..9b7d4e59 100644 --- a/pkg/cookies/csrf_per_request_test.go +++ b/pkg/cookies/csrf_per_request_test.go @@ -190,5 +190,84 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { Expect(privateCSRF.cookieName()).To(ContainSubstring(cookieName)) }) }) + + Context("CSRF per request limit", func() { + It("clears cookies based on the limit", func() { + //needs to be now as pkg/encryption/utils.go uses time.Now() + testNow := time.Now() + cookieOpts.CSRFPerRequestLimit = 1 + + publicCSRF1, err := NewCSRF(cookieOpts, "verifier") + Expect(err).ToNot(HaveOccurred()) + privateCSRF1 := publicCSRF1.(*csrf) + privateCSRF1.time.Set(testNow) + + publicCSRF2, err := NewCSRF(cookieOpts, "verifier") + Expect(err).ToNot(HaveOccurred()) + privateCSRF2 := publicCSRF2.(*csrf) + privateCSRF2.time.Set(testNow.Add(time.Minute)) + + publicCSRF3, err := NewCSRF(cookieOpts, "verifier") + Expect(err).ToNot(HaveOccurred()) + privateCSRF3 := publicCSRF3.(*csrf) + privateCSRF3.time.Set(testNow.Add(time.Minute * 2)) + + cookies := []string{} + for _, csrf := range []*csrf{privateCSRF1, privateCSRF2, privateCSRF3} { + encoded, err := csrf.encodeCookie() + Expect(err).ToNot(HaveOccurred()) + cookie := MakeCookieFromOptions( + req, + csrf.cookieName(), + encoded, + csrf.cookieOpts, + csrf.cookieOpts.CSRFExpire, + ) + cookies = append(cookies, fmt.Sprintf("%v=%v", cookie.Name, cookie.Value)) + } + + header := make(map[string][]string, 1) + header["Cookie"] = cookies + req = &http.Request{ + Method: http.MethodGet, + Proto: "HTTP/1.1", + Host: cookieDomain, + + URL: &url.URL{ + Scheme: "https", + Host: cookieDomain, + Path: cookiePath, + }, + Header: header, + } + + // when setting the limit to one csrf cookie but configuring three csrf cookies + // then two cookies should be removed / set to expired on the response + + // for this test case we have set all the cookies on a single request, + // but in reality this will be multiple requests after another + rw := httptest.NewRecorder() + ClearExtraCsrfCookies(cookieOpts, rw, req) + + clearedCookies := rw.Header()["Set-Cookie"] + Expect(clearedCookies).To(HaveLen(2)) + Expect(clearedCookies[0]).To(Equal( + fmt.Sprintf( + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure", + privateCSRF1.cookieName(), + cookiePath, + cookieDomain, + ), + )) + Expect(clearedCookies[1]).To(Equal( + fmt.Sprintf( + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure", + privateCSRF2.cookieName(), + cookiePath, + cookieDomain, + ), + )) + }) + }) }) }) From 5e7f14bdcbbd22702c7b5de907398e94012bab2a Mon Sep 17 00:00:00 2001 From: Johann <76482511+Primexz@users.noreply.github.com> Date: Sun, 20 Jul 2025 17:17:24 +0200 Subject: [PATCH 058/130] fix: show login page on broken session cookie (#2605) * fix: redirect on invalid cookie * docs: update changelog * chore: remove duplicated code * fix: status code handling if wrong http method is used --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + oauthproxy.go | 10 ++++------ 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8cd1865..35685b7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.10.0 - [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) +- [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) # V7.10.0 diff --git a/oauthproxy.go b/oauthproxy.go index a35e08ac..d8984cde 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -633,12 +633,6 @@ func (p *OAuthProxy) isTrustedIP(req *http.Request) bool { // SignInPage writes the sign in template to the response func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code int) { prepareNoCache(rw) - err := p.ClearSessionCookie(rw, req) - if err != nil { - logger.Printf("Error clearing session cookie: %v", err) - p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error()) - return - } rw.WriteHeader(code) redirectURL, err := p.appDirector.GetRedirect(req) @@ -652,6 +646,10 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code redirectURL = "/" } + if err := p.ClearSessionCookie(rw, req); err != nil { + logger.Printf("Error clearing session cookie: %v", err) + } + p.pageWriter.WriteSignInPage(rw, req, redirectURL, code) } From 3ac834dbcfbb06de1b5168eb6397835f6f6538bb Mon Sep 17 00:00:00 2001 From: Simmo Saan Date: Sun, 20 Jul 2025 21:32:50 +0300 Subject: [PATCH 059/130] Fix local-environment ports (#3136) * Change Dex port in local-environment from 4190 to 5556 Port 4190 is blocked by standards-compliant browsers (e.g. Firefox), as per https://fetch.spec.whatwg.org/#port-blocking. Port 5556 is used by Dex in its example config files: https://github.com/dexidp/dex/blob/745e1114f341e849f3b0edde45b39c14017deaf8/examples/config-dev.yaml#L50 * Fix upstream in local-environment/oauth2-proxy.cfg http://httpbin.localtest.me:8080 is only exposed to the host, not to httpbin Docker network. Causes Bad Gateway before. * Do not expose unauthenticated httpbin service in local-environment This defeats the point of having oauth2-proxy. It has already been misleading by causing the bug fixed in cafc6af48fc38f6fe4395fb0c7e2638bc84e6091. It serves as a bad example: users might accidentally expose the service they're trying to protect in the first place. * Remove unnecessary httpbin.localtest.me alias from local-environment --- contrib/local-environment/dex.yaml | 6 +++--- contrib/local-environment/docker-compose-gitea.yaml | 7 ++----- contrib/local-environment/docker-compose-keycloak.yaml | 7 ++----- contrib/local-environment/docker-compose-nginx.yaml | 9 +++------ contrib/local-environment/docker-compose.yaml | 9 +++------ contrib/local-environment/oauth2-proxy-alpha-config.yaml | 2 +- contrib/local-environment/oauth2-proxy-keycloak.cfg | 2 +- contrib/local-environment/oauth2-proxy-nginx.cfg | 2 +- contrib/local-environment/oauth2-proxy-traefik.cfg | 4 ++-- contrib/local-environment/oauth2-proxy.cfg | 4 ++-- docs/docs/community/contribution.md | 2 +- .../version-7.10.x/community/contribution.md | 2 +- 12 files changed, 22 insertions(+), 34 deletions(-) diff --git a/contrib/local-environment/dex.yaml b/contrib/local-environment/dex.yaml index fd64152b..f0a2ead4 100644 --- a/contrib/local-environment/dex.yaml +++ b/contrib/local-environment/dex.yaml @@ -1,7 +1,7 @@ # This configuration is intended to be used with the docker-compose testing # environment. -# This should configure Dex to run on port 4190 and provides a static login -issuer: http://dex.localtest.me:4190/dex +# This should configure Dex to run on port 5556 and provides a static login +issuer: http://dex.localtest.me:5556/dex storage: type: etcd config: @@ -9,7 +9,7 @@ storage: - http://etcd:2379 namespace: dex/ web: - http: 0.0.0.0:4190 + http: 0.0.0.0:5556 oauth2: skipApprovalScreen: true expiry: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 454d0123..c3236084 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -34,12 +34,9 @@ services: container_name: httpbin image: kennethreitz/httpbin:latest hostname: httpbin - ports: - - 8080:80 + ports: [] networks: - httpbin: - aliases: - - httpbin.localtest.me + httpbin: {} gitea: image: gitea/gitea:1.24.3 diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 3a5a3914..66a2d011 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -34,12 +34,9 @@ services: container_name: httpbin image: kennethreitz/httpbin:latest hostname: httpbin - ports: - - 8080:80/tcp + ports: [] networks: - httpbin: - aliases: - - httpbin.localtest.me + httpbin: {} keycloak: container_name: keycloak diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 45dcad84..72f9d97a 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -62,7 +62,7 @@ services: - "./dex.yaml:/dex.yaml" restart: unless-stopped ports: - - 4190:4190/tcp + - 5556:4181/tcp networks: dex: aliases: @@ -73,12 +73,9 @@ services: httpbin: container_name: httpbin image: kennethreitz/httpbin - ports: - - 8080:80/tcp + ports: [] networks: - httpbin: - aliases: - - httpbin.localtest.me + httpbin: {} etcd: container_name: etcd image: gcr.io/etcd-development/etcd:v3.6.2 diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index d79ee292..3da4a9a6 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -36,7 +36,7 @@ services: - "./dex.yaml:/dex.yaml" restart: unless-stopped ports: - - 4190:4190/tcp + - 5556:4181/tcp networks: dex: aliases: @@ -47,12 +47,9 @@ services: httpbin: container_name: httpbin image: kennethreitz/httpbin - ports: - - 8080:80/tcp + ports: [] networks: - httpbin: - aliases: - - httpbin.localtest.me + httpbin: {} etcd: container_name: etcd image: gcr.io/etcd-development/etcd:v3.6.2 diff --git a/contrib/local-environment/oauth2-proxy-alpha-config.yaml b/contrib/local-environment/oauth2-proxy-alpha-config.yaml index 6a46e1b1..b2c9f6a8 100644 --- a/contrib/local-environment/oauth2-proxy-alpha-config.yaml +++ b/contrib/local-environment/oauth2-proxy-alpha-config.yaml @@ -20,4 +20,4 @@ providers: clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK clientID: oauth2-proxy oidcConfig: - issuerURL: http://dex.localhost:4190/dex + issuerURL: http://dex.localhost:5556/dex diff --git a/contrib/local-environment/oauth2-proxy-keycloak.cfg b/contrib/local-environment/oauth2-proxy-keycloak.cfg index 391ad331..8491b286 100644 --- a/contrib/local-environment/oauth2-proxy-keycloak.cfg +++ b/contrib/local-environment/oauth2-proxy-keycloak.cfg @@ -3,7 +3,7 @@ cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" email_domains="example.com" cookie_secure="false" upstreams="http://httpbin" -cookie_domains=["oauth2-proxy.localtest.me:4080", "httpbin.localtest.me:8080", "keycloak.localtest.me:9080"] # Required so cookie can be read on all subdomains. +cookie_domains=["oauth2-proxy.localtest.me:4080", "keycloak.localtest.me:9080"] # Required so cookie can be read on all subdomains. whitelist_domains=[".localtest.me"] # Required to allow redirection back to original requested target. # keycloak provider diff --git a/contrib/local-environment/oauth2-proxy-nginx.cfg b/contrib/local-environment/oauth2-proxy-nginx.cfg index e17eb311..01b64a55 100644 --- a/contrib/local-environment/oauth2-proxy-nginx.cfg +++ b/contrib/local-environment/oauth2-proxy-nginx.cfg @@ -2,7 +2,7 @@ http_address="0.0.0.0:4180" cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" provider="oidc" email_domains="example.com" -oidc_issuer_url="http://dex.localtest.me:4190/dex" +oidc_issuer_url="http://dex.localtest.me:5556/dex" client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" client_id="oauth2-proxy" cookie_secure="false" diff --git a/contrib/local-environment/oauth2-proxy-traefik.cfg b/contrib/local-environment/oauth2-proxy-traefik.cfg index 6357c383..8dce6752 100644 --- a/contrib/local-environment/oauth2-proxy-traefik.cfg +++ b/contrib/local-environment/oauth2-proxy-traefik.cfg @@ -2,7 +2,7 @@ http_address="0.0.0.0:4180" cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" provider="oidc" email_domains=["example.com"] -oidc_issuer_url="http://dex.localhost:4190/dex" +oidc_issuer_url="http://dex.localhost:5556/dex" client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" client_id="oauth2-proxy" cookie_secure="false" @@ -13,7 +13,7 @@ whitelist_domains=".oauth2-proxy.localhost" # Required to allow redirection back # Mandatory option when using oauth2-proxy with traefik reverse_proxy="true" -# Required for traefik with ForwardAuth and static upstream configuration +# Required for traefik with ForwardAuth and static upstream configuration upstreams="static://202" # The following option skip the page requesting the user # to click on a button to be redirected to the identity provider diff --git a/contrib/local-environment/oauth2-proxy.cfg b/contrib/local-environment/oauth2-proxy.cfg index ee58e145..dfa8b341 100644 --- a/contrib/local-environment/oauth2-proxy.cfg +++ b/contrib/local-environment/oauth2-proxy.cfg @@ -2,7 +2,7 @@ http_address="0.0.0.0:4180" cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" email_domains="example.com" cookie_secure="false" -upstreams="http://httpbin.localtest.me:8080" +upstreams="http://httpbin" cookie_domains=[".localtest.me"] # Required so cookie can be read on all subdomains. whitelist_domains=[".localtest.me"] # Required to allow redirection back to original requested target. @@ -11,6 +11,6 @@ client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" client_id="oauth2-proxy" redirect_url="http://oauth2-proxy.localtest.me:4180/oauth2/callback" -oidc_issuer_url="http://dex.localtest.me:4190/dex" +oidc_issuer_url="http://dex.localtest.me:5556/dex" provider="oidc" provider_display_name="Dex" diff --git a/docs/docs/community/contribution.md b/docs/docs/community/contribution.md index 2cd330ac..92255eda 100644 --- a/docs/docs/community/contribution.md +++ b/docs/docs/community/contribution.md @@ -85,5 +85,5 @@ The docker compose setups expose the services with a dynamic reverse DNS resolve - OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 - Upstream: http://httpbin.localtest.me:8080 -- Dex: http://dex.localtest.me:4190 +- Dex: http://dex.localtest.me:5556 diff --git a/docs/versioned_docs/version-7.10.x/community/contribution.md b/docs/versioned_docs/version-7.10.x/community/contribution.md index 2cd330ac..92255eda 100644 --- a/docs/versioned_docs/version-7.10.x/community/contribution.md +++ b/docs/versioned_docs/version-7.10.x/community/contribution.md @@ -85,5 +85,5 @@ The docker compose setups expose the services with a dynamic reverse DNS resolve - OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 - Upstream: http://httpbin.localtest.me:8080 -- Dex: http://dex.localtest.me:4190 +- Dex: http://dex.localtest.me:5556 From 4d17bc1d6834b62c49548b88eff3f8d2a666ef8d Mon Sep 17 00:00:00 2001 From: Bob Du Date: Mon, 21 Jul 2025 15:06:17 +0800 Subject: [PATCH 060/130] feat: allow use more possible google admin-sdk api scopes (#2743) * feat: Allow use more possible google admin-sdk api scopes. * reduce cognitive complexity Signed-off-by: Bob Du * remove unnecessary else block / indentation Signed-off-by: Jan Larwig * add changelog entry Signed-off-by: Jan Larwig * slight formatting and error message rephrasing Signed-off-by: Jan Larwig --------- Signed-off-by: Bob Du Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- .gitignore | 1 + CHANGELOG.md | 1 + docs/docs/configuration/providers/google.md | 7 +- providers/google.go | 87 +++++++++++++++------ 4 files changed, 69 insertions(+), 27 deletions(-) diff --git a/.gitignore b/.gitignore index e40acd52..a7ee4162 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ c.out # Folders _obj _test +.DS_Store .idea/ .vscode/* !/.vscode/tasks.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 35685b7a..2aa456e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) - [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) +- [#2743](https://github.com/oauth2-proxy/oauth2-proxy/pull/2743) feat: allow use more possible google admin-sdk api scopes (@BobDu) # V7.10.0 diff --git a/docs/docs/configuration/providers/google.md b/docs/docs/configuration/providers/google.md index e3e819ad..26af87ab 100644 --- a/docs/docs/configuration/providers/google.md +++ b/docs/docs/configuration/providers/google.md @@ -37,18 +37,17 @@ account is still authorized. #### Restrict auth to specific Google groups on your domain. (optional) -1. Create a [service account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount) and configure it +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, alternatively download the JSON. 2. Make note of the Client ID for a future step. 3. Under "APIs & Auth", choose APIs. 4. Click on Admin SDK and then Enable API. -5. Follow the steps on https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) and give the client id from step 2 the following oauth scopes: ``` - https://www.googleapis.com/auth/admin.directory.group.readonly - https://www.googleapis.com/auth/admin.directory.user.readonly + https://www.googleapis.com/auth/admin.directory.group.member.readonly ``` 6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. diff --git a/providers/google.go b/providers/google.go index 8b17d090..0e1e2156 100644 --- a/providers/google.go +++ b/providers/google.go @@ -229,38 +229,79 @@ func (p *GoogleProvider) setGroupRestriction(opts options.GoogleOptions) { } } -func getAdminService(opts options.GoogleOptions) *admin.Service { - ctx := context.Background() - var client *http.Client +// https://developers.google.com/admin-sdk/directory/reference/rest/v1/members/hasMember#authorization-scopes +var possibleScopesList = [...]string{ + admin.AdminDirectoryGroupMemberReadonlyScope, + admin.AdminDirectoryGroupReadonlyScope, + admin.AdminDirectoryGroupMemberScope, + admin.AdminDirectoryGroupScope, +} + +func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope string) oauth2.TokenSource { if opts.UseApplicationDefaultCredentials { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), - Scopes: []string{admin.AdminDirectoryGroupReadonlyScope, admin.AdminDirectoryUserReadonlyScope}, + Scopes: []string{scope}, Subject: opts.AdminEmail, }) if err != nil { logger.Fatal("failed to fetch application default credentials: ", err) } - client = oauth2.NewClient(ctx, ts) - } else { - credentialsReader, err := os.Open(opts.ServiceAccountJSON) - if err != nil { - logger.Fatal("couldn't open Google credentials file: ", err) - return nil - } - - data, err := io.ReadAll(credentialsReader) - if err != nil { - logger.Fatal("can't read Google credentials file:", err) - } - - conf, err := google.JWTConfigFromJSON(data, admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope) - if err != nil { - logger.Fatal("can't load Google credentials file:", err) - } - conf.Subject = opts.AdminEmail - client = conf.Client(ctx) + return ts } + + credentialsReader, err := os.Open(opts.ServiceAccountJSON) + if err != nil { + logger.Fatal("couldn't open Google credentials file: ", err) + } + + data, err := io.ReadAll(credentialsReader) + if err != nil { + logger.Fatal("can't read Google credentials file:", err) + } + + conf, err := google.JWTConfigFromJSON(data, scope) + if err != nil { + logger.Fatal("can't load Google credentials file:", err) + } + + conf.Subject = opts.AdminEmail + return conf.TokenSource(ctx) +} + +func getAdminService(opts options.GoogleOptions) *admin.Service { + ctx := context.Background() + var client *http.Client + + for _, scope := range possibleScopesList { + + ts := getOauth2TokenSource(ctx, opts, scope) + _, err := ts.Token() + + if err == nil { + client = oauth2.NewClient(ctx, ts) + break + } + + if retrieveErr, ok := err.(*oauth2.RetrieveError); ok { + retrieveErrBody := map[string]interface{}{} + + if err := json.Unmarshal(retrieveErr.Body, &retrieveErrBody); err != nil { + logger.Fatal("error unmarshalling retrieveErr body:", err) + } + + if retrieveErrBody["error"] == "unauthorized_client" && retrieveErrBody["error_description"] == "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested." { + continue + } + + logger.Fatal("error retrieving token:", err) + } + } + + if client == nil { + logger.Fatal("error: google credentials do not have enough permissions to access admin API scope") + } + adminService, err := admin.NewService(ctx, option.WithHTTPClient(client)) if err != nil { logger.Fatal(err) From a88306be980a4866edae676f8c976ab94f23eec6 Mon Sep 17 00:00:00 2001 From: Conrad Hoffmann <1226676+bitfehler@users.noreply.github.com> Date: Tue, 22 Jul 2025 08:16:32 +0200 Subject: [PATCH 061/130] feat: add SourceHut (sr.ht) provider (#2359) * Add SourceHut (sr.ht) provider * fix changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + .../docs/configuration/providers/sourcehut.md | 25 ++++ pkg/apis/options/providers.go | 3 + providers/providers.go | 5 +- providers/srht.go | 108 ++++++++++++++++++ providers/srht_test.go | 77 +++++++++++++ 6 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 docs/docs/configuration/providers/sourcehut.md create mode 100644 providers/srht.go create mode 100644 providers/srht_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 2aa456e2..b2ffc50d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) - [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) - [#2743](https://github.com/oauth2-proxy/oauth2-proxy/pull/2743) feat: allow use more possible google admin-sdk api scopes (@BobDu) +- [#2359](https://github.com/oauth2-proxy/oauth2-proxy/pull/2359) feat: add SourceHut (sr.ht) provider(@bitfehler) # V7.10.0 diff --git a/docs/docs/configuration/providers/sourcehut.md b/docs/docs/configuration/providers/sourcehut.md new file mode 100644 index 00000000..88d14622 --- /dev/null +++ b/docs/docs/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](#email-authentication). + diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 280b1ce0..ac5652ca 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -147,6 +147,9 @@ const ( // OIDCProvider is the provider type for OIDC OIDCProvider ProviderType = "oidc" + + // SourceHutProvider is the provider type for SourceHut + SourceHutProvider ProviderType = "sourcehut" ) type KeycloakOptions struct { diff --git a/providers/providers.go b/providers/providers.go index 3a125a24..8bc5ff88 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -67,6 +67,8 @@ func NewProvider(providerConfig options.Provider) (Provider, error) { return NewNextcloudProvider(providerData), nil case options.OIDCProvider: return NewOIDCProvider(providerData, providerConfig.OIDCConfig), nil + case options.SourceHutProvider: + return NewSourceHutProvider(providerData), nil default: return nil, fmt.Errorf("unknown provider type %q", providerConfig.Type) } @@ -183,7 +185,8 @@ func parseCodeChallengeMethod(providerConfig options.Provider) string { func providerRequiresOIDCProviderVerifier(providerType options.ProviderType) (bool, error) { switch providerType { case options.BitbucketProvider, options.DigitalOceanProvider, options.FacebookProvider, options.GitHubProvider, - options.GoogleProvider, options.KeycloakProvider, options.LinkedInProvider, options.LoginGovProvider, options.NextCloudProvider: + options.GoogleProvider, options.KeycloakProvider, options.LinkedInProvider, options.LoginGovProvider, + options.NextCloudProvider, options.SourceHutProvider: return false, nil case options.ADFSProvider, options.AzureProvider, options.GitLabProvider, options.KeycloakOIDCProvider, options.OIDCProvider, options.MicrosoftEntraIDProvider: return true, nil diff --git a/providers/srht.go b/providers/srht.go new file mode 100644 index 00000000..aa72229c --- /dev/null +++ b/providers/srht.go @@ -0,0 +1,108 @@ +package providers + +import ( + "bytes" + "context" + "fmt" + "net/url" + + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" +) + +type SourceHutProvider struct { + *ProviderData +} + +var _ Provider = (*SourceHutProvider)(nil) + +const ( + SourceHutProviderName = "SourceHut" + SourceHutDefaultScope = "meta.sr.ht/PROFILE:RO" +) + +var ( + // Default Login URL for SourceHut. + // Pre-parsed URL of https://meta.sr.ht/oauth2/authorize. + SourceHutDefaultLoginURL = &url.URL{ + Scheme: "https", + Host: "meta.sr.ht", + Path: "/oauth2/authorize", + } + + // Default Redeem URL for SourceHut. + // Pre-parsed URL of https://meta.sr.ht/oauth2/access-token. + SourceHutDefaultRedeemURL = &url.URL{ + Scheme: "https", + Host: "meta.sr.ht", + Path: "/oauth2/access-token", + } + + // Default Profile URL for SourceHut. + // Pre-parsed URL of https://meta.sr.ht/query. + SourceHutDefaultProfileURL = &url.URL{ + Scheme: "https", + Host: "meta.sr.ht", + Path: "/query", + } + + // Default Validation URL for SourceHut. + // Pre-parsed URL of https://meta.sr.ht/profile. + SourceHutDefaultValidateURL = &url.URL{ + Scheme: "https", + Host: "meta.sr.ht", + Path: "/profile", + } +) + +// NewSourceHutProvider creates a SourceHutProvider using the passed ProviderData +func NewSourceHutProvider(p *ProviderData) *SourceHutProvider { + p.setProviderDefaults(providerDefaults{ + name: SourceHutProviderName, + loginURL: SourceHutDefaultLoginURL, + redeemURL: SourceHutDefaultRedeemURL, + profileURL: SourceHutDefaultProfileURL, + validateURL: SourceHutDefaultValidateURL, + scope: SourceHutDefaultScope, + }) + + return &SourceHutProvider{ProviderData: p} +} + +// EnrichSession uses the SourceHut userinfo endpoint to populate the session's +// email and username. +func (p *SourceHutProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error { + json, err := requests.New(p.ProfileURL.String()). + WithContext(ctx). + WithMethod("POST"). + SetHeader("Content-Type", "application/json"). + SetHeader("Authorization", "Bearer "+s.AccessToken). + WithBody(bytes.NewBufferString(`{"query": "{ me { username, email } }"}`)). + Do(). + UnmarshalSimpleJSON() + if err != nil { + logger.Errorf("failed making request %v", err) + return err + } + + email, err := json.GetPath("data", "me", "email").String() + if err != nil { + return fmt.Errorf("unable to extract email from userinfo endpoint: %v", err) + } + s.Email = email + + username, err := json.GetPath("data", "me", "username").String() + if err != nil { + return fmt.Errorf("unable to extract username from userinfo endpoint: %v", err) + } + s.PreferredUsername = username + s.User = username + + return nil +} + +// ValidateSession validates the AccessToken +func (p *SourceHutProvider) ValidateSession(ctx context.Context, s *sessions.SessionState) bool { + return validateToken(ctx, p, s.AccessToken, makeOIDCHeader(s.AccessToken)) +} diff --git a/providers/srht_test.go b/providers/srht_test.go new file mode 100644 index 00000000..fd51bf7f --- /dev/null +++ b/providers/srht_test.go @@ -0,0 +1,77 @@ +package providers + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/stretchr/testify/assert" +) + +func testSourceHutProvider(hostname string) *SourceHutProvider { + p := NewSourceHutProvider( + &ProviderData{ + ProviderName: "SourceHut", + LoginURL: &url.URL{}, + RedeemURL: &url.URL{}, + ProfileURL: &url.URL{}, + ValidateURL: &url.URL{}, + Scope: ""}, + ) + p.ProviderName = "SourceHut" + + if hostname != "" { + updateURL(p.Data().LoginURL, hostname) + updateURL(p.Data().RedeemURL, hostname) + updateURL(p.Data().ProfileURL, hostname) + updateURL(p.Data().ValidateURL, hostname) + } + return p +} + +func testSourceHutBackend(payloads map[string][]string) *httptest.Server { + return httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + index := 0 + payload, ok := payloads[r.URL.Path] + if !ok { + w.WriteHeader(404) + } else if payload[index] == "" { + w.WriteHeader(204) + } else { + w.WriteHeader(200) + w.Write([]byte(payload[index])) + } + })) +} + +func TestSourceHutProvider_ValidateSessionWithBaseUrl(t *testing.T) { + b := testSourceHutBackend(map[string][]string{}) + defer b.Close() + + bURL, _ := url.Parse(b.URL) + p := testSourceHutProvider(bURL.Host) + + session := CreateAuthorizedSession() + + valid := p.ValidateSession(context.Background(), session) + assert.False(t, valid) +} + +func TestSourceHutProvider_ValidateSessionWithUserEmails(t *testing.T) { + b := testSourceHutBackend(map[string][]string{ + "/query": {`{"data":{"me":{"username":"bitfehler","email":"ch@bitfehler.net"}}}`}, + "/profile": {`ok`}, + }) + defer b.Close() + + bURL, _ := url.Parse(b.URL) + p := testSourceHutProvider(bURL.Host) + + session := CreateAuthorizedSession() + + valid := p.ValidateSession(context.Background(), session) + assert.True(t, valid) +} From 137e59d52668e3fc5d670dfbb6c3d667739e22e3 Mon Sep 17 00:00:00 2001 From: Ashkan Daie <1415513+dashkan@users.noreply.github.com> Date: Mon, 21 Jul 2025 23:52:23 -0700 Subject: [PATCH 062/130] fix: regex substitution for $ signs in upstream path handling before running envsubst (#2524) * Perform a regex replace of $NUM to $$NUM before running envsubst * Perform a regex replace of $NUM to $$NUM before running envsubst * add test case; fix linter warnings; add method documentation Signed-off-by: Jan Larwig * add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/apis/options/load.go | 24 ++++++++++++++++++++---- pkg/apis/options/load_test.go | 25 +++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2ffc50d..50dbc9b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) - [#2743](https://github.com/oauth2-proxy/oauth2-proxy/pull/2743) feat: allow use more possible google admin-sdk api scopes (@BobDu) - [#2359](https://github.com/oauth2-proxy/oauth2-proxy/pull/2359) feat: add SourceHut (sr.ht) provider(@bitfehler) +-[#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) # V7.10.0 diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index b198c4ff..c302e8e7 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "reflect" + "regexp" "strings" "github.com/a8m/envsubst" @@ -155,7 +156,8 @@ func LoadYAML(configFileName string, into interface{}) error { return nil } -// Performs the heavy lifting of the LoadYaml function +// loadAndParseYaml reads the config from the filesystem and +// execute the environment variable substitution func loadAndParseYaml(configFileName string) ([]byte, error) { if configFileName == "" { return nil, errors.New("no configuration file provided") @@ -166,12 +168,26 @@ func loadAndParseYaml(configFileName string) ([]byte, error) { return nil, fmt.Errorf("unable to load config file: %w", err) } - // We now parse over the yaml with env substring, and fill in the ENV's - buffer, err := envsubst.Bytes(unparsedBuffer) + modifiedBuffer, err := normalizeSubstitution(unparsedBuffer) + if err != nil { + return nil, fmt.Errorf("error normalizing substitution string : %w", err) + } + + buffer, err := envsubst.Bytes(modifiedBuffer) if err != nil { return nil, fmt.Errorf("error in substituting env variables : %w", err) } return buffer, nil - +} + +// normalizeSubstitution normalizes dollar signs ($) with numerals like +// $1 or $2 properly by correctly escaping them +func normalizeSubstitution(unparsedBuffer []byte) ([]byte, error) { + unparsedString := string(unparsedBuffer) + + regexPattern := regexp.MustCompile(`\$(\d+)`) + + substitutedString := regexPattern.ReplaceAllString(unparsedString, `$$$$1`) + return []byte(substitutedString), nil } diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index fefbc2e7..06123c37 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -487,6 +487,31 @@ sub: StringOption: "Bob", }, }), + Entry("with a config file containing $ signs for things other than environment variables", loadYAMLTableInput{ + configFile: []byte(` +stringOption: /$1 +stringSliceOption: +- /$1 +- ^/(.*)$ +- api/$1 +- api/(.*)$ +- ^/api/(.*)$ +- /api/$1`), + input: &TestOptions{}, + expectedOutput: &TestOptions{ + StringOption: "/$1", + TestOptionSubStruct: TestOptionSubStruct{ + StringSliceOption: []string{ + "/$1", + "^/(.*)$", + "api/$1", + "api/(.*)$", + "^/api/(.*)$", + "/api/$1", + }, + }, + }, + }), ) }) From dc8b1623a26a2537a8d0119e087f2048234c9843 Mon Sep 17 00:00:00 2001 From: Sandy Chen Date: Wed, 23 Jul 2025 01:59:55 +0900 Subject: [PATCH 063/130] feat(cookie): add feature support for cookie-secret-file (#3104) * feat: add feature support for cookie-secret-file --------- Signed-off-by: Jan Larwig Co-Authored-By: Sandy Chen Co-authored-by: Jan Larwig --- CHANGELOG.md | 3 +- docs/docs/configuration/overview.md | 1 + pkg/apis/options/cookie.go | 46 +++++++++++++----- pkg/apis/options/cookie_test.go | 70 ++++++++++++++++++++++++++++ pkg/cookies/csrf.go | 32 +++++++++---- pkg/sessions/cookie/session_store.go | 26 +++++++---- pkg/sessions/persistence/ticket.go | 6 ++- pkg/validation/cookie.go | 27 +++++++++-- pkg/validation/cookie_test.go | 49 ++++++++++++++++++- pkg/validation/options_test.go | 2 +- 10 files changed, 226 insertions(+), 36 deletions(-) create mode 100644 pkg/apis/options/cookie_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 50dbc9b9..ea7b0b09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,8 @@ - [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) - [#2743](https://github.com/oauth2-proxy/oauth2-proxy/pull/2743) feat: allow use more possible google admin-sdk api scopes (@BobDu) - [#2359](https://github.com/oauth2-proxy/oauth2-proxy/pull/2359) feat: add SourceHut (sr.ht) provider(@bitfehler) --[#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) +- [#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) +- [#3104](https://github.com/oauth2-proxy/oauth2-proxy/pull/3104) feat(cookie): add feature support for cookie-secret-file (@sandy2008) # V7.10.0 diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 6a8f52e5..7c216dfb 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -128,6 +128,7 @@ Provider specific options can be found on their respective subpages. | flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | | flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | | flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | | flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | [^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) diff --git a/pkg/apis/options/cookie.go b/pkg/apis/options/cookie.go index 22b74a6c..3653b7d0 100644 --- a/pkg/apis/options/cookie.go +++ b/pkg/apis/options/cookie.go @@ -1,8 +1,11 @@ package options import ( + "errors" + "os" "time" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/spf13/pflag" ) @@ -10,6 +13,7 @@ import ( type Cookie struct { Name string `flag:"cookie-name" cfg:"cookie_name"` Secret string `flag:"cookie-secret" cfg:"cookie_secret"` + SecretFile string `flag:"cookie-secret-file" cfg:"cookie_secret_file"` Domains []string `flag:"cookie-domain" cfg:"cookie_domains"` Path string `flag:"cookie-path" cfg:"cookie_path"` Expire time.Duration `flag:"cookie-expire" cfg:"cookie_expire"` @@ -18,8 +22,8 @@ type Cookie struct { HTTPOnly bool `flag:"cookie-httponly" cfg:"cookie_httponly"` SameSite string `flag:"cookie-samesite" cfg:"cookie_samesite"` CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"` - CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"` CSRFPerRequestLimit int `flag:"cookie-csrf-per-request-limit" cfg:"cookie_csrf_per_request_limit"` + CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"` } func cookieFlagSet() *pflag.FlagSet { @@ -27,6 +31,7 @@ func cookieFlagSet() *pflag.FlagSet { flagSet.String("cookie-name", "_oauth2_proxy", "the name of the cookie that the oauth_proxy creates") flagSet.String("cookie-secret", "", "the seed string for secure cookies (optionally base64 encoded)") + flagSet.String("cookie-secret-file", "", "For defining a separate cookie secret file to read the encryption key from") flagSet.StringSlice("cookie-domain", []string{}, "Optional cookie domains to force cookies to (ie: `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match).") flagSet.String("cookie-path", "/", "an optional cookie path to force cookies to (ie: /poc/)*") flagSet.Duration("cookie-expire", time.Duration(168)*time.Hour, "expire timeframe for cookie") @@ -43,16 +48,33 @@ func cookieFlagSet() *pflag.FlagSet { // cookieDefaults creates a Cookie populating each field with its default value func cookieDefaults() Cookie { return Cookie{ - Name: "_oauth2_proxy", - Secret: "", - Domains: nil, - Path: "/", - Expire: time.Duration(168) * time.Hour, - Refresh: time.Duration(0), - Secure: true, - HTTPOnly: true, - SameSite: "", - CSRFPerRequest: false, - CSRFExpire: time.Duration(15) * time.Minute, + Name: "_oauth2_proxy", + Secret: "", + SecretFile: "", + Domains: nil, + Path: "/", + Expire: time.Duration(168) * time.Hour, + Refresh: time.Duration(0), + Secure: true, + HTTPOnly: true, + SameSite: "", + CSRFPerRequest: false, + CSRFPerRequestLimit: 0, + CSRFExpire: time.Duration(15) * time.Minute, } } + +// GetSecret returns the cookie secret, reading from file if SecretFile is set +func (c *Cookie) GetSecret() (secret string, err error) { + if c.Secret != "" || c.SecretFile == "" { + return c.Secret, nil + } + + fileSecret, err := os.ReadFile(c.SecretFile) + if err != nil { + logger.Errorf("error reading cookie secret file %s: %s", c.SecretFile, err) + return "", errors.New("could not read cookie secret file") + } + + return string(fileSecret), nil +} diff --git a/pkg/apis/options/cookie_test.go b/pkg/apis/options/cookie_test.go new file mode 100644 index 00000000..a1486fed --- /dev/null +++ b/pkg/apis/options/cookie_test.go @@ -0,0 +1,70 @@ +package options + +import ( + "os" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCookieGetSecret(t *testing.T) { + t.Run("returns secret when Secret is set", func(t *testing.T) { + c := &Cookie{ + Secret: "my-secret", + SecretFile: "", + } + secret, err := c.GetSecret() + assert.NoError(t, err) + assert.Equal(t, "my-secret", secret) + }) + + t.Run("returns secret when both Secret and SecretFile are set", func(t *testing.T) { + c := &Cookie{ + Secret: "my-secret", + SecretFile: "/some/file", + } + secret, err := c.GetSecret() + assert.NoError(t, err) + assert.Equal(t, "my-secret", secret) + }) + + t.Run("reads from file when only SecretFile is set", func(t *testing.T) { + // Create a temporary file + tmpfile, err := os.CreateTemp("", "cookie-secret-test") + assert.NoError(t, err) + defer os.Remove(tmpfile.Name()) + + _, err = tmpfile.Write([]byte("file-secret")) + assert.NoError(t, err) + tmpfile.Close() + + c := &Cookie{ + Secret: "", + SecretFile: tmpfile.Name(), + } + secret, err := c.GetSecret() + assert.NoError(t, err) + assert.Equal(t, "file-secret", secret) + }) + + t.Run("returns error when file does not exist", func(t *testing.T) { + c := &Cookie{ + Secret: "", + SecretFile: "/nonexistent/file", + } + secret, err := c.GetSecret() + assert.Error(t, err) + assert.Equal(t, "", secret) + assert.Contains(t, err.Error(), "could not read cookie secret file") + }) + + t.Run("returns empty when both Secret and SecretFile are empty", func(t *testing.T) { + c := &Cookie{ + Secret: "", + SecretFile: "", + } + secret, err := c.GetSecret() + assert.NoError(t, err) + assert.Equal(t, "", secret) + }) +} diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go index eab87869..3b8efaf3 100644 --- a/pkg/cookies/csrf.go +++ b/pkg/cookies/csrf.go @@ -219,13 +219,22 @@ func (c *csrf) encodeCookie() (string, error) { return "", err } - return encryption.SignedValue(c.cookieOpts.Secret, c.cookieName(), encrypted, c.time.Now()) + secret, err := c.cookieOpts.GetSecret() + if err != nil { + return "", fmt.Errorf("error getting cookie secret: %v", err) + } + return encryption.SignedValue(secret, c.cookieName(), encrypted, c.time.Now()) } // decodeCSRFCookie validates the signature then decrypts and decodes a CSRF // cookie into a CSRF struct func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) { - val, t, ok := encryption.Validate(cookie, opts.Secret, opts.Expire) + secret, err := opts.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + + val, t, ok := encryption.Validate(cookie, secret, opts.Expire) if !ok { return nil, errors.New("CSRF cookie failed validation") } @@ -235,15 +244,18 @@ func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) return nil, err } - // Valid cookie, Unmarshal the CSRF + return unmarshalCSRF(decrypted, opts, t) +} + +// unmarshalCSRF unmarshals decrypted data into a CSRF struct +func unmarshalCSRF(decrypted []byte, opts *options.Cookie, csrfTime time.Time) (*csrf, error) { clock := clock.Clock{} - clock.Set(t) + clock.Set(csrfTime) + csrf := &csrf{cookieOpts: opts, time: clock} - err = msgpack.Unmarshal(decrypted, csrf) - if err != nil { + if err := msgpack.Unmarshal(decrypted, csrf); err != nil { return nil, fmt.Errorf("error unmarshalling data to CSRF: %v", err) } - return csrf, nil } @@ -290,5 +302,9 @@ func decrypt(data []byte, opts *options.Cookie) ([]byte, error) { } func makeCipher(opts *options.Cookie) (encryption.Cipher, error) { - return encryption.NewCFBCipher(encryption.SecretBytes(opts.Secret)) + secret, err := opts.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + return encryption.NewCFBCipher(encryption.SecretBytes(secret)) } diff --git a/pkg/sessions/cookie/session_store.go b/pkg/sessions/cookie/session_store.go index 3947177f..095bc0e7 100644 --- a/pkg/sessions/cookie/session_store.go +++ b/pkg/sessions/cookie/session_store.go @@ -54,16 +54,18 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) { // always http.ErrNoCookie return nil, err } - val, _, ok := encryption.Validate(c, s.Cookie.Secret, s.Cookie.Expire) + + secret, err := s.Cookie.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + + val, _, ok := encryption.Validate(c, secret, s.Cookie.Expire) if !ok { return nil, errors.New("cookie signature not valid") } - session, err := sessions.DecodeSessionState(val, s.CookieCipher, true) - if err != nil { - return nil, err - } - return session, nil + return sessions.DecodeSessionState(val, s.CookieCipher, true) } // Clear clears any saved session information by writing a cookie to @@ -121,7 +123,11 @@ func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now ti strValue := string(value) if strValue != "" { var err error - strValue, err = encryption.SignedValue(s.Cookie.Secret, s.Cookie.Name, value, now) + secret, err := s.Cookie.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + strValue, err = encryption.SignedValue(secret, s.Cookie.Name, value, now) if err != nil { return nil, err } @@ -146,7 +152,11 @@ func (s *SessionStore) makeCookie(req *http.Request, name string, value string, // NewCookieSessionStore initialises a new instance of the SessionStore from // the configuration given func NewCookieSessionStore(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessions.SessionStore, error) { - cipher, err := encryption.NewCFBCipher(encryption.SecretBytes(cookieOpts.Secret)) + secret, err := cookieOpts.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + cipher, err := encryption.NewCFBCipher(encryption.SecretBytes(secret)) if err != nil { return nil, fmt.Errorf("error initialising cipher: %v", err) } diff --git a/pkg/sessions/persistence/ticket.go b/pkg/sessions/persistence/ticket.go index 581a7f45..7855db45 100644 --- a/pkg/sessions/persistence/ticket.go +++ b/pkg/sessions/persistence/ticket.go @@ -146,7 +146,11 @@ func decodeTicketFromRequest(req *http.Request, cookieOpts *options.Cookie) (*ti } // An existing cookie exists, try to retrieve the ticket - val, _, ok := encryption.Validate(requestCookie, cookieOpts.Secret, cookieOpts.Expire) + secret, err := cookieOpts.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + val, _, ok := encryption.Validate(requestCookie, secret, cookieOpts.Expire) if !ok { return nil, fmt.Errorf("session ticket cookie failed validation: %v", err) } diff --git a/pkg/validation/cookie.go b/pkg/validation/cookie.go index b515809d..5f2dd8ac 100644 --- a/pkg/validation/cookie.go +++ b/pkg/validation/cookie.go @@ -3,6 +3,7 @@ package validation import ( "fmt" "net/http" + "os" "sort" "time" @@ -11,7 +12,7 @@ import ( ) func validateCookie(o options.Cookie) []string { - msgs := validateCookieSecret(o.Secret) + msgs := validateCookieSecret(o.Secret, o.SecretFile) if o.Expire != time.Duration(0) && o.Refresh >= o.Expire { msgs = append(msgs, fmt.Sprintf( @@ -49,9 +50,27 @@ func validateCookieName(name string) []string { return msgs } -func validateCookieSecret(secret string) []string { - if secret == "" { - return []string{"missing setting: cookie-secret"} +func validateCookieSecret(secret string, secretFile string) []string { + if secret == "" && secretFile == "" { + return []string{"missing setting: cookie-secret or cookie-secret-file"} + } + if secret == "" && secretFile != "" { + fileData, err := os.ReadFile(secretFile) + if err != nil { + return []string{"could not read cookie secret file: " + secretFile} + } + // Validate the file content as a secret + secretBytes := encryption.SecretBytes(string(fileData)) + switch len(secretBytes) { + case 16, 24, 32: + // Valid secret size found + return []string{} + } + // Invalid secret size found, return a message + return []string{fmt.Sprintf( + "cookie_secret from file must be 16, 24, or 32 bytes to create an AES cipher, but is %d bytes", + len(secretBytes)), + } } secretBytes := encryption.SecretBytes(secret) diff --git a/pkg/validation/cookie_test.go b/pkg/validation/cookie_test.go index 1f0dc5cd..d11134da 100644 --- a/pkg/validation/cookie_test.go +++ b/pkg/validation/cookie_test.go @@ -1,6 +1,7 @@ package validation import ( + "os" "strings" "testing" "time" @@ -29,9 +30,23 @@ func TestValidateCookie(t *testing.T) { "a.cba.localhost", } + // Create a temporary file for the valid secret file test + tmpfile, err := os.CreateTemp("", "cookie-secret-test") + if err != nil { + t.Fatalf("Failed to create temporary file: %v", err) + } + defer os.Remove(tmpfile.Name()) + + // Write a valid 32-byte secret to the file + _, err = tmpfile.Write([]byte(validSecret)) + if err != nil { + t.Fatalf("Failed to write to temporary file: %v", err) + } + tmpfile.Close() + invalidNameMsg := "invalid cookie name: \"_oauth2;proxy\"" longNameMsg := "cookie name should be under 256 characters: cookie name is 260 characters" - missingSecretMsg := "missing setting: cookie-secret" + missingSecretMsg := "missing setting: cookie-secret or cookie-secret-file" invalidSecretMsg := "cookie_secret must be 16, 24, or 32 bytes to create an AES cipher, but is 6 bytes" invalidBase64SecretMsg := "cookie_secret must be 16, 24, or 32 bytes to create an AES cipher, but is 10 bytes" refreshLongerThanExpireMsg := "cookie_refresh (\"1h0m0s\") must be less than cookie_expire (\"15m0s\")" @@ -271,6 +286,38 @@ func TestValidateCookie(t *testing.T) { }, errStrings: []string{}, }, + { + name: "with valid secret file", + cookie: options.Cookie{ + Name: validName, + Secret: "", + SecretFile: tmpfile.Name(), + Domains: domains, + Path: "", + Expire: 24 * time.Hour, + Refresh: 0, + Secure: true, + HTTPOnly: true, + SameSite: "", + }, + errStrings: []string{}, + }, + { + name: "with nonexistent secret file", + cookie: options.Cookie{ + Name: validName, + Secret: "", + SecretFile: "/nonexistent/file.txt", + Domains: domains, + Path: "", + Expire: 24 * time.Hour, + Refresh: 0, + Secure: true, + HTTPOnly: true, + SameSite: "", + }, + errStrings: []string{"could not read cookie secret file: /nonexistent/file.txt"}, + }, } for _, tc := range testCases { diff --git a/pkg/validation/options_test.go b/pkg/validation/options_test.go index 2d5e9560..5c242e02 100644 --- a/pkg/validation/options_test.go +++ b/pkg/validation/options_test.go @@ -48,7 +48,7 @@ func TestNewOptions(t *testing.T) { assert.NotEqual(t, nil, err) expected := errorMsg([]string{ - "missing setting: cookie-secret", + "missing setting: cookie-secret or cookie-secret-file", "provider has empty id: ids are required for all providers", "provider missing setting: client-id", "missing setting: client-secret or client-secret-file"}) From b905f2cd934315100dadc5c64203533fa4c9aa70 Mon Sep 17 00:00:00 2001 From: Michael Cornel Date: Wed, 23 Jul 2025 22:40:12 +0200 Subject: [PATCH 064/130] feat: use non-default authorization request response mode in OIDC providers (#3055) * fix: OIDC sets response mode * Update CHANGELOG --- CHANGELOG.md | 1 + providers/oidc.go | 5 +++++ providers/oidc_test.go | 29 +++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea7b0b09..78718cc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - [#2359](https://github.com/oauth2-proxy/oauth2-proxy/pull/2359) feat: add SourceHut (sr.ht) provider(@bitfehler) - [#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) - [#3104](https://github.com/oauth2-proxy/oauth2-proxy/pull/3104) feat(cookie): add feature support for cookie-secret-file (@sandy2008) +- [#3055](https://github.com/oauth2-proxy/oauth2-proxy/pull/3055) feat: support non-default authorization request response mode also for OIDC providers (@stieler-it) # V7.10.0 diff --git a/providers/oidc.go b/providers/oidc.go index 43b5227e..15598aba 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -61,6 +61,11 @@ func (p *OIDCProvider) GetLoginURL(redirectURI, state, nonce string, extraParams if !p.SkipNonce { extraParams.Add("nonce", nonce) } + // Response mode should only be set if a non default mode is requested + if p.AuthRequestResponseMode != "" { + extraParams.Add("response_mode", p.AuthRequestResponseMode) + } + loginURL := makeLoginURL(p.Data(), redirectURI, state, extraParams) return loginURL.String() } diff --git a/providers/oidc_test.go b/providers/oidc_test.go index 6a49f8ff..81a70eb4 100644 --- a/providers/oidc_test.go +++ b/providers/oidc_test.go @@ -275,3 +275,32 @@ func TestOIDCProviderCreateSessionFromToken(t *testing.T) { }) } } + +func TestOIDCProviderResponseModeConfigured(t *testing.T) { + providerData := &ProviderData{ + LoginURL: &url.URL{ + Scheme: "http", + Host: "my.test.idp", + Path: "/oauth/authorize", + }, + AuthRequestResponseMode: "form_post", + } + p := NewOIDCProvider(providerData, options.OIDCOptions{}) + + result := p.GetLoginURL("https://my.test.app/oauth", "", "", url.Values{}) + assert.Contains(t, result, "response_mode=form_post") +} + +func TestOIDCProviderResponseModeNotConfigured(t *testing.T) { + providerData := &ProviderData{ + LoginURL: &url.URL{ + Scheme: "http", + Host: "my.test.idp", + Path: "/oauth/authorize", + }, + } + p := NewOIDCProvider(providerData, options.OIDCOptions{}) + + result := p.GetLoginURL("https://my.test.app/oauth", "", "", url.Values{}) + assert.NotContains(t, result, "response_mode") +} From e75a258299ec3db633450dd48a6df54b38988916 Mon Sep 17 00:00:00 2001 From: Sourav Agrawal <146818014+sourava01@users.noreply.github.com> Date: Thu, 24 Jul 2025 11:25:54 +0530 Subject: [PATCH 065/130] feat: make google-groups argument optional (#3138) add test cases update documentation refactor code and some cleanup update changelog Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/providers/google.md | 2 +- pkg/validation/options_test.go | 26 +++++- pkg/validation/providers.go | 6 +- providers/google.go | 89 +++++++++++++++++---- providers/google_test.go | 36 +++++++++ 6 files changed, 135 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78718cc3..0c117129 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - [#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) - [#3104](https://github.com/oauth2-proxy/oauth2-proxy/pull/3104) feat(cookie): add feature support for cookie-secret-file (@sandy2008) - [#3055](https://github.com/oauth2-proxy/oauth2-proxy/pull/3055) feat: support non-default authorization request response mode also for OIDC providers (@stieler-it) +- [#3138](https://github.com/oauth2-proxy/oauth2-proxy/pull/3138) feat: make google_groups argument optional when using google provider (@sourava01) # V7.10.0 diff --git a/docs/docs/configuration/providers/google.md b/docs/docs/configuration/providers/google.md index 26af87ab..ac2a7dfa 100644 --- a/docs/docs/configuration/providers/google.md +++ b/docs/docs/configuration/providers/google.md @@ -8,7 +8,7 @@ title: Google (default) | Flag | Toml Field | Type | Description | Default | | ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | | `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | -| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | | `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | | `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | | `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | diff --git a/pkg/validation/options_test.go b/pkg/validation/options_test.go index 5c242e02..5c283545 100644 --- a/pkg/validation/options_test.go +++ b/pkg/validation/options_test.go @@ -55,18 +55,38 @@ func TestNewOptions(t *testing.T) { assert.Equal(t, expected, err.Error()) } -func TestGoogleGroupOptions(t *testing.T) { +func TestGoogleGroupOptionsWithoutServiceAccountJSON(t *testing.T) { o := testOptions() - o.Providers[0].GoogleConfig.Groups = []string{"googlegroup"} + o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" err := Validate(o) assert.NotEqual(t, nil, err) expected := errorMsg([]string{ - "missing setting: google-admin-email", "missing setting: google-service-account-json or google-use-application-default-credentials"}) assert.Equal(t, expected, err.Error()) } +func TestGoogleGroupOptionsWithoutAdminEmail(t *testing.T) { + o := testOptions() + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = true + err := Validate(o) + assert.NotEqual(t, nil, err) + + expected := errorMsg([]string{ + "missing setting: google-admin-email"}) + assert.Equal(t, expected, err.Error()) +} + +func TestGoogleGroupOptionsWithoutGroups(t *testing.T) { + o := testOptions() + // Set admin email and application default credentials but no groups - should still require them + o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = true + err := Validate(o) + // Should pass validation since google-group is now optional + assert.Equal(t, nil, err) +} + func TestGoogleGroupInvalidFile(t *testing.T) { o := testOptions() o.Providers[0].GoogleConfig.Groups = []string{"test_group"} diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index b1106b35..4527b841 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -94,18 +94,14 @@ func validateClientSecret(provider options.Provider) []string { func validateGoogleConfig(provider options.Provider) []string { msgs := []string{} - hasGoogleGroups := len(provider.GoogleConfig.Groups) >= 1 hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" useADC := provider.GoogleConfig.UseApplicationDefaultCredentials - if !hasGoogleGroups && !hasAdminEmail && !hasSAJSON && !useADC { + if !hasAdminEmail && !hasSAJSON && !useADC { return msgs } - if !hasGoogleGroups { - msgs = append(msgs, "missing setting: google-group") - } if !hasAdminEmail { msgs = append(msgs, "missing setting: google-admin-email") } diff --git a/providers/google.go b/providers/google.go index 0e1e2156..097e3567 100644 --- a/providers/google.go +++ b/providers/google.go @@ -103,17 +103,24 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv } if opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { - // Backwards compatibility with `--google-group` option - if len(opts.Groups) > 0 { - provider.setAllowedGroups(opts.Groups) - } - - provider.setGroupRestriction(opts) + provider.configureGroups(opts) } return provider, nil } +func (p *GoogleProvider) configureGroups(opts options.GoogleOptions) { + adminService := getAdminService(opts) + // Backwards compatibility with `--google-group` option + if len(opts.Groups) > 0 { + p.setAllowedGroups(opts.Groups) + p.groupValidator = p.setGroupRestriction(opts.Groups, adminService) + return + } + + p.groupValidator = p.populateAllGroups(adminService) +} + func claimsFromIDToken(idToken string) (*claims, error) { // id_token is a base64 encode ID token payload @@ -209,18 +216,13 @@ func (p *GoogleProvider) EnrichSession(_ context.Context, s *sessions.SessionSta } // SetGroupRestriction configures the GoogleProvider to restrict access to the -// specified group(s). AdminEmail has to be an administrative email on the domain that is -// checked. CredentialsFile is the path to a json file containing a Google service -// account credentials. -// -// TODO (@NickMeves) - Unit Test this OR refactor away from groupValidator func -func (p *GoogleProvider) setGroupRestriction(opts options.GoogleOptions) { - adminService := getAdminService(opts) - p.groupValidator = func(s *sessions.SessionState) bool { +// specified group(s). +func (p *GoogleProvider) setGroupRestriction(groups []string, adminService *admin.Service) func(*sessions.SessionState) bool { + return func(s *sessions.SessionState) bool { // Reset our saved Groups in case membership changed // This is used by `Authorize` on every request - s.Groups = make([]string, 0, len(opts.Groups)) - for _, group := range opts.Groups { + s.Groups = make([]string, 0, len(groups)) + for _, group := range groups { if userInGroup(adminService, group, s.Email) { s.Groups = append(s.Groups, group) } @@ -229,6 +231,25 @@ func (p *GoogleProvider) setGroupRestriction(opts options.GoogleOptions) { } } +// populateAllGroups configures the GoogleProvider to allow access with all +// groups and populate session with all groups of the user when no specific +// groups are configured. +func (p *GoogleProvider) populateAllGroups(adminService *admin.Service) func(s *sessions.SessionState) bool { + return func(s *sessions.SessionState) bool { + // Get all groups of the user + groups, err := getUserGroups(adminService, s.Email) + if err != nil { + logger.Errorf("Failed to get user groups for %s: %v", s.Email, err) + s.Groups = []string{} + return true // Allow access even if we can't get groups + } + + // Populate session with all user groups + s.Groups = groups + return true // Always allow access when no specific groups are configured + } +} + // https://developers.google.com/admin-sdk/directory/reference/rest/v1/members/hasMember#authorization-scopes var possibleScopesList = [...]string{ admin.AdminDirectoryGroupMemberReadonlyScope, @@ -269,6 +290,10 @@ func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope return conf.TokenSource(ctx) } +// getAdminService retrieves an oauth token for the admin api of Google +// AdminEmail has to be an administrative email on the domain that is +// checked. CredentialsFile is the path to a json file containing a Google service +// account credentials. func getAdminService(opts options.GoogleOptions) *admin.Service { ctx := context.Background() var client *http.Client @@ -339,6 +364,38 @@ func getTargetPrincipal(ctx context.Context, opts options.GoogleOptions) (target return targetPrincipal } +// getUserGroups retrieves all groups that a user is a member of using the Google Admin Directory API +func getUserGroups(service *admin.Service, email string) ([]string, error) { + var allGroups []string + var pageToken string + + for { + req := service.Groups.List().UserKey(email).MaxResults(200) + if pageToken != "" { + req = req.PageToken(pageToken) + } + + groupsResp, err := req.Do() + if err != nil { + return nil, fmt.Errorf("failed to list groups for user %s: %v", email, err) + } + + for _, group := range groupsResp.Groups { + if group.Email != "" { + allGroups = append(allGroups, group.Email) + } + } + + // Check if there are more pages + if groupsResp.NextPageToken == "" { + break + } + pageToken = groupsResp.NextPageToken + } + + return allGroups, nil +} + func userInGroup(service *admin.Service, group string, email string) bool { // Use the HasMember API to checking for the user's presence in each group or nested subgroups req := service.Members.HasMember(group, email) diff --git a/providers/google_test.go b/providers/google_test.go index 23bca7ea..dc061203 100644 --- a/providers/google_test.go +++ b/providers/google_test.go @@ -289,3 +289,39 @@ func TestGoogleProvider_userInGroup(t *testing.T) { result = userInGroup(service, "group@example.com", "non-member-out-of-domain@otherexample.com") assert.False(t, result) } + +func TestGoogleProvider_getUserGroups(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/admin/directory/v1/groups" && r.URL.Query().Get("userKey") == "test@example.com" { + response := `{ + "kind": "admin#directory#groups", + "groups": [ + { + "kind": "admin#directory#group", + "id": "1", + "email": "group1@example.com", + "name": "Group 1" + }, + { + "kind": "admin#directory#group", + "id": "2", + "email": "group2@example.com", + "name": "Group 2" + } + ] + }` + fmt.Fprintln(w, response) + } else { + http.NotFound(w, r) + } + })) + defer ts.Close() + + client := &http.Client{} + adminService, err := admin.NewService(context.Background(), option.WithHTTPClient(client), option.WithEndpoint(ts.URL)) + assert.NoError(t, err) + + groups, err := getUserGroups(adminService, "test@example.com") + assert.NoError(t, err) + assert.Equal(t, []string{"group1@example.com", "group2@example.com"}, groups) +} From f4b33b64bd66ad28e9b0d63bea51837b83c00ca1 Mon Sep 17 00:00:00 2001 From: nobletrout Date: Thu, 24 Jul 2025 02:33:06 -0400 Subject: [PATCH 066/130] feat: differentiate between "no available key" and error for redis sessions (#3093) * add some better error handling * add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 2 ++ pkg/sessions/redis/redis_store.go | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c117129..ed30ea57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ - [#3104](https://github.com/oauth2-proxy/oauth2-proxy/pull/3104) feat(cookie): add feature support for cookie-secret-file (@sandy2008) - [#3055](https://github.com/oauth2-proxy/oauth2-proxy/pull/3055) feat: support non-default authorization request response mode also for OIDC providers (@stieler-it) - [#3138](https://github.com/oauth2-proxy/oauth2-proxy/pull/3138) feat: make google_groups argument optional when using google provider (@sourava01) +- [#3093](https://github.com/oauth2-proxy/oauth2-proxy/pull/3093) feat: differentiate between "no available key" and error for redis sessions (@nobletrout) + # V7.10.0 diff --git a/pkg/sessions/redis/redis_store.go b/pkg/sessions/redis/redis_store.go index 18d79b80..4e846e9b 100644 --- a/pkg/sessions/redis/redis_store.go +++ b/pkg/sessions/redis/redis_store.go @@ -49,9 +49,12 @@ func (store *SessionStore) Save(ctx context.Context, key string, value []byte, e // cookie within the HTTP request object func (store *SessionStore) Load(ctx context.Context, key string) ([]byte, error) { value, err := store.Client.Get(ctx, key) - if err != nil { + if err == redis.Nil { + return nil, fmt.Errorf("session does not exist") + } else if err != nil { return nil, fmt.Errorf("error loading redis session: %v", err) } + return value, nil } From 9ffafad4b2d2f9f7668e5504565f356a7c047b77 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Wed, 30 Jul 2025 19:46:58 +0200 Subject: [PATCH 067/130] Merge commit from fork Signed-off-by: Jan Larwig --- CHANGELOG.md | 15 +++++++++ oauthproxy.go | 2 +- pkg/requests/util/util.go | 21 ++++++++++++ pkg/requests/util/util_test.go | 61 ++++++++++++++++++++++++++-------- 4 files changed, 85 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed30ea57..2b751d9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,22 @@ ## Important Notes +Fixed critical vulnerability where `skip_auth_routes` regex patterns matched against the full request URI (path + query parameters) instead of just the path, allowing authentication bypass attacks. + ## Breaking Changes +If your configuration relies on matching query parameters in `skip_auth_routes` patterns, you must update your regex patterns to match paths only. Review all `skip_auth_routes` entries for potential impact. + +**Example of affected configuration:** +```yaml +# This pattern previously matched both: +# - /api/foo/status (intended) +# - /api/private/sensitive?path=/status (bypass - now fixed) +skip_auth_routes: ["^/api/.*/status"] +``` + +For detailed information, migration guidance, and security implications, see the [security advisory](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7rh7-c77v-6434). + ## Changes since v7.10.0 - [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) @@ -17,6 +31,7 @@ - [#3055](https://github.com/oauth2-proxy/oauth2-proxy/pull/3055) feat: support non-default authorization request response mode also for OIDC providers (@stieler-it) - [#3138](https://github.com/oauth2-proxy/oauth2-proxy/pull/3138) feat: make google_groups argument optional when using google provider (@sourava01) - [#3093](https://github.com/oauth2-proxy/oauth2-proxy/pull/3093) feat: differentiate between "no available key" and error for redis sessions (@nobletrout) +- [GHSA-7rh7-c77v-6434](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7rh7-c77v-6434) fix: skip_auth_routes bypass through query parameter inclusion # V7.10.0 diff --git a/oauthproxy.go b/oauthproxy.go index d8984cde..7526d641 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -580,7 +580,7 @@ func isAllowedMethod(req *http.Request, route allowedRoute) bool { } func isAllowedPath(req *http.Request, route allowedRoute) bool { - matches := route.pathRegex.MatchString(requestutil.GetRequestURI(req)) + matches := route.pathRegex.MatchString(requestutil.GetRequestPath(req)) if route.negate { return !matches diff --git a/pkg/requests/util/util.go b/pkg/requests/util/util.go index 44e1ab0e..290f8059 100644 --- a/pkg/requests/util/util.go +++ b/pkg/requests/util/util.go @@ -2,6 +2,8 @@ package util import ( "net/http" + "net/url" + "strings" middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" ) @@ -43,6 +45,25 @@ func GetRequestURI(req *http.Request) string { return uri } +// GetRequestPath returns the request URI or X-Forwarded-Uri if present and the +// request is proxied but always strips the query parameters and only returns +// the pure path +func GetRequestPath(req *http.Request) string { + uri := GetRequestURI(req) + + // Parse URI and return only the path component + if parsedURL, err := url.Parse(uri); err == nil { + return parsedURL.Path + } + + // Fallback: strip query parameters manually + if idx := strings.Index(uri, "?"); idx != -1 { + return uri[:idx] + } + + return uri +} + // IsProxied determines if a request was from a proxy based on the RequestScope // ReverseProxy tracker. func IsProxied(req *http.Request) bool { diff --git a/pkg/requests/util/util_test.go b/pkg/requests/util/util_test.go index f1153d87..ba72c66d 100644 --- a/pkg/requests/util/util_test.go +++ b/pkg/requests/util/util_test.go @@ -13,16 +13,17 @@ import ( var _ = Describe("Util Suite", func() { const ( - proto = "http" - host = "www.oauth2proxy.test" - uri = "/test/endpoint" + proto = "http" + host = "www.oauth2proxy.test" + uriWithQueryParams = "/test/endpoint?query=param" + uriNoQueryParams = "/test/endpoint" ) var req *http.Request BeforeEach(func() { req = httptest.NewRequest( http.MethodGet, - fmt.Sprintf("%s://%s%s", proto, host, uri), + fmt.Sprintf("%s://%s%s", proto, host, uriWithQueryParams), nil, ) }) @@ -101,13 +102,13 @@ var _ = Describe("Util Suite", func() { req = middleware.AddRequestScope(req, &middleware.RequestScope{}) }) - It("returns the URI", func() { - Expect(util.GetRequestURI(req)).To(Equal(uri)) + It("returns the URI (with query params)", func() { + Expect(util.GetRequestURI(req)).To(Equal(uriWithQueryParams)) }) - It("ignores X-Forwarded-Uri and returns the URI", func() { + It("ignores X-Forwarded-Uri and returns the URI (with query params)", func() { req.Header.Add("X-Forwarded-Uri", "/some/other/path") - Expect(util.GetRequestURI(req)).To(Equal(uri)) + Expect(util.GetRequestURI(req)).To(Equal(uriWithQueryParams)) }) }) @@ -118,13 +119,47 @@ var _ = Describe("Util Suite", func() { }) }) - It("returns the URI if X-Forwarded-Uri is not present", func() { - Expect(util.GetRequestURI(req)).To(Equal(uri)) + It("returns the URI if X-Forwarded-Uri is not present (with query params)", func() { + Expect(util.GetRequestURI(req)).To(Equal(uriWithQueryParams)) }) - It("returns the X-Forwarded-Uri when present", func() { - req.Header.Add("X-Forwarded-Uri", "/some/other/path") - Expect(util.GetRequestURI(req)).To(Equal("/some/other/path")) + It("returns the X-Forwarded-Uri when present (with query params)", func() { + req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param") + Expect(util.GetRequestURI(req)).To(Equal("/some/other/path?query=param")) + }) + }) + }) + + Context("GetRequestPath", func() { + Context("IsProxied is false", func() { + BeforeEach(func() { + req = middleware.AddRequestScope(req, &middleware.RequestScope{}) + }) + + It("returns the URI (without query params)", func() { + Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams)) + }) + + It("ignores X-Forwarded-Uri and returns the URI (without query params)", func() { + req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param") + Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams)) + }) + }) + + Context("IsProxied is true", func() { + BeforeEach(func() { + req = middleware.AddRequestScope(req, &middleware.RequestScope{ + ReverseProxy: true, + }) + }) + + It("returns the URI if X-Forwarded-Uri is not present (without query params)", func() { + Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams)) + }) + + It("returns the X-Forwarded-Uri when present (without query params)", func() { + req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param") + Expect(util.GetRequestPath(req)).To(Equal("/some/other/path")) }) }) }) From c0a928ededa40391baeedf8c5f3e104c047bfb6e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 30 Jul 2025 20:09:33 +0200 Subject: [PATCH 068/130] release v7.11.0 (#3145) * add new docs version 7.11.x * update to release version v7.11.0 * add changelog entry for v7.11.0 Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 34 +- .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- .../version-7.11.x/behaviour.md | 11 + .../version-7.11.x/community/contribution.md | 89 +++ .../version-7.11.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 564 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 318 ++++++++++ .../version-7.11.x/configuration/overview.md | 405 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 75 +++ .../configuration/providers/index.md | 43 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 ++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../configuration/providers/sourcehut.md | 25 + .../version-7.11.x/configuration/sessions.md | 99 +++ .../configuration/systemd_socket.md | 43 ++ .../version-7.11.x/configuration/tls.md | 85 +++ .../version-7.11.x/features/endpoints.md | 47 ++ .../version-7.11.x/installation.md | 32 + docs/versioned_docs/version-7.11.x/welcome.md | 23 + .../version-7.11.x-sidebars.json | 83 +++ docs/versions.json | 1 + 41 files changed, 3106 insertions(+), 8 deletions(-) create mode 100644 docs/versioned_docs/version-7.11.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.11.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.11.x/community/security.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.11.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.11.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.11.x/installation.md create mode 100644 docs/versioned_docs/version-7.11.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.11.x-sidebars.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b751d9f..c8301170 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,39 @@ ## Important Notes -Fixed critical vulnerability where `skip_auth_routes` regex patterns matched against the full request URI (path + query parameters) instead of just the path, allowing authentication bypass attacks. +## Breaking Changes + +## Changes since v7.11.0 + +# V7.11.0 + +## Release Highlights + +- 🏢 Support for SourceHut (sr.ht) provider +- 🔍️ Support for more fine-grained control over the google admin-sdk scopes and optional google groups +- 🐛 Squashed some bugs + + +## Important Notes + +Firstly, fixed critical vulnerability where `skip_auth_routes` regex patterns matched against the full request URI (path + query parameters) instead of just the path, allowing authentication bypass attacks. + +Secondly, fixed double-escaping of `$` in regexes for Alpha Config upstreams path and rewriteTargets: + +```yaml +# Before +upstreams: + - id: web + path: ^/(.*)$$ + rewriteTarget: /$$1 + +# After +upstreams: + - id: web + path: ^/(.*)$ + rewriteTarget: /$1 +``` + ## Breaking Changes diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 3acc01bf..55b4649e 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index c3236084..f3f4f900 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 66a2d011..1796b65c 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 72f9d97a..3875eda9 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index e22c633d..d9d4897a 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 3da4a9a6..3940f475 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 95da82da..b6fc9d01 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.10.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.11.x/behaviour.md b/docs/versioned_docs/version-7.11.x/behaviour.md new file mode 100644 index 00000000..e063d4f9 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/behaviour.md @@ -0,0 +1,11 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) +3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set +4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) + +Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). diff --git a/docs/versioned_docs/version-7.11.x/community/contribution.md b/docs/versioned_docs/version-7.11.x/community/contribution.md new file mode 100644 index 00000000..92255eda --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/community/contribution.md @@ -0,0 +1,89 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +This project is currently still using go 1.22. You can follow the installation guide for go [here.](https://go.dev/doc/install) And you can find go version 1.22 in the archived section [here.](https://go.dev/dl/) + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:5556 + diff --git a/docs/versioned_docs/version-7.11.x/community/security.md b/docs/versioned_docs/version-7.11.x/community/security.md new file mode 100644 index 00000000..c24b57d9 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md new file mode 100644 index 00000000..018a2941 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md @@ -0,0 +1,564 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### Duration +#### (`string` alias) + +(**Appears on:** [Upstream](#upstream)) + +Duration is as string representation of a period of time. +A duration string is a is a possibly signed sequence of decimal numbers, +each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md.tmpl new file mode 100644 index 00000000..8258201f --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.11.x/configuration/integration.md b/docs/versioned_docs/version-7.11.x/configuration/integration.md new file mode 100644 index 00000000..05d39281 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/integration.md @@ -0,0 +1,318 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. +Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. +Note that `nginxinc/kubernetes-ingress` does not include the Lua module. + +```yaml +nginx.ingress.kubernetes.io/auth-response-headers: Authorization +nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri +nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth +nginx.ingress.kubernetes.io/configuration-snippet: | + auth_request_set $name_upstream_1 $upstream_cookie_name_1; + + access_by_lua_block { + if ngx.var.name_upstream_1 ~= "" then + ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") + end + } +``` +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.11.x/configuration/overview.md b/docs/versioned_docs/version-7.11.x/configuration/overview.md new file mode 100644 index 00000000..7c216dfb --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/overview.md @@ -0,0 +1,405 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.11.x/configuration/providers/adfs.md new file mode 100644 index 00000000..ec8d72d2 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.11.x/configuration/providers/bitbucket.md new file mode 100644 index 00000000..e31de752 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.11.x/configuration/providers/digitalocean.md new file mode 100644 index 00000000..f6a1e891 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.11.x/configuration/providers/facebook.md new file mode 100644 index 00000000..352c95ce --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.11.x/configuration/providers/gitea.md new file mode 100644 index 00000000..996a5ddb --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea +--- + +:::note +This is not actually its own provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/github.md b/docs/versioned_docs/version-7.11.x/configuration/providers/github.md new file mode 100644 index 00000000..cebca314 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md new file mode 100644 index 00000000..4cdbbbe1 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/google.md b/docs/versioned_docs/version-7.11.x/configuration/providers/google.md new file mode 100644 index 00000000..ac2a7dfa --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/google.md @@ -0,0 +1,75 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.member.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/index.md b/docs/versioned_docs/version-7.11.x/configuration/providers/index.md new file mode 100644 index 00000000..b947c09b --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/index.md @@ -0,0 +1,43 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak.md new file mode 100644 index 00000000..11a1abca --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 00000000..b29096e3 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.11.x/configuration/providers/linkedin.md new file mode 100644 index 00000000..7d26ec43 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.11.x/configuration/providers/login_gov.md new file mode 100644 index 00000000..badbe48e --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 00000000..4feefc68 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md new file mode 100644 index 00000000..c5d9594e --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.11.x/configuration/providers/nextcloud.md new file mode 100644 index 00000000..85ebff03 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.11.x/configuration/providers/openid_connect.md new file mode 100644 index 00000000..de170058 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md new file mode 100644 index 00000000..88d14622 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](#email-authentication). + diff --git a/docs/versioned_docs/version-7.11.x/configuration/sessions.md b/docs/versioned_docs/version-7.11.x/configuration/sessions.md new file mode 100644 index 00000000..e2037817 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.11.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.11.x/configuration/systemd_socket.md new file mode 100644 index 00000000..642e6f3f --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.11.x/configuration/tls.md b/docs/versioned_docs/version-7.11.x/configuration/tls.md new file mode 100644 index 00000000..68344b22 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.11.x/features/endpoints.md b/docs/versioned_docs/version-7.11.x/features/endpoints.md new file mode 100644 index 00000000..3ec1e2aa --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/features/endpoints.md @@ -0,0 +1,47 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.11.x/installation.md b/docs/versioned_docs/version-7.11.x/installation.md new file mode 100644 index 00000000..b6fc9d01 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.11.x/welcome.md b/docs/versioned_docs/version-7.11.x/welcome.md new file mode 100644 index 00000000..7bceadd8 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.11.x-sidebars.json b/docs/versioned_sidebars/version-7.11.x-sidebars.json new file mode 100644 index 00000000..0dbf04bd --- /dev/null +++ b/docs/versioned_sidebars/version-7.11.x-sidebars.json @@ -0,0 +1,83 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index 2b556795..b4f8a9f5 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.11.x", "7.10.x", "7.9.x", "7.8.x", From 4eaa1bcfd5774fc534d81ca715d1fade07345a5b Mon Sep 17 00:00:00 2001 From: Theron Boerner Date: Fri, 1 Aug 2025 17:36:45 -0500 Subject: [PATCH 069/130] fix: port for local-environment (#3148) --- contrib/local-environment/docker-compose.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 3940f475..02c8a165 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -36,7 +36,7 @@ services: - "./dex.yaml:/dex.yaml" restart: unless-stopped ports: - - 5556:4181/tcp + - 5556:5556/tcp networks: dex: aliases: From 9667bce094bd4e322ce882cd7d3e132822aa3763 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 12 Aug 2025 08:11:00 +0200 Subject: [PATCH 070/130] feat(e2e): add workflow to trigger e2e test suite through PR comments (#3153) * feat(e2e): add workflow to trigger e2e test suite through PR comments * add empty line --- .github/workflows/e2e.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .github/workflows/e2e.yml diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml new file mode 100644 index 00000000..97f43c7c --- /dev/null +++ b/.github/workflows/e2e.yml @@ -0,0 +1,14 @@ +name: E2E + +on: + issue_comment: + types: [created] + +jobs: + e2e: + uses: oauth2-proxy/e2e-suite/.github/workflows/e2e.yml@main + permissions: + contents: read + statuses: write + issues: write + pull-requests: write From 4c86a4d574952ffa829dbe1f5a32c48b3f2e1ddc Mon Sep 17 00:00:00 2001 From: Kevin Kreitner Date: Tue, 12 Aug 2025 17:41:45 +0200 Subject: [PATCH 071/130] feat: add Cidaas provider (#2273) * Add sensible logging flag to default setup for logger * Fix default value flag for sensitive logging * Remove sensitive logging changes * Add Cidaas provider * Update CHANGELOG.md * Add required groups scope to defaults * Fix tests * Remove if block with protected resource * Fix linting * Adjust provider sorting, fixes * Directly handle error return Co-authored-by: Jan Larwig * Use less deep nesting Co-authored-by: Jan Larwig * Directly handle returned error Co-authored-by: Jan Larwig * Pass provider options to Cidaas provider Co-authored-by: Jan Larwig * Add import for provider options * Fix tests * Fix linting * Add Cidaas doc page * Add Cidaas provider doc page to overview * Fix link in docs * Fix link in docs * Add link to Cidaas * fix provider order in docs and changelog position Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Teko012 <112829523+Teko012@users.noreply.github.com> Co-authored-by: Jan Larwig Co-authored-by: Kevin Kreitner --- CHANGELOG.md | 2 + docs/docs/configuration/providers/cidaas.md | 37 ++ docs/docs/configuration/providers/index.md | 1 + pkg/apis/options/providers.go | 3 + providers/cidaas.go | 144 ++++++ providers/cidaas_test.go | 493 ++++++++++++++++++++ providers/providers.go | 5 +- 7 files changed, 684 insertions(+), 1 deletion(-) create mode 100644 docs/docs/configuration/providers/cidaas.md create mode 100644 providers/cidaas.go create mode 100644 providers/cidaas_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index c8301170..a6909163 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.11.0 +- [#2273](https://github.com/oauth2-proxy/oauth2-proxy/pull/2273) feat: add Cidaas provider (@Bibob7, @Teko012) + # V7.11.0 ## Release Highlights diff --git a/docs/docs/configuration/providers/cidaas.md b/docs/docs/configuration/providers/cidaas.md new file mode 100644 index 00000000..7a987018 --- /dev/null +++ b/docs/docs/configuration/providers/cidaas.md @@ -0,0 +1,37 @@ +--- +id: cidaas +title: Cidaas +--- + +[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services. +It supports various protocols including OpenID Connect, OAuth 2.0, and SAML. + +However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet. +The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy. + +Example of groups and roles in Cidaas: + +```json +{ + "groups": [ + { + "groupId": "group1", + "roles": ["role1", "role2"] + }, + { + "groupId": "group2", + "roles": ["role3"] + } + ] +} +``` + +This will be transformed into a flat list of groups: + +```json +{ + "groups": ["group1:role1", "group2:role2", "group2:role3"] +} +``` + +Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md). \ No newline at end of file diff --git a/docs/docs/configuration/providers/index.md b/docs/docs/configuration/providers/index.md index b947c09b..713b5cb9 100644 --- a/docs/docs/configuration/providers/index.md +++ b/docs/docs/configuration/providers/index.md @@ -10,6 +10,7 @@ Valid providers are : - [ADFS](adfs.md) - [Bitbucket](bitbucket.md) +- [Cidaas](cidaas.md) - [DigitalOcean](digitalocean.md) - [Facebook](facebook.md) - [Gitea](gitea.md) diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index ac5652ca..0f254575 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -115,6 +115,9 @@ const ( // BitbucketProvider is the provider type for Bitbucket BitbucketProvider ProviderType = "bitbucket" + // CidaasProvider is the provider type for Cidaas IDP + CidaasProvider ProviderType = "cidaas" + // DigitalOceanProvider is the provider type for DigitalOcean DigitalOceanProvider ProviderType = "digitalocean" diff --git a/providers/cidaas.go b/providers/cidaas.go new file mode 100644 index 00000000..1d526dfc --- /dev/null +++ b/providers/cidaas.go @@ -0,0 +1,144 @@ +package providers + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "github.com/bitly/go-simplejson" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" +) + +type GroupsClaimList []GroupClaimEntry + +type GroupClaimEntry struct { + GroupID string `json:"groupId"` + Roles []string `json:"roles"` +} + +// CIDAASProvider represents an CIDAAS based Identity Provider +type CIDAASProvider struct { + *OIDCProvider +} + +var _ Provider = (*CIDAASProvider)(nil) + +const ( + CidaasProviderName = "CIDAAS" + CidaasGroupName = "cidaas" + CidaasDefaultScope = "openid email profile roles groups" +) + +// NewCIDAASProvider initiates a new CIDAASProvider +func NewCIDAASProvider(p *ProviderData, opts options.Provider) *CIDAASProvider { + p.setProviderDefaults(providerDefaults{ + name: CidaasProviderName, + scope: CidaasDefaultScope, + }) + + return &CIDAASProvider{ + OIDCProvider: NewOIDCProvider(p, opts.OIDCConfig), + } +} + +// RefreshSession uses the RefreshToken to fetch new Access and ID Tokens +func (p *CIDAASProvider) RefreshSession(ctx context.Context, s *sessions.SessionState) (bool, error) { + if s == nil || s.RefreshToken == "" { + return false, nil + } + + if err := p.redeemRefreshToken(ctx, s); err != nil { + return false, fmt.Errorf("unable to redeem refresh token: %w", err) + } + + if err := p.EnrichSession(ctx, s); err != nil { + return false, fmt.Errorf("unable to enrich session data after refresh: %w %v", err, s) + } + + return true, nil +} + +// EnrichSession data to add email an groups +func (p *CIDAASProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error { + if p.ProfileURL.String() == "" && s.Email == "" { + return errors.New("id_token did not contain an email and profileURL is not defined") + } else if p.ProfileURL.String() == "" { + return nil + } + + // Try to get missing emails or groups from a profileURL + if err := p.enrichFromUserinfoEndpoint(ctx, s); err != nil { + logger.Errorf("Warning: Profile URL request failed: %s", err) + } + + // If a mandatory email wasn't set, error at this point. + if s.Email == "" { + return errors.New("neither the id_token nor the profileURL set an email") + } + return nil +} + +// enrichFromUserinfoEndpoint enriches a session's Email & Groups via the JSON response of +// an OIDC profile URL +func (p *CIDAASProvider) enrichFromUserinfoEndpoint(ctx context.Context, s *sessions.SessionState) error { + // profile url is userinfo url in case of Cidaas + respJSON, err := requests.New(p.ProfileURL.String()). + WithContext(ctx). + WithHeaders(makeOIDCHeader(s.AccessToken)). + Do(). + UnmarshalSimpleJSON() + if err != nil { + return err + } + + email, err := respJSON.Get(p.EmailClaim).String() + if err == nil && s.Email == "" { + s.Email = email + } + + groups, err := p.extractGroups(respJSON) + if err != nil { + return fmt.Errorf("extracting groups failed: %w", err) + } + + s.Groups = groups + return nil +} + +func (p *CIDAASProvider) extractGroups(respJSON *simplejson.Json) ([]string, error) { + rawGroupsClaim, err := respJSON.Get(p.GroupsClaim).MarshalJSON() + if err != nil { + return nil, err + } + + var groupsClaimList GroupsClaimList + err = json.Unmarshal(rawGroupsClaim, &groupsClaimList) + if err != nil { + return nil, err + } + + var groups []string + for _, group := range groupsClaimList { + for _, role := range group.Roles { + groups = append(groups, fmt.Sprintf("%s:%s", group.GroupID, role)) + } + } + + // Cidaas specific roles + if rolesVal, rolesClaimExists := respJSON.CheckGet("roles"); rolesClaimExists { + cidaasRoles, err := rolesVal.StringArray() + if err != nil { + return nil, fmt.Errorf("unmarshal roles failed: %w", err) + } + + for _, role := range cidaasRoles { + groups = append(groups, fmt.Sprintf("%s:%s", CidaasGroupName, role)) + } + } + + return groups, nil +} diff --git a/providers/cidaas_test.go b/providers/cidaas_test.go new file mode 100644 index 00000000..a9ee4e97 --- /dev/null +++ b/providers/cidaas_test.go @@ -0,0 +1,493 @@ +package providers + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + + "github.com/coreos/go-oidc/v3/oidc" + "github.com/stretchr/testify/assert" + + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" +) + +func newCidaasProvider(serverURL *url.URL) *CIDAASProvider { + providerData := &ProviderData{ + ProviderName: "cidaas", + ClientID: oidcClientID, + ClientSecret: oidcSecret, + LoginURL: &url.URL{ + Scheme: serverURL.Scheme, + Host: serverURL.Host, + Path: "/login/oauth/authorize"}, + RedeemURL: &url.URL{ + Scheme: serverURL.Scheme, + Host: serverURL.Host, + Path: "/login/oauth/access_token"}, + ProfileURL: &url.URL{ + Scheme: serverURL.Scheme, + Host: serverURL.Host, + Path: "/profile"}, + ValidateURL: &url.URL{ + Scheme: serverURL.Scheme, + Host: serverURL.Host, + Path: "/api"}, + Scope: "openid profile offline_access roles groups", + EmailClaim: "email", + GroupsClaim: "groups", + Verifier: oidc.NewVerifier( + oidcIssuer, + mockJWKS{}, + &oidc.Config{ClientID: oidcClientID}, + ), + } + cfg := options.Provider{ + Type: options.CidaasProvider, + } + + p := NewCIDAASProvider(providerData, cfg) + + return p +} + +func newCidaasServer(pathBodyMap map[string][]byte) (*url.URL, *httptest.Server) { + s := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + body, ok := pathBodyMap[r.URL.Path] + if !ok { + rw.WriteHeader(404) + return + } + rw.Header().Add("content-type", "application/json") + _, _ = rw.Write(body) + })) + u, _ := url.Parse(s.URL) + return u, s +} + +func newTestCidaasSetup(pathToBodyMap map[string][]byte) (*httptest.Server, *CIDAASProvider) { + redeemURL, server := newCidaasServer(pathToBodyMap) + provider := newCidaasProvider(redeemURL) + return server, provider +} + +func TestCidaasProvider_EnrichSession(t *testing.T) { + testCases := map[string]struct { + ExistingSession *sessions.SessionState + EmailClaim string + GroupsClaim string + ProfileJSON map[string]interface{} + ExpectedError error + ExpectedSession *sessions.SessionState + }{ + "Missing Email Only in Profile URL": { + ExistingSession: &sessions.SessionState{ + User: "missing.email", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "email": "found@email.com", + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "missing.email", + Email: "found@email.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Email with Custom Claim": { + ExistingSession: &sessions.SessionState{ + User: "missing.email", + Groups: []string{"already", "populated"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "weird", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "weird": "weird@claim.com", + "groups": []map[string]interface{}{ + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "missing.email", + Email: "weird@claim.com", + Groups: []string{"CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Email not in Profile URL": { + ExistingSession: &sessions.SessionState{ + User: "missing.email", + Groups: []string{"already", "populated"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "groups": []map[string]interface{}{ + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: errors.New("neither the id_token nor the profileURL set an email"), + ExpectedSession: &sessions.SessionState{ + User: "missing.email", + Groups: []string{"CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Groups": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: nil, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "email": "new@thing.com", + "groups": []map[string]interface{}{ + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Empty Groups Claims": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "email": "new@thing.com", + "groups": []map[string]interface{}{ + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Groups with Custom Claim": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: nil, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups2", + ProfileJSON: map[string]interface{}{ + "email": "already@populated.com", + "groups2": []map[string]interface{}{ + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d40", + "groupId": "CIDAAS_ADMINS", + "path": "/CIDAAS_ADMINS/", + "roles": []string{"ADMIN"}, + }, + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d39", + "groupId": "customers", + "groupType": "Customers", + "path": "/customers/", + "roles": []string{ + "CUSTOMER_ACCOUNT_LOGIN", + "GROUP_ADMIN", + }, + }, + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"CIDAAS_ADMINS:ADMIN", "customers:CUSTOMER_ACCOUNT_LOGIN", "customers:GROUP_ADMIN", "CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Just format Groups": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: nil, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups2", + ProfileJSON: map[string]interface{}{ + "email": "already@populated.com", + "groups2": []map[string]interface{}{ + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d39", + "groupId": "customers", + "groupType": "Customers", + "path": "/customers/", + "roles": []string{ + "CUSTOMER_ACCOUNT_LOGIN", + "GROUP_ADMIN", + }, + }, + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"customers:CUSTOMER_ACCOUNT_LOGIN", "customers:GROUP_ADMIN", "CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Groups String Profile URL Response": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: nil, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "groups": []map[string]interface{}{ + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d40", + "groupId": "CIDAAS_ADMINS", + "path": "/CIDAAS_ADMINS/", + "roles": []string{"ADMIN"}, + }, + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d39", + "groupId": "customers", + "groupType": "Customers", + "path": "/customers/", + "roles": []string{ + "CUSTOMER_ACCOUNT_LOGIN", + "GROUP_ADMIN", + }, + }, + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"CIDAAS_ADMINS:ADMIN", "customers:CUSTOMER_ACCOUNT_LOGIN", "customers:GROUP_ADMIN", "CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Groups in both Claims and Profile URL": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "email": "new@thing.com", + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + } + for testName, tc := range testCases { + t.Run(testName, func(t *testing.T) { + path := "/userinfo/" + jsonResp, err := json.Marshal(tc.ProfileJSON) + assert.NoError(t, err) + + server, provider := newTestCidaasSetup(map[string][]byte{path: jsonResp}) + provider.ProfileURL, err = url.Parse(fmt.Sprintf("%s%s", server.URL, path)) + assert.NoError(t, err) + + provider.EmailClaim = tc.EmailClaim + provider.GroupsClaim = tc.GroupsClaim + defer server.Close() + + err = provider.EnrichSession(context.Background(), tc.ExistingSession) + if tc.ExpectedError != nil { + assert.EqualError(t, err, tc.ExpectedError.Error()) + } else { + assert.NoError(t, err) + } + assert.Equal(t, *tc.ExpectedSession, *tc.ExistingSession) + }) + } +} + +func TestCidaasProvider_RefreshSession(t *testing.T) { + testCases := map[string]struct { + ExistingSession *sessions.SessionState + EmailClaim string + GroupsClaim string + ProfileJSON map[string]interface{} + RedeemJSON redeemTokenResponse + ExpectedRefreshed bool + ExpectedError error + ExpectedEmail string + ExpectedUser string + }{ + "Refresh session successfully": { + ExistingSession: &sessions.SessionState{ + User: "session.is.not.locked", + Email: "found@email.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + RedeemJSON: redeemTokenResponse{ + AccessToken: accessToken, + ExpiresIn: 10, + TokenType: "Bearer", + RefreshToken: refreshToken, + }, + ExpectedRefreshed: true, + ExpectedError: nil, + ExpectedEmail: defaultIDToken.Email, + ExpectedUser: defaultIDToken.Subject, + }, + "Unable to refresh session": { + ExistingSession: &sessions.SessionState{ + User: "session.is.unable.to.refresh", + Email: "found@email.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + ExpectedRefreshed: false, + ExpectedError: fmt.Errorf("unable to redeem refresh token: failed to get token: oauth2: server response missing access_token"), + ExpectedUser: "session.is.unable.to.refresh", + ExpectedEmail: "found@email.com", + }, + } + for testName, tc := range testCases { + t.Run(testName, func(t *testing.T) { + idToken, _ := newSignedTestIDToken(defaultIDToken) + tc.RedeemJSON.IDToken = idToken + redeemPath := "/token/" + redeemJSONResp, err := json.Marshal(tc.RedeemJSON) + assert.NoError(t, err) + + serverURL, server := newCidaasServer( + map[string][]byte{ + redeemPath: redeemJSONResp, + }) + provider := newCidaasProvider(serverURL) + + // Disable session enrichment, because we want to focus on refreshing logic + provider.ProfileURL, err = url.Parse("") + assert.NoError(t, err) + provider.RedeemURL, err = url.Parse(fmt.Sprintf("%s%s", server.URL, redeemPath)) + assert.NoError(t, err) + + provider.GroupsClaim = tc.GroupsClaim + defer server.Close() + + var refreshed bool + refreshed, err = provider.RefreshSession(context.Background(), tc.ExistingSession) + + if tc.ExpectedError != nil { + assert.EqualError(t, err, tc.ExpectedError.Error()) + } else { + assert.NoError(t, err) + } + assert.Equal(t, tc.ExpectedRefreshed, refreshed) + assert.Equal(t, tc.ExpectedEmail, tc.ExistingSession.Email) + assert.Equal(t, tc.ExpectedUser, tc.ExistingSession.User) + }) + } +} diff --git a/providers/providers.go b/providers/providers.go index 8bc5ff88..ec00f412 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -45,6 +45,8 @@ func NewProvider(providerConfig options.Provider) (Provider, error) { return NewMicrosoftEntraIDProvider(providerData, providerConfig), nil case options.BitbucketProvider: return NewBitbucketProvider(providerData, providerConfig.BitbucketConfig), nil + case options.CidaasProvider: + return NewCIDAASProvider(providerData, providerConfig), nil case options.DigitalOceanProvider: return NewDigitalOceanProvider(providerData), nil case options.FacebookProvider: @@ -188,7 +190,8 @@ func providerRequiresOIDCProviderVerifier(providerType options.ProviderType) (bo options.GoogleProvider, options.KeycloakProvider, options.LinkedInProvider, options.LoginGovProvider, options.NextCloudProvider, options.SourceHutProvider: return false, nil - case options.ADFSProvider, options.AzureProvider, options.GitLabProvider, options.KeycloakOIDCProvider, options.OIDCProvider, options.MicrosoftEntraIDProvider: + case options.OIDCProvider, options.ADFSProvider, options.AzureProvider, options.CidaasProvider, + options.GitLabProvider, options.KeycloakOIDCProvider, options.MicrosoftEntraIDProvider: return true, nil default: return false, fmt.Errorf("unknown provider type: %s", providerType) From 744b31a2c6d6338b09935f7ce0946f2b5f830075 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 18 Aug 2025 14:27:19 +0200 Subject: [PATCH 072/130] chore(dep): upgrade to latest golang 1.24.6 (#3166) Signed-off-by: Jan Larwig --- CHANGELOG.md | 4 ++++ go.mod | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6909163..7bcc843b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Release Highlights +- 🕵️‍♀️ Vulnerabilities have been addressed + - [CVE-2025-47907](https://pkg.go.dev/vuln/GO-2025-3849) + ## Important Notes ## Breaking Changes @@ -9,6 +12,7 @@ ## Changes since v7.11.0 - [#2273](https://github.com/oauth2-proxy/oauth2-proxy/pull/2273) feat: add Cidaas provider (@Bibob7, @Teko012) +- [#3166](https://github.com/oauth2-proxy/oauth2-proxy/pull/3166) chore(dep): upgrade to latest golang 1.24.6 (@tuunit) # V7.11.0 diff --git a/go.mod b/go.mod index 044f2c23..24f316e4 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.24.5 +go 1.24.6 require ( cloud.google.com/go/compute/metadata v0.7.0 From 82e016954caf174adbe573dafc41108d2efb076f Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 14:27:29 +0200 Subject: [PATCH 073/130] chore(deps): update actions/checkout action to v5 (#3164) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 4 ++-- .github/workflows/codeql.yml | 2 +- .github/workflows/create-release.yml | 2 +- .github/workflows/docs.yml | 4 ++-- .github/workflows/nightly.yml | 2 +- .github/workflows/publish-release.yml | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 906b5eb5..e33c9229 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,7 @@ jobs: COVER: true steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Go uses: actions/setup-go@v5 @@ -60,7 +60,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up QEMU uses: docker/setup-qemu-action@v3 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index df63060c..d3ebda1d 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -32,7 +32,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index 8a0008bc..9ab0d79f 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: master fetch-depth: 0 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index a60f0359..81ab689a 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -14,7 +14,7 @@ jobs: if: github.event_name == 'pull_request' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup Pages id: pages @@ -35,7 +35,7 @@ jobs: if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - uses: actions/setup-node@v4 with: diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index b2a69d95..8b14174b 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -12,7 +12,7 @@ jobs: if: github.repository == 'oauth2-proxy/oauth2-proxy' steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: master fetch-depth: 0 diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 9ebf4b6c..0aeff237 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -20,7 +20,7 @@ jobs: tag: ${{ steps.tag.outputs.version }} steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: ${{ github.event.pull_request.merge_commit_sha }} fetch-depth: 0 @@ -100,7 +100,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: ${{ needs.publish.outputs.tag }} fetch-depth: 0 From 26813d3cddafc37c6997f75c7a5e1dfb4a400f39 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 14:27:37 +0200 Subject: [PATCH 074/130] chore(deps): update dependency golangci/golangci-lint to v2.4.0 (#3161) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e33c9229..b8bcd580 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.2.2 + GOLANGCI_LINT_VERSION: v2.4.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 0aeff237..f45debab 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.2.2 + GOLANGCI_LINT_VERSION: v2.4.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter From 3978b2f27fd4af09ae2103aa337768ab0bc5a809 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 14:27:46 +0200 Subject: [PATCH 075/130] chore(deps): update docker-compose (#3160) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index f3f4f900..92c1dedf 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -39,7 +39,7 @@ services: httpbin: {} gitea: - image: gitea/gitea:1.24.3 + image: gitea/gitea:1.24.5 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 3875eda9..91374fbb 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -78,7 +78,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.2 + image: gcr.io/etcd-development/etcd:v3.6.4 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index d9d4897a..86363400 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.27 + image: traefik:v2.11.28 volumes: - "./traefik:/etc/traefik" ports: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 02c8a165..aaae1551 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -52,7 +52,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.2 + image: gcr.io/etcd-development/etcd:v3.6.4 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From f18a0b7b0744eac3c0696764aa6ccdcc08856b0c Mon Sep 17 00:00:00 2001 From: jet <71936688+jet-go@users.noreply.github.com> Date: Tue, 19 Aug 2025 14:56:16 +0900 Subject: [PATCH 076/130] feat: allow disable-keep-alives configuration in upstream (#3156) Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/alpha_config.md | 1 + docs/docs/configuration/overview.md | 1 + pkg/apis/options/legacy_options.go | 13 +++++++++---- pkg/apis/options/legacy_options_test.go | 11 +++++++++++ pkg/apis/options/upstreams.go | 4 ++++ pkg/upstream/http.go | 4 ++++ pkg/upstream/http_test.go | 26 +++++++++++++++++++------ 8 files changed, 51 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bcc843b..dce52ba7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - [#2273](https://github.com/oauth2-proxy/oauth2-proxy/pull/2273) feat: add Cidaas provider (@Bibob7, @Teko012) - [#3166](https://github.com/oauth2-proxy/oauth2-proxy/pull/3166) chore(dep): upgrade to latest golang 1.24.6 (@tuunit) +- [#3156](https://github.com/oauth2-proxy/oauth2-proxy/pull/3156) feat: allow disable-keep-alives configuration for upstream (@jet-go) # V7.11.0 diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 018a2941..28645ceb 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -551,6 +551,7 @@ Requests will be proxied to this upstream if the path matches the request path. | `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | | `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | | `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | ### UpstreamConfig diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 7c216dfb..b159df09 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -261,6 +261,7 @@ Provider specific options can be found on their respective subpages. | flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | | flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | | flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--disable-keep-alives`
toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false | | flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | | flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index a2c5f4e3..12975225 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -31,10 +31,11 @@ type LegacyOptions struct { func NewLegacyOptions() *LegacyOptions { return &LegacyOptions{ LegacyUpstreams: LegacyUpstreams{ - PassHostHeader: true, - ProxyWebSockets: true, - FlushInterval: DefaultUpstreamFlushInterval, - Timeout: DefaultUpstreamTimeout, + PassHostHeader: true, + ProxyWebSockets: true, + FlushInterval: DefaultUpstreamFlushInterval, + Timeout: DefaultUpstreamTimeout, + DisableKeepAlives: false, }, LegacyHeaders: LegacyHeaders{ @@ -105,6 +106,7 @@ type LegacyUpstreams struct { SSLUpstreamInsecureSkipVerify bool `flag:"ssl-upstream-insecure-skip-verify" cfg:"ssl_upstream_insecure_skip_verify"` Upstreams []string `flag:"upstream" cfg:"upstreams"` Timeout time.Duration `flag:"upstream-timeout" cfg:"upstream_timeout"` + DisableKeepAlives bool `flag:"disable-keep-alives" cfg:"disable_keep_alives"` } func legacyUpstreamsFlagSet() *pflag.FlagSet { @@ -116,6 +118,7 @@ func legacyUpstreamsFlagSet() *pflag.FlagSet { flagSet.Bool("ssl-upstream-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS upstreams") flagSet.StringSlice("upstream", []string{}, "the http url(s) of the upstream endpoint, file:// paths for static files or static:// for static response. Routing is based on the path") flagSet.Duration("upstream-timeout", DefaultUpstreamTimeout, "maximum amount of time the server will wait for a response from the upstream") + flagSet.Bool("disable-keep-alives", false, "disable HTTP keep-alive connections to the upstream server") return flagSet } @@ -144,6 +147,7 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { ProxyWebSockets: &l.ProxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, + DisableKeepAlives: l.DisableKeepAlives, } switch u.Scheme { @@ -176,6 +180,7 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { upstream.ProxyWebSockets = nil upstream.FlushInterval = nil upstream.Timeout = nil + upstream.DisableKeepAlives = false case "unix": upstream.Path = "/" } diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 84d7661f..9481cf95 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -24,6 +24,7 @@ var _ = Describe("Legacy Options", func() { legacyOpts.LegacyUpstreams.SSLUpstreamInsecureSkipVerify = true legacyOpts.LegacyUpstreams.Upstreams = []string{"http://foo.bar/baz", "file:///var/lib/website#/bar", "static://204"} legacyOpts.LegacyProvider.ClientID = "oauth-proxy" + legacyOpts.LegacyUpstreams.DisableKeepAlives = false truth := true staticCode := 204 @@ -38,6 +39,7 @@ var _ = Describe("Legacy Options", func() { PassHostHeader: &truth, ProxyWebSockets: &truth, Timeout: &timeout, + DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, }, { ID: "/bar", @@ -48,6 +50,7 @@ var _ = Describe("Legacy Options", func() { PassHostHeader: &truth, ProxyWebSockets: &truth, Timeout: &timeout, + DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, }, { ID: "static://204", @@ -60,6 +63,7 @@ var _ = Describe("Legacy Options", func() { PassHostHeader: nil, ProxyWebSockets: nil, Timeout: nil, + DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, }, }, } @@ -145,6 +149,7 @@ var _ = Describe("Legacy Options", func() { proxyWebSockets := true flushInterval := Duration(5 * time.Second) timeout := Duration(5 * time.Second) + disableKeepAlives := true // Test cases and expected outcomes validHTTP := "http://foo.bar/baz" @@ -157,6 +162,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, + DisableKeepAlives: disableKeepAlives, } // Test cases and expected outcomes @@ -170,6 +176,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, + DisableKeepAlives: disableKeepAlives, } validFileWithFragment := "file:///var/lib/website#/bar" @@ -182,6 +189,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, + DisableKeepAlives: disableKeepAlives, } validStatic := "static://204" @@ -197,6 +205,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, + DisableKeepAlives: false, } invalidStatic := "static://abc" @@ -212,6 +221,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, + DisableKeepAlives: false, } invalidHTTP := ":foo" @@ -226,6 +236,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: proxyWebSockets, FlushInterval: time.Duration(flushInterval), Timeout: time.Duration(timeout), + DisableKeepAlives: disableKeepAlives, } upstreams, err := legacyUpstreams.convert() diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index 971d151e..b3c7195f 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -93,4 +93,8 @@ type Upstream struct { // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. Timeout *Duration `json:"timeout,omitempty"` + + // DisableKeepAlives disables HTTP keep-alive connections to the upstream server. + // Defaults to false. + DisableKeepAlives bool `json:"disableKeepAlives,omitempty"` } diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 56fcc23e..7a0e6e84 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -166,6 +166,10 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr proxy.ErrorHandler = errorHandler } + // Pass on DisableKeepAlives to the transport settings + // to allow for disabling HTTP keep-alive connections + transport.DisableKeepAlives = upstream.DisableKeepAlives + // Apply the customized transport to our proxy before returning it proxy.Transport = transport diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index 16f75f2d..31476df0 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -372,12 +372,13 @@ var _ = Describe("HTTP Upstream Suite", func() { }) type newUpstreamTableInput struct { - proxyWebSockets bool - flushInterval options.Duration - skipVerify bool - sigData *options.SignatureData - errorHandler func(http.ResponseWriter, *http.Request, error) - timeout options.Duration + proxyWebSockets bool + flushInterval options.Duration + skipVerify bool + sigData *options.SignatureData + errorHandler func(http.ResponseWriter, *http.Request, error) + timeout options.Duration + disableKeepAlives bool } DescribeTable("newHTTPUpstreamProxy", @@ -391,6 +392,7 @@ var _ = Describe("HTTP Upstream Suite", func() { InsecureSkipTLSVerify: in.skipVerify, ProxyWebSockets: &in.proxyWebSockets, Timeout: &in.timeout, + DisableKeepAlives: in.disableKeepAlives, } handler := newHTTPUpstreamProxy(upstream, u, in.sigData, in.errorHandler) @@ -412,6 +414,9 @@ var _ = Describe("HTTP Upstream Suite", func() { if in.skipVerify { Expect(transport.TLSClientConfig.InsecureSkipVerify).To(Equal(true)) } + if in.disableKeepAlives { + Expect(transport.DisableKeepAlives).To(Equal(true)) + } }, Entry("with proxy websockets", &newUpstreamTableInput{ proxyWebSockets: true, @@ -463,6 +468,15 @@ var _ = Describe("HTTP Upstream Suite", func() { errorHandler: nil, timeout: options.Duration(5 * time.Second), }), + Entry("with a DisableKeepAlives", &newUpstreamTableInput{ + proxyWebSockets: false, + flushInterval: defaultFlushInterval, + skipVerify: false, + sigData: nil, + errorHandler: nil, + timeout: defaultTimeout, + disableKeepAlives: true, + }), ) Context("with a websocket proxy", func() { From 8c1b2b63bfdba1118f55464a1554a672be9637d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Richard=20Bre=C5=BE=C3=A1k?= Date: Tue, 19 Aug 2025 08:40:36 +0200 Subject: [PATCH 077/130] fix: Gitea team membership (#3150) * bugfix: Gitaa team membership Gitea doesn't properly fill in all the fields like GitHub, so implement a series of fallbacks. Signed-off-by: magic_rb * add changelog, documentation and fix groups list Signed-off-by: Jan Larwig --------- Signed-off-by: magic_rb Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/providers/gitea.md | 4 +-- providers/github.go | 36 ++++++++++++++++++---- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dce52ba7..faecde02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - [#2273](https://github.com/oauth2-proxy/oauth2-proxy/pull/2273) feat: add Cidaas provider (@Bibob7, @Teko012) - [#3166](https://github.com/oauth2-proxy/oauth2-proxy/pull/3166) chore(dep): upgrade to latest golang 1.24.6 (@tuunit) - [#3156](https://github.com/oauth2-proxy/oauth2-proxy/pull/3156) feat: allow disable-keep-alives configuration for upstream (@jet-go) +- [#3150](https://github.com/oauth2-proxy/oauth2-proxy/pull/3150) fix: Gitea team membership (@MagicRB, @tuunit) # V7.11.0 diff --git a/docs/docs/configuration/providers/gitea.md b/docs/docs/configuration/providers/gitea.md index 996a5ddb..6c679dd0 100644 --- a/docs/docs/configuration/providers/gitea.md +++ b/docs/docs/configuration/providers/gitea.md @@ -1,10 +1,10 @@ --- id: gitea -title: Gitea +title: Gitea / Forgejo --- :::note -This is not actually its own provider. For more details and options please refer to the [GitHub Provider Options](github.md) +This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md) ::: 1. Create a new application: `https://< your gitea host >/user/settings/applications` diff --git a/providers/github.go b/providers/github.go index 749fcc03..09f10083 100644 --- a/providers/github.go +++ b/providers/github.go @@ -460,10 +460,14 @@ func (p *GitHubProvider) getOrgAndTeam(ctx context.Context, s *sessions.SessionS } func (p *GitHubProvider) getOrgs(ctx context.Context, s *sessions.SessionState) error { - // https://docs.github.com/en/rest/orgs/orgs#list-organizations-for-the-authenticated-user type Organization struct { - Login string `json:"login"` + // Support for Github organizations + // https://docs.github.com/en/rest/orgs/orgs#list-organizations-for-the-authenticated-user + Login string `json:"login,omitempty"` + // Support for Gitea organizations + // https://docs.gitea.com/api/1.24/#tag/organization/operation/orgGetAll + Name string `json:"name,omitempty"` } pn := 1 @@ -490,8 +494,16 @@ func (p *GitHubProvider) getOrgs(ctx context.Context, s *sessions.SessionState) } for _, org := range orgs { - logger.Printf("Member of Github Organization:%q", org.Login) - s.Groups = append(s.Groups, org.Login) + var orgName string + if len(org.Login) > 0 { + orgName = org.Login + logger.Printf("Member of Github Organization: %q", orgName) + } else { + orgName = org.Name + logger.Printf("Member of Gitea Organization: %q", orgName) + } + + s.Groups = append(s.Groups, orgName) } pn++ } @@ -506,6 +518,7 @@ func (p *GitHubProvider) getTeams(ctx context.Context, s *sessions.SessionState) Slug string `json:"slug"` Org struct { Login string `json:"login"` + Name string `json:"name"` } `json:"organization"` } @@ -533,8 +546,19 @@ func (p *GitHubProvider) getTeams(ctx context.Context, s *sessions.SessionState) } for _, team := range teams { - logger.Printf("Member of Github Organization/Team: %q/%q", team.Org.Login, team.Slug) - s.Groups = append(s.Groups, fmt.Sprintf("%s%s%s", team.Org.Login, orgTeamSeparator, team.Slug)) + var orgName, teamName string + + if len(team.Org.Login) > 0 { + orgName = team.Org.Login + teamName = team.Slug + logger.Printf("Member of Github Organization/Team: %q/%q", orgName, teamName) + } else { + orgName = team.Org.Name + teamName = team.Name + logger.Printf("Member of Gitea Organization/Team: %q/%q", orgName, teamName) + } + + s.Groups = append(s.Groups, fmt.Sprintf("%s%s%s", orgName, orgTeamSeparator, teamName)) } pn++ From 413d4f697632a270516a482910a157470b58f28f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 19 Aug 2025 05:58:41 +0000 Subject: [PATCH 078/130] add new docs version 7.12.x Signed-off-by: Jan Larwig --- .../version-7.12.x/behaviour.md | 11 + .../version-7.12.x/community/contribution.md | 89 +++ .../version-7.12.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 565 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 318 ++++++++++ .../version-7.12.x/configuration/overview.md | 406 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/cidaas.md | 37 ++ .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 75 +++ .../configuration/providers/index.md | 44 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 ++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../configuration/providers/sourcehut.md | 25 + .../version-7.12.x/configuration/sessions.md | 99 +++ .../configuration/systemd_socket.md | 43 ++ .../version-7.12.x/configuration/tls.md | 85 +++ .../version-7.12.x/features/endpoints.md | 47 ++ .../version-7.12.x/installation.md | 32 + docs/versioned_docs/version-7.12.x/welcome.md | 23 + .../version-7.12.x-sidebars.json | 83 +++ docs/versions.json | 1 + 34 files changed, 3106 insertions(+) create mode 100644 docs/versioned_docs/version-7.12.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.12.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.12.x/community/security.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.12.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/cidaas.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.12.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.12.x/installation.md create mode 100644 docs/versioned_docs/version-7.12.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.12.x-sidebars.json diff --git a/docs/versioned_docs/version-7.12.x/behaviour.md b/docs/versioned_docs/version-7.12.x/behaviour.md new file mode 100644 index 00000000..e063d4f9 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/behaviour.md @@ -0,0 +1,11 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) +3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set +4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) + +Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). diff --git a/docs/versioned_docs/version-7.12.x/community/contribution.md b/docs/versioned_docs/version-7.12.x/community/contribution.md new file mode 100644 index 00000000..92255eda --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/community/contribution.md @@ -0,0 +1,89 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +This project is currently still using go 1.22. You can follow the installation guide for go [here.](https://go.dev/doc/install) And you can find go version 1.22 in the archived section [here.](https://go.dev/dl/) + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:5556 + diff --git a/docs/versioned_docs/version-7.12.x/community/security.md b/docs/versioned_docs/version-7.12.x/community/security.md new file mode 100644 index 00000000..c24b57d9 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md new file mode 100644 index 00000000..28645ceb --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md @@ -0,0 +1,565 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### Duration +#### (`string` alias) + +(**Appears on:** [Upstream](#upstream)) + +Duration is as string representation of a period of time. +A duration string is a is a possibly signed sequence of decimal numbers, +each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md.tmpl new file mode 100644 index 00000000..8258201f --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.12.x/configuration/integration.md b/docs/versioned_docs/version-7.12.x/configuration/integration.md new file mode 100644 index 00000000..05d39281 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/integration.md @@ -0,0 +1,318 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. +Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. +Note that `nginxinc/kubernetes-ingress` does not include the Lua module. + +```yaml +nginx.ingress.kubernetes.io/auth-response-headers: Authorization +nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri +nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth +nginx.ingress.kubernetes.io/configuration-snippet: | + auth_request_set $name_upstream_1 $upstream_cookie_name_1; + + access_by_lua_block { + if ngx.var.name_upstream_1 ~= "" then + ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") + end + } +``` +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.12.x/configuration/overview.md b/docs/versioned_docs/version-7.12.x/configuration/overview.md new file mode 100644 index 00000000..b159df09 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/overview.md @@ -0,0 +1,406 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--disable-keep-alives`
toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.12.x/configuration/providers/adfs.md new file mode 100644 index 00000000..ec8d72d2 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.12.x/configuration/providers/bitbucket.md new file mode 100644 index 00000000..e31de752 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/cidaas.md b/docs/versioned_docs/version-7.12.x/configuration/providers/cidaas.md new file mode 100644 index 00000000..7a987018 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/cidaas.md @@ -0,0 +1,37 @@ +--- +id: cidaas +title: Cidaas +--- + +[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services. +It supports various protocols including OpenID Connect, OAuth 2.0, and SAML. + +However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet. +The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy. + +Example of groups and roles in Cidaas: + +```json +{ + "groups": [ + { + "groupId": "group1", + "roles": ["role1", "role2"] + }, + { + "groupId": "group2", + "roles": ["role3"] + } + ] +} +``` + +This will be transformed into a flat list of groups: + +```json +{ + "groups": ["group1:role1", "group2:role2", "group2:role3"] +} +``` + +Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md). \ No newline at end of file diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.12.x/configuration/providers/digitalocean.md new file mode 100644 index 00000000..f6a1e891 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.12.x/configuration/providers/facebook.md new file mode 100644 index 00000000..352c95ce --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.12.x/configuration/providers/gitea.md new file mode 100644 index 00000000..6c679dd0 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea / Forgejo +--- + +:::note +This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/github.md b/docs/versioned_docs/version-7.12.x/configuration/providers/github.md new file mode 100644 index 00000000..cebca314 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md new file mode 100644 index 00000000..4cdbbbe1 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/google.md b/docs/versioned_docs/version-7.12.x/configuration/providers/google.md new file mode 100644 index 00000000..ac2a7dfa --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/google.md @@ -0,0 +1,75 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.member.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/index.md b/docs/versioned_docs/version-7.12.x/configuration/providers/index.md new file mode 100644 index 00000000..713b5cb9 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/index.md @@ -0,0 +1,44 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [Cidaas](cidaas.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak.md new file mode 100644 index 00000000..11a1abca --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 00000000..b29096e3 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.12.x/configuration/providers/linkedin.md new file mode 100644 index 00000000..7d26ec43 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.12.x/configuration/providers/login_gov.md new file mode 100644 index 00000000..badbe48e --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 00000000..4feefc68 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md new file mode 100644 index 00000000..c5d9594e --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.12.x/configuration/providers/nextcloud.md new file mode 100644 index 00000000..85ebff03 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.12.x/configuration/providers/openid_connect.md new file mode 100644 index 00000000..de170058 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md new file mode 100644 index 00000000..88d14622 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](#email-authentication). + diff --git a/docs/versioned_docs/version-7.12.x/configuration/sessions.md b/docs/versioned_docs/version-7.12.x/configuration/sessions.md new file mode 100644 index 00000000..e2037817 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.12.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.12.x/configuration/systemd_socket.md new file mode 100644 index 00000000..642e6f3f --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.12.x/configuration/tls.md b/docs/versioned_docs/version-7.12.x/configuration/tls.md new file mode 100644 index 00000000..68344b22 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.12.x/features/endpoints.md b/docs/versioned_docs/version-7.12.x/features/endpoints.md new file mode 100644 index 00000000..3ec1e2aa --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/features/endpoints.md @@ -0,0 +1,47 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.12.x/installation.md b/docs/versioned_docs/version-7.12.x/installation.md new file mode 100644 index 00000000..b6fc9d01 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.12.x/welcome.md b/docs/versioned_docs/version-7.12.x/welcome.md new file mode 100644 index 00000000..7bceadd8 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.12.x-sidebars.json b/docs/versioned_sidebars/version-7.12.x-sidebars.json new file mode 100644 index 00000000..0dbf04bd --- /dev/null +++ b/docs/versioned_sidebars/version-7.12.x-sidebars.json @@ -0,0 +1,83 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index b4f8a9f5..ada187c6 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.12.x", "7.11.x", "7.10.x", "7.9.x", From b4b69a6cb370e863d45c17f90a9567b0ff474b67 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 19 Aug 2025 05:58:41 +0000 Subject: [PATCH 079/130] update to release version v7.12.0 --- CHANGELOG.md | 10 ++++++++++ .../local-environment/docker-compose-alpha-config.yaml | 2 +- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-keycloak.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- docs/versioned_docs/version-7.12.x/installation.md | 2 +- 9 files changed, 18 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index faecde02..7717e659 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Release Highlights +## Important Notes + +## Breaking Changes + +## Changes since v7.12.0 + +# V7.12.0 + +## Release Highlights + - 🕵️‍♀️ Vulnerabilities have been addressed - [CVE-2025-47907](https://pkg.go.dev/vuln/GO-2025-3849) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 55b4649e..a43dc457 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 92c1dedf..14228880 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 1796b65c..faa1b47b 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 91374fbb..668e61ff 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 86363400..b56ff12e 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index aaae1551..6490ca8e 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index b6fc9d01..bba3f4c3 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.12.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.12.x/installation.md b/docs/versioned_docs/version-7.12.x/installation.md index b6fc9d01..bba3f4c3 100644 --- a/docs/versioned_docs/version-7.12.x/installation.md +++ b/docs/versioned_docs/version-7.12.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.12.0`) b. Using Go to install the latest release ```bash From 7294eebce1d626f1a47a1b4567b987f78365ad23 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 19 Aug 2025 08:40:59 +0200 Subject: [PATCH 080/130] add changelog entry for v7.12.0 Signed-off-by: Jan Larwig --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7717e659..f2c9b441 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ - 🕵️‍♀️ Vulnerabilities have been addressed - [CVE-2025-47907](https://pkg.go.dev/vuln/GO-2025-3849) +- 🦸 Support for Cidaas IDP +- 🐛 Squashed some bugs + ## Important Notes From 8afb047e01906a20d73f7578ef5d54b592e2a4ef Mon Sep 17 00:00:00 2001 From: Conrad Hoffmann <1226676+bitfehler@users.noreply.github.com> Date: Wed, 20 Aug 2025 12:02:32 +0200 Subject: [PATCH 081/130] doc: SourceHut documentation fixes (#3170) * fix: SourceHut documentation - Add it to sidebar and provider index - Fix broken link This fixes an oversight in #2359, where I had not fully understood how the documentation works. Signed-off-by: Conrad Hoffmann * fix: doc build instructions in docs/README.md --------- Signed-off-by: Conrad Hoffmann --- docs/README.md | 2 +- docs/docs/configuration/providers/index.md | 1 + docs/docs/configuration/providers/sourcehut.md | 2 +- docs/sidebars.js | 1 + .../version-7.11.x/configuration/providers/index.md | 1 + .../version-7.11.x/configuration/providers/sourcehut.md | 2 +- .../version-7.12.x/configuration/providers/index.md | 1 + .../version-7.12.x/configuration/providers/sourcehut.md | 2 +- docs/versioned_sidebars/version-7.11.x-sidebars.json | 3 ++- docs/versioned_sidebars/version-7.12.x-sidebars.json | 3 ++- 10 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/README.md b/docs/README.md index 349f3456..5aa1c060 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,7 +19,7 @@ This command starts a local development server and open up a browser window. Mos ## Build ```console -npm build +npm run build ``` This command generates static content into the `build` directory and can be served using any static contents hosting service. diff --git a/docs/docs/configuration/providers/index.md b/docs/docs/configuration/providers/index.md index 713b5cb9..3d3938ff 100644 --- a/docs/docs/configuration/providers/index.md +++ b/docs/docs/configuration/providers/index.md @@ -25,6 +25,7 @@ Valid providers are : - [Microsoft Entra ID](ms_entra_id.md) - [Nextcloud](nextcloud.md) - [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). diff --git a/docs/docs/configuration/providers/sourcehut.md b/docs/docs/configuration/providers/sourcehut.md index 88d14622..2c196bda 100644 --- a/docs/docs/configuration/providers/sourcehut.md +++ b/docs/docs/configuration/providers/sourcehut.md @@ -21,5 +21,5 @@ to the appropriate URLs: The default configuration allows everyone with an account to authenticate. Restricting access is currently only supported by -[email](#email-authentication). +[email](index.md#email-authentication). diff --git a/docs/sidebars.js b/docs/sidebars.js index 3240e7df..0a1bf0b4 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -47,6 +47,7 @@ const sidebars = { "configuration/providers/ms_entra_id", "configuration/providers/nextcloud", "configuration/providers/openid_connect", + "configuration/providers/sourcehut" ], }, 'configuration/session_storage', diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/index.md b/docs/versioned_docs/version-7.11.x/configuration/providers/index.md index b947c09b..248e4380 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/providers/index.md +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/index.md @@ -24,6 +24,7 @@ Valid providers are : - [Microsoft Entra ID](ms_entra_id.md) - [Nextcloud](nextcloud.md) - [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md index 88d14622..2c196bda 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md @@ -21,5 +21,5 @@ to the appropriate URLs: The default configuration allows everyone with an account to authenticate. Restricting access is currently only supported by -[email](#email-authentication). +[email](index.md#email-authentication). diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/index.md b/docs/versioned_docs/version-7.12.x/configuration/providers/index.md index 713b5cb9..3d3938ff 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/providers/index.md +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/index.md @@ -25,6 +25,7 @@ Valid providers are : - [Microsoft Entra ID](ms_entra_id.md) - [Nextcloud](nextcloud.md) - [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md index 88d14622..2c196bda 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md @@ -21,5 +21,5 @@ to the appropriate URLs: The default configuration allows everyone with an account to authenticate. Restricting access is currently only supported by -[email](#email-authentication). +[email](index.md#email-authentication). diff --git a/docs/versioned_sidebars/version-7.11.x-sidebars.json b/docs/versioned_sidebars/version-7.11.x-sidebars.json index 0dbf04bd..3f5eb854 100644 --- a/docs/versioned_sidebars/version-7.11.x-sidebars.json +++ b/docs/versioned_sidebars/version-7.11.x-sidebars.json @@ -46,7 +46,8 @@ "configuration/providers/login_gov", "configuration/providers/ms_entra_id", "configuration/providers/nextcloud", - "configuration/providers/openid_connect" + "configuration/providers/openid_connect", + "configuration/providers/sourcehut" ] }, "configuration/session_storage", diff --git a/docs/versioned_sidebars/version-7.12.x-sidebars.json b/docs/versioned_sidebars/version-7.12.x-sidebars.json index 0dbf04bd..3f5eb854 100644 --- a/docs/versioned_sidebars/version-7.12.x-sidebars.json +++ b/docs/versioned_sidebars/version-7.12.x-sidebars.json @@ -46,7 +46,8 @@ "configuration/providers/login_gov", "configuration/providers/ms_entra_id", "configuration/providers/nextcloud", - "configuration/providers/openid_connect" + "configuration/providers/openid_connect", + "configuration/providers/sourcehut" ] }, "configuration/session_storage", From f1c08a3cd7e0d643dd0808416d1d189879baa8d1 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 25 Sep 2025 20:09:52 +0200 Subject: [PATCH 082/130] chore(deps): update actions/upload-pages-artifact action to v4 (#3194) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 81ab689a..6ae15ac6 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -49,7 +49,7 @@ jobs: npm run build - name: Upload artifact - uses: actions/upload-pages-artifact@v3 + uses: actions/upload-pages-artifact@v4 with: path: ./docs/build From 66cdb9d9398caa44f2596d8e4dda13f1e3c9eff1 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Fri, 26 Sep 2025 04:11:57 +1000 Subject: [PATCH 083/130] doc: update contribution guide to avoid a specific mention of the version of Go being used. (#3157) --- docs/docs/community/contribution.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/docs/community/contribution.md b/docs/docs/community/contribution.md index 92255eda..a8e47349 100644 --- a/docs/docs/community/contribution.md +++ b/docs/docs/community/contribution.md @@ -15,7 +15,9 @@ We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languag # Go version -This project is currently still using go 1.22. You can follow the installation guide for go [here.](https://go.dev/doc/install) And you can find go version 1.22 in the archived section [here.](https://go.dev/dl/) +See the `go.mod` file in the root of this repository for the version of Go used by this project. +You can follow [the installation guide for Go](https://go.dev/doc/install), +and you can find this specific Go version on [the Go downloads page](https://go.dev/dl/). # Preparing your fork Clone your fork, create a feature branch and update the depedencies to get started. From 9168731c7afa26698c7ee84a230b351e2163dee4 Mon Sep 17 00:00:00 2001 From: Richard Ahlquist Date: Sun, 28 Sep 2025 14:48:59 +0200 Subject: [PATCH 084/130] fix(deps): revert actions/upload-pages-artifact action to v3 (#3211) Signed-off-by: Richard Ahlquist --- .github/workflows/docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 6ae15ac6..81ab689a 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -49,7 +49,7 @@ jobs: npm run build - name: Upload artifact - uses: actions/upload-pages-artifact@v4 + uses: actions/upload-pages-artifact@v3 with: path: ./docs/build From a3349add545bce2c25e35c39194add36d3eaec17 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:40:08 +0100 Subject: [PATCH 085/130] chore(deps): update alpine docker tag to v3.22.2 (#3241) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 091ca726..20ed88c9 100644 --- a/Makefile +++ b/Makefile @@ -67,7 +67,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM} DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x -DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.1 +DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.2 DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS} DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push From bccc988366d6d8a1ebd1fc6cd9c40969cc4f91e3 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:41:34 +0100 Subject: [PATCH 086/130] chore(deps): update actions/setup-node action to v6 (#3242) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/create-release.yml | 2 +- .github/workflows/docs.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index 9ab0d79f..ea8fcb02 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -54,7 +54,7 @@ jobs: git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" - name: Setup node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: node-version-file: docs/package.json diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 81ab689a..6f8f7ad6 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -20,7 +20,7 @@ jobs: id: pages uses: actions/configure-pages@v5 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v6 with: # renovate: datasource=node-version depName=node node-version: 22 @@ -37,7 +37,7 @@ jobs: steps: - uses: actions/checkout@v5 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v6 with: # renovate: datasource=node-version depName=node node-version: 22 From 65ef2ca3c946c1ddf64f473db99bb28def648bda Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:42:13 +0100 Subject: [PATCH 087/130] chore(deps): update actions/stale action to v10 (#3193) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/stale.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 2406f695..d14e9935 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/stale@v9 + - uses: actions/stale@v10 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-stale: 180 From 5539e590025c4e66ace6e764675600ade1ebf9fa Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:43:04 +0100 Subject: [PATCH 088/130] chore(deps): update actions/setup-go action to v6 (#3191) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b8bcd580..01826f97 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ jobs: uses: actions/checkout@v5 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version-file: go.mod id: go diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index f45debab..637a6780 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -43,7 +43,7 @@ jobs: id: tag - name: Set up go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version-file: go.mod From e693f4070a42f3f8f133eadfb8367ea842fbfc8c Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:43:22 +0100 Subject: [PATCH 089/130] chore(deps): update actions/labeler action to v6 (#3190) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/labeler.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index b3e85438..6b2762f0 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -9,7 +9,7 @@ jobs: pull-requests: write runs-on: ubuntu-latest steps: - - uses: actions/labeler@v5 + - uses: actions/labeler@v6 with: sync-labels: true dot: true From dea0d0cf44452cd3666790ddc85579c1d4c02d83 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:53:12 +0100 Subject: [PATCH 090/130] chore(deps): update helmv3 (#3189) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/kubernetes/Chart.lock | 8 ++++---- contrib/local-environment/kubernetes/Chart.yaml | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/local-environment/kubernetes/Chart.lock b/contrib/local-environment/kubernetes/Chart.lock index e6774fb2..527eab3b 100644 --- a/contrib/local-environment/kubernetes/Chart.lock +++ b/contrib/local-environment/kubernetes/Chart.lock @@ -1,15 +1,15 @@ dependencies: - name: dex repository: https://charts.dexidp.io - version: 0.23.0 + version: 0.24.0 - name: oauth2-proxy repository: https://oauth2-proxy.github.io/manifests - version: 7.14.1 + version: 7.18.0 - name: httpbin repository: https://conservis.github.io/helm-charts version: 1.1.0 - name: hello-world repository: https://conservis.github.io/helm-charts version: 1.1.0 -digest: sha256:9b18e072db6863053c2967d023929ab4b9c03b6bd84f6529d90fe7a9ec5e315f -generated: "2025-07-20T08:56:43.559585022Z" +digest: sha256:fee913531bfb67e5555e995d8fb040c330e6eb4b5a8c777ceb9841135ea9bb84 +generated: "2025-10-28T06:46:35.38300324Z" diff --git a/contrib/local-environment/kubernetes/Chart.yaml b/contrib/local-environment/kubernetes/Chart.yaml index 3d224378..83c09b47 100644 --- a/contrib/local-environment/kubernetes/Chart.yaml +++ b/contrib/local-environment/kubernetes/Chart.yaml @@ -3,10 +3,10 @@ description: K8S example based on https://kind.sigs.k8s.io name: kubernetes dependencies: - name: dex - version: 0.23.0 + version: 0.24.0 repository: https://charts.dexidp.io - name: oauth2-proxy - version: &chartVersion 7.14.1 + version: &chartVersion 7.18.0 repository: https://oauth2-proxy.github.io/manifests # https://github.com/postmanlabs/httpbin/issues/549 is still in progress, for now using a non-official chart - name: httpbin From a50bbcd6f6fe2e6c0516678fd536848e650ac2f1 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:53:29 +0100 Subject: [PATCH 091/130] chore(deps): update docker-compose (#3188) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 4 ++-- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 14228880..f506c4ac 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -39,7 +39,7 @@ services: httpbin: {} gitea: - image: gitea/gitea:1.24.5 + image: gitea/gitea:1.24.7 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 668e61ff..60343012 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -55,7 +55,7 @@ services: httpbin: {} dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.43.1 + image: ghcr.io/dexidp/dex:v2.44.0 command: dex serve /dex.yaml hostname: dex volumes: @@ -78,7 +78,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.4 + image: gcr.io/etcd-development/etcd:v3.6.5 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index b56ff12e..8bff6b03 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.28 + image: traefik:v2.11.29 volumes: - "./traefik:/etc/traefik" ports: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 6490ca8e..ae9e3bf1 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -29,7 +29,7 @@ services: - httpbin dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.43.1 + image: ghcr.io/dexidp/dex:v2.44.0 command: dex serve /dex.yaml hostname: dex volumes: @@ -52,7 +52,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.4 + image: gcr.io/etcd-development/etcd:v3.6.5 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From 4295f0c1f94a4bb6b50b046ef35b1eb9797cbc77 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 08:00:27 +0100 Subject: [PATCH 092/130] chore(deps): update dependency golangci/golangci-lint to v2.5.0 (#3212) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 01826f97..4764c813 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.4.0 + GOLANGCI_LINT_VERSION: v2.5.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 637a6780..fe27cabe 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.4.0 + GOLANGCI_LINT_VERSION: v2.5.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter From c0a087d7f2bcaf2142f259fd834b4b8af66a4a5b Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 08:03:40 +0100 Subject: [PATCH 093/130] chore(deps): update actions/upload-artifact action to v5 (#3243) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/publish-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index fe27cabe..ccefd1c9 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -64,7 +64,7 @@ jobs: # Upload artifacts in case of workflow failure - name: Upload Artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: oauth2-proxy-artifacts path: | From 51e80f24ef25252d65476cf33e31242e43919af9 Mon Sep 17 00:00:00 2001 From: stagswtf <142280349+stagswtf@users.noreply.github.com> Date: Tue, 28 Oct 2025 00:37:25 -0700 Subject: [PATCH 094/130] fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (#3228) * fix: use GetSecret() in ticket.go makeCookie The makeCookie method in ticket.go was using t.options.Secret directly, which meant cookie-secret-file was not being respected. Updated to use GetSecret() which handles both cookie-secret and cookie-secret-file properly. Also added test coverage for cookie-secret-file functionality. Fixes #3224 Signed-off-by: stagswtf <142280349+stagswtf@users.noreply.github.com> * docs: update CHANGELOG.md for cookie-secret-file fix Signed-off-by: stagswtf <142280349+stagswtf@users.noreply.github.com> * correct PR link and undo file formatting Signed-off-by: stagswtf <142280349+stagswtf@users.noreply.github.com> * fix: error wrapping Signed-off-by: Jan Larwig --------- Signed-off-by: stagswtf <142280349+stagswtf@users.noreply.github.com> Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 4 ++- pkg/sessions/persistence/ticket.go | 11 +++++-- pkg/sessions/tests/session_store_tests.go | 37 +++++++++++++++++++++++ 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f2c9b441..5aefaafa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.12.0 +- [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) + # V7.12.0 ## Release Highlights @@ -119,7 +121,7 @@ For detailed information, migration guidance, and security implications, see the - 🕵️‍♀️ Vulnerabilities have been addressed - [CVE-2025-22871](https://github.com/advisories/GHSA-g9pc-8g42-g6vq) - 🐛 Squashed some bugs - + ## Important Notes ## Breaking Changes diff --git a/pkg/sessions/persistence/ticket.go b/pkg/sessions/persistence/ticket.go index 7855db45..56d6bd9b 100644 --- a/pkg/sessions/persistence/ticket.go +++ b/pkg/sessions/persistence/ticket.go @@ -233,12 +233,17 @@ func (t *ticket) clearCookie(rw http.ResponseWriter, req *http.Request) { // makeCookie makes a cookie, signing the value if present func (t *ticket) makeCookie(req *http.Request, value string, expires time.Duration, now time.Time) (*http.Cookie, error) { if value != "" { - var err error - value, err = encryption.SignedValue(t.options.Secret, t.options.Name, []byte(value), now) + secret, err := t.options.GetSecret() if err != nil { - return nil, err + return nil, fmt.Errorf("retrieving secret failed: %w", err) + } + + value, err = encryption.SignedValue(secret, t.options.Name, []byte(value), now) + if err != nil { + return nil, fmt.Errorf("signing cookie value failed: %w", err) } } + return cookies.MakeCookieFromOptions( req, t.options.Name, diff --git a/pkg/sessions/tests/session_store_tests.go b/pkg/sessions/tests/session_store_tests.go index a4818ef2..05b67d8d 100644 --- a/pkg/sessions/tests/session_store_tests.go +++ b/pkg/sessions/tests/session_store_tests.go @@ -4,6 +4,7 @@ import ( "crypto/rand" "net/http" "net/http/httptest" + "os" "strconv" "strings" "time" @@ -133,6 +134,42 @@ func RunSessionStoreTests(newSS NewSessionStoreFunc, persistentFastForward Persi PersistentSessionStoreInterfaceTests(&input) } }) + + Context("with cookie secret file", func() { + var tmpfile *os.File + var err error + BeforeEach(func() { + tmpfile, err = os.CreateTemp("", "cookie-secret-test") + secretBytes := make([]byte, 32) + tmpfile.Write(secretBytes) + tmpfile.Close() + + input.cookieOpts = &options.Cookie{ + Name: "_oauth2_proxy_file", + Path: "/", + Expire: time.Duration(168) * time.Hour, + Refresh: time.Duration(1) * time.Hour, + Secure: true, + HTTPOnly: true, + SameSite: "", + Secret: "", + SecretFile: tmpfile.Name(), + } + ss, err = newSS(opts, input.cookieOpts) + Expect(err).ToNot(HaveOccurred()) + }) + + AfterEach(func() { + if tmpfile != nil { + os.Remove(tmpfile.Name()) + } + }) + + SessionStoreInterfaceTests(&input) + if persistentFastForward != nil { + PersistentSessionStoreInterfaceTests(&input) + } + }) }) } From ea1dc3f606fa5a5817bc168ecb64c67f792ca25e Mon Sep 17 00:00:00 2001 From: Vincent Privat <146961743+vprivat-ads@users.noreply.github.com> Date: Tue, 28 Oct 2025 08:40:51 +0100 Subject: [PATCH 095/130] Fix typo: diffrerent -> different (#3222) Signed-off-by: Vincent Privat --- docs/docs/configuration/providers/ms_entra_id.md | 2 +- .../version-7.10.x/configuration/providers/ms_entra_id.md | 2 +- .../version-7.11.x/configuration/providers/ms_entra_id.md | 2 +- .../version-7.12.x/configuration/providers/ms_entra_id.md | 2 +- .../version-7.8.x/configuration/providers/ms_entra_id.md | 2 +- .../version-7.9.x/configuration/providers/ms_entra_id.md | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/docs/configuration/providers/ms_entra_id.md b/docs/docs/configuration/providers/ms_entra_id.md index c5d9594e..95fb99bc 100644 --- a/docs/docs/configuration/providers/ms_entra_id.md +++ b/docs/docs/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md index c5d9594e..95fb99bc 100644 --- a/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md index c5d9594e..95fb99bc 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md index c5d9594e..95fb99bc 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md index c5d9594e..95fb99bc 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md index c5d9594e..95fb99bc 100644 --- a/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. From 31b275f5805ee1d6c62906a81274c21587e70a40 Mon Sep 17 00:00:00 2001 From: Schmitt Paul <100230730+paulsc54@users.noreply.github.com> Date: Tue, 28 Oct 2025 08:48:23 +0100 Subject: [PATCH 096/130] docs: clarify ingress-nginx integration and remove Lua block example (#3202) * docs: clarify ingress-nginx integration and remove Lua block example for oauth2-proxy This PR revises the integration guide for oauth2-proxy with ingress-nginx in Kubernetes: Recommends the minimal configuration: just auth-url and auth-signin annotations. Removes the Lua block example, as it did not work in practice despite following nginx documentation and extensive testing. Clearly states that the official ingress-nginx external auth example is the recommended approach for most users. Notes that advanced Lua/cookie handling is only needed for rare, advanced scenarios. Signed-off-by: Jan Larwig * doc: update 3 latest docs versions Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- docs/docs/configuration/integration.md | 20 ++++++------------- .../configuration/integration.md | 20 ++++++------------- .../configuration/integration.md | 20 ++++++------------- .../configuration/integration.md | 20 ++++++------------- 4 files changed, 24 insertions(+), 56 deletions(-) diff --git a/docs/docs/configuration/integration.md b/docs/docs/configuration/integration.md index 05d39281..c57cfa6b 100644 --- a/docs/docs/configuration/integration.md +++ b/docs/docs/configuration/integration.md @@ -77,23 +77,15 @@ server { } ``` -When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. -Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. -Note that `nginxinc/kubernetes-ingress` does not include the Lua module. +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml -nginx.ingress.kubernetes.io/auth-response-headers: Authorization -nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri -nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth -nginx.ingress.kubernetes.io/configuration-snippet: | - auth_request_set $name_upstream_1 $upstream_cookie_name_1; - - access_by_lua_block { - if ngx.var.name_upstream_1 ~= "" then - ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") - end - } +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" ``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". diff --git a/docs/versioned_docs/version-7.10.x/configuration/integration.md b/docs/versioned_docs/version-7.10.x/configuration/integration.md index 05d39281..c57cfa6b 100644 --- a/docs/versioned_docs/version-7.10.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.10.x/configuration/integration.md @@ -77,23 +77,15 @@ server { } ``` -When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. -Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. -Note that `nginxinc/kubernetes-ingress` does not include the Lua module. +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml -nginx.ingress.kubernetes.io/auth-response-headers: Authorization -nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri -nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth -nginx.ingress.kubernetes.io/configuration-snippet: | - auth_request_set $name_upstream_1 $upstream_cookie_name_1; - - access_by_lua_block { - if ngx.var.name_upstream_1 ~= "" then - ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") - end - } +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" ``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". diff --git a/docs/versioned_docs/version-7.11.x/configuration/integration.md b/docs/versioned_docs/version-7.11.x/configuration/integration.md index 05d39281..c57cfa6b 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.11.x/configuration/integration.md @@ -77,23 +77,15 @@ server { } ``` -When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. -Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. -Note that `nginxinc/kubernetes-ingress` does not include the Lua module. +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml -nginx.ingress.kubernetes.io/auth-response-headers: Authorization -nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri -nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth -nginx.ingress.kubernetes.io/configuration-snippet: | - auth_request_set $name_upstream_1 $upstream_cookie_name_1; - - access_by_lua_block { - if ngx.var.name_upstream_1 ~= "" then - ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") - end - } +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" ``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". diff --git a/docs/versioned_docs/version-7.12.x/configuration/integration.md b/docs/versioned_docs/version-7.12.x/configuration/integration.md index 05d39281..c57cfa6b 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.12.x/configuration/integration.md @@ -77,23 +77,15 @@ server { } ``` -When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. -Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. -Note that `nginxinc/kubernetes-ingress` does not include the Lua module. +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml -nginx.ingress.kubernetes.io/auth-response-headers: Authorization -nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri -nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth -nginx.ingress.kubernetes.io/configuration-snippet: | - auth_request_set $name_upstream_1 $upstream_cookie_name_1; - - access_by_lua_block { - if ngx.var.name_upstream_1 ~= "" then - ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") - end - } +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" ``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". From f950dc99426014f3973b2c9193ee5eecf515e39b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olivier=20Mengu=C3=A9?= Date: Tue, 28 Oct 2025 09:13:35 +0100 Subject: [PATCH 097/130] feat(makefile): simplify validate-go-version (#3147) Since Go 1.21 the go toolchain validates strictly the "go" version directive in go.mod, and downloads and uses the requested toolchain if necessary. See https://go.dev/doc/toolchain So we can just run "go list" to tell the Go toolchain to validate our build environment according to go.mod. To extract the "go" directive version from go.mod (used to select the Docker build image) we also use "go list". --- Makefile | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/Makefile b/Makefile index 20ed88c9..06471100 100644 --- a/Makefile +++ b/Makefile @@ -36,13 +36,12 @@ REPOSITORY ?= oauth2-proxy DATE := $(shell date +"%Y%m%d") .NOTPARALLEL: -GO_MAJOR_VERSION = $(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f1) -GO_MINOR_VERSION = $(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2) +# The go version in go.mod used for the Docker build toolchain, without the patch +GO_MOD_VERSION_MINOR := $(shell $(GO) list -f '{{printf "%.4s" .Module.GoVersion}}' ) -GO_MOD_VERSION = $(shell sed -En 's/^go ([[:digit:]]\.[[:digit:]]+)\.[[:digit:]]+/\1/p' go.mod) -MINIMUM_SUPPORTED_GO_MAJOR_VERSION = $(shell echo ${GO_MOD_VERSION} | cut -d' ' -f1 | cut -d'.' -f1) -MINIMUM_SUPPORTED_GO_MINOR_VERSION = $(shell echo ${GO_MOD_VERSION} | cut -d' ' -f1 | cut -d'.' -f2) -GO_VERSION_VALIDATION_ERR_MSG = Golang version is not supported, please update to at least $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION).$(MINIMUM_SUPPORTED_GO_MINOR_VERSION) +# From go1.21 go will transparently download the toolchain declared in go.mod. https://go.dev/doc/toolchain +# We don't need to keep this message updated: the important info is in go.mod. +GO_VERSION_VALIDATION_ERR_MSG = Golang version is not supported, please update to at least go1.21 ifeq ($(COVER),true) TESTCOVER ?= -coverprofile c.out @@ -56,7 +55,7 @@ build: validate-go-version clean $(BINARY) ## Build and create oauth2-proxy bina $(BINARY): CGO_ENABLED=0 $(GO) build -a -installsuffix cgo -ldflags="-X github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version.VERSION=${VERSION}" -o $@ github.com/oauth2-proxy/oauth2-proxy/v7 -DOCKER_BUILDX_COMMON_ARGS ?= --build-arg BUILD_IMAGE=docker.io/library/golang:${GO_MOD_VERSION}-bookworm --build-arg VERSION=${VERSION} +DOCKER_BUILDX_COMMON_ARGS ?= --build-arg BUILD_IMAGE=docker.io/library/golang:$(GO_MOD_VERSION_MINOR)-bookworm --build-arg VERSION=$(VERSION) DOCKER_BUILD_PLATFORM ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v7,linux/s390x DOCKER_BUILD_RUNTIME_IMAGE ?= gcr.io/distroless/static:nonroot @@ -158,15 +157,7 @@ lint: validate-go-version ## Lint all files using golangci-lint .PHONY: validate-go-version validate-go-version: ## Validate Go environment requirements - @if [ $(GO_MAJOR_VERSION) -gt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \ - exit 0 ;\ - elif [ $(GO_MAJOR_VERSION) -lt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \ - echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\ - exit 1; \ - elif [ $(GO_MINOR_VERSION) -lt $(MINIMUM_SUPPORTED_GO_MINOR_VERSION) ] ; then \ - echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\ - exit 1; \ - fi + @$(GO) list . >/dev/null || { echo '$(GO_VERSION_VALIDATION_ERR_MSG)'; exit 1; } # local-env can be used to interact with the local development environment # eg: From 8f687e4d0cb416232397b1076f387a23c9622183 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 28 Oct 2025 09:54:10 +0100 Subject: [PATCH 098/130] chore(deps): upgrade to latest go1.25.3 (#3244) Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + go.mod | 2 +- go.sum | 34 ++-------------------------------- 3 files changed, 4 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5aefaafa..c52eedef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.12.0 - [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) +- [#3244](https://github.com/oauth2-proxy/oauth2-proxy/pull/3244) chore(deps): upgrade to latest go1.25.3 (@tuunit) # V7.12.0 diff --git a/go.mod b/go.mod index 24f316e4..3aeeda0a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.24.6 +go 1.25.3 require ( cloud.google.com/go/compute/metadata v0.7.0 diff --git a/go.sum b/go.sum index caa8e2a0..2e8db1ef 100644 --- a/go.sum +++ b/go.sum @@ -61,12 +61,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk= -github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= -github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= -github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-jwt/jwt/v5 v5.2.3 h1:kkGXqQOBSDDWRhWNXTFpqGSCMyh/PLnqUvMGJPDJDs0= github.com/golang-jwt/jwt/v5 v5.2.3/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= @@ -85,8 +81,6 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= -github.com/googleapis/gax-go/v2 v2.14.2 h1:eBLnkZ9635krYIPD+ag1USrOAI0Nr0QYF3+/3GqO0k0= -github.com/googleapis/gax-go/v2 v2.14.2/go.mod h1:ON64QhlJkhVtSqp4v1uaK92VyZ2gmvDQsweuyLV+8+w= github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= @@ -142,8 +136,6 @@ github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA= github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo= github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= -github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= -github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M= github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= @@ -186,8 +178,6 @@ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN8 golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= -golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -197,8 +187,6 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= -golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= @@ -206,8 +194,6 @@ golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKl golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8= -golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -219,8 +205,6 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= -golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -234,8 +218,6 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= -golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= @@ -244,25 +226,15 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo= -golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg= golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.240.0 h1:PxG3AA2UIqT1ofIzWV2COM3j3JagKTKSwy7L6RHNXNU= -google.golang.org/api v0.240.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= -google.golang.org/api v0.241.0 h1:QKwqWQlkc6O895LchPEDUSYr22Xp3NCxpQRiWTB6avE= -google.golang.org/api v0.241.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= google.golang.org/api v0.242.0 h1:7Lnb1nfnpvbkCiZek6IXKdJ0MFuAZNAJKQfA1ws62xg= google.golang.org/api v0.242.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= -google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 h1:1tXaIXCracvtsRxSBsYDiSBN0cuJvM7QYW+MrpIRY78= -google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:49MsLSx0oWMOZqcpB3uL8ZOkAh1+TndpJ8ONoCBWiZk= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= -google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2 h1:vPV0tzlsK6EzEDHNNH5sa7Hs9bd7iXR7B1tSiPepkV0= -google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:pKLAc5OolXC3ViWGI62vvC0n10CpwAtRcTNCFwTKBEw= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 h1:fc6jSaCT0vBduLYZHYrBBNY4dsWuvgyff9noRNDdBeE= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822/go.mod h1:h3c4v36UTKzUiuaOKQ6gr3S+0hovBtUrXzTG/i3+XEc= google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 h1:pFyd6EwwL2TqFf8emdthzeX+gZE1ElRq3iM8pui4KBY= google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= google.golang.org/grpc v1.73.0 h1:VIWSmpI2MegBtTuFt5/JWy2oXxtjJ/e89Z70ImfD2ok= @@ -280,7 +252,5 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/apimachinery v0.33.2 h1:IHFVhqg59mb8PJWTLi8m1mAoepkUNYmptHsV+Z1m5jY= -k8s.io/apimachinery v0.33.2/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= k8s.io/apimachinery v0.33.3 h1:4ZSrmNa0c/ZpZJhAgRdcsFcZOw1PQU1bALVQ0B3I5LA= k8s.io/apimachinery v0.33.3/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= From 110d51d1d742b5cde9cb629d6912f47e5d9ab878 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Tue, 28 Oct 2025 20:05:02 +1100 Subject: [PATCH 099/130] test: replace mock pkg/clock with narrowly targeted stub clocks. (#3238) The package under pkg/clock is github.com/benbjohnson/clock, which is archived. It's also way more complex than is what is actually needed here, so we can entirely remove the dependency and remove the helper package. Fixes #2840. Signed-off-by: David Symonds --- CHANGELOG.md | 1 + go.mod | 1 - go.sum | 2 - pkg/apis/sessions/session_state.go | 18 +- pkg/apis/sessions/session_state_test.go | 6 +- pkg/clock/clock.go | 157 ---------- pkg/clock/clock_suite_test.go | 17 -- pkg/clock/clock_test.go | 380 ------------------------ pkg/cookies/csrf.go | 16 +- pkg/cookies/csrf_per_request_test.go | 10 +- pkg/cookies/csrf_test.go | 6 +- pkg/middleware/stored_session_test.go | 25 +- providers/provider_default_test.go | 5 +- 13 files changed, 50 insertions(+), 594 deletions(-) delete mode 100644 pkg/clock/clock.go delete mode 100644 pkg/clock/clock_suite_test.go delete mode 100644 pkg/clock/clock_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index c52eedef..e014aee3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) - [#3244](https://github.com/oauth2-proxy/oauth2-proxy/pull/3244) chore(deps): upgrade to latest go1.25.3 (@tuunit) +- [#3238](https://github.com/oauth2-proxy/oauth2-proxy/pull/3238) chore: Replace pkg/clock with narrowly targeted stub clocks (@dsymonds) # V7.12.0 diff --git a/go.mod b/go.mod index 3aeeda0a..0e14464c 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,6 @@ require ( github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb github.com/a8m/envsubst v1.4.3 github.com/alicebob/miniredis/v2 v2.35.0 - github.com/benbjohnson/clock v1.3.5 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 github.com/coreos/go-oidc/v3 v3.14.1 diff --git a/go.sum b/go.sum index 2e8db1ef..8bc31660 100644 --- a/go.sum +++ b/go.sum @@ -14,8 +14,6 @@ github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGn github.com/alicebob/miniredis/v2 v2.11.1/go.mod h1:UA48pmi7aSazcGAvcdKcBB49z521IC9VjTTRz2nIaJE= github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI= github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= -github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= -github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow= diff --git a/pkg/apis/sessions/session_state.go b/pkg/apis/sessions/session_state.go index b5e4fc83..5b063c3f 100644 --- a/pkg/apis/sessions/session_state.go +++ b/pkg/apis/sessions/session_state.go @@ -7,7 +7,6 @@ import ( "io" "time" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/clock" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption" "github.com/pierrec/lz4/v4" "github.com/vmihailenco/msgpack/v5" @@ -30,8 +29,15 @@ type SessionState struct { PreferredUsername string `msgpack:"pu,omitempty"` // Internal helpers, not serialized - Clock clock.Clock `msgpack:"-"` - Lock Lock `msgpack:"-"` + Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing + Lock Lock `msgpack:"-"` +} + +func (s *SessionState) now() time.Time { + if s.Clock != nil { + return s.Clock() + } + return time.Now() } func (s *SessionState) ObtainLock(ctx context.Context, expiration time.Duration) error { @@ -64,7 +70,7 @@ func (s *SessionState) PeekLock(ctx context.Context) (bool, error) { // CreatedAtNow sets a SessionState's CreatedAt to now func (s *SessionState) CreatedAtNow() { - now := s.Clock.Now() + now := s.now() s.CreatedAt = &now } @@ -85,7 +91,7 @@ func (s *SessionState) ExpiresIn(d time.Duration) { // IsExpired checks whether the session has expired func (s *SessionState) IsExpired() bool { - if s.ExpiresOn != nil && !s.ExpiresOn.IsZero() && s.ExpiresOn.Before(s.Clock.Now()) { + if s.ExpiresOn != nil && !s.ExpiresOn.IsZero() && s.ExpiresOn.Before(s.now()) { return true } return false @@ -94,7 +100,7 @@ func (s *SessionState) IsExpired() bool { // Age returns the age of a session func (s *SessionState) Age() time.Duration { if s.CreatedAt != nil && !s.CreatedAt.IsZero() { - return s.Clock.Now().Truncate(time.Second).Sub(*s.CreatedAt) + return s.now().Truncate(time.Second).Sub(*s.CreatedAt) } return 0 } diff --git a/pkg/apis/sessions/session_state_test.go b/pkg/apis/sessions/session_state_test.go index e12c2776..442fcea8 100644 --- a/pkg/apis/sessions/session_state_test.go +++ b/pkg/apis/sessions/session_state_test.go @@ -22,7 +22,7 @@ func TestCreatedAtNow(t *testing.T) { ss := &SessionState{} now := time.Unix(1234567890, 0) - ss.Clock.Set(now) + ss.Clock = func() time.Time { return now } ss.CreatedAtNow() g.Expect(*ss.CreatedAt).To(Equal(now)) @@ -33,9 +33,9 @@ func TestExpiresIn(t *testing.T) { ss := &SessionState{} now := time.Unix(1234567890, 0) - ss.Clock.Set(now) + ss.Clock = func() time.Time { return now } - ttl := time.Duration(743) * time.Second + ttl := 743 * time.Second ss.ExpiresIn(ttl) g.Expect(*ss.ExpiresOn).To(Equal(ss.CreatedAt.Add(ttl))) diff --git a/pkg/clock/clock.go b/pkg/clock/clock.go deleted file mode 100644 index 887bf0aa..00000000 --- a/pkg/clock/clock.go +++ /dev/null @@ -1,157 +0,0 @@ -package clock - -import ( - "errors" - "sync" - "time" - - clockapi "github.com/benbjohnson/clock" -) - -var ( - globalClock = clockapi.New() - mu sync.Mutex -) - -// Set the global clock to a clockapi.Mock with the given time.Time -func Set(t time.Time) { - mu.Lock() - defer mu.Unlock() - mock, ok := globalClock.(*clockapi.Mock) - if !ok { - mock = clockapi.NewMock() - } - mock.Set(t) - globalClock = mock -} - -// Add moves the mocked global clock forward the given duration. It will error -// if the global clock is not mocked. -func Add(d time.Duration) error { - mu.Lock() - defer mu.Unlock() - mock, ok := globalClock.(*clockapi.Mock) - if !ok { - return errors.New("time not mocked") - } - mock.Add(d) - return nil -} - -// Reset sets the global clock to a pure time implementation. Returns any -// existing Mock if set in case lingering time operations are attached to it. -func Reset() *clockapi.Mock { - mu.Lock() - defer mu.Unlock() - existing := globalClock - globalClock = clockapi.New() - - mock, ok := existing.(*clockapi.Mock) - if !ok { - return nil - } - return mock -} - -// Clock is a non-package level wrapper around time that supports stubbing. -// It will use its localized stubs (allowing for parallelized unit tests -// where package level stubbing would cause issues). It falls back to any -// package level time stubs for non-parallel, cross-package integration -// testing scenarios. -// -// If nothing is stubbed, it defaults to default time behavior in the time -// package. -type Clock struct { - mock *clockapi.Mock -} - -// Set sets the Clock to a clock.Mock at the given time.Time -func (c *Clock) Set(t time.Time) { - if c.mock == nil { - c.mock = clockapi.NewMock() - } - c.mock.Set(t) -} - -// Add moves clock forward time.Duration if it is mocked. It will error -// if the clock is not mocked. -func (c *Clock) Add(d time.Duration) error { - if c.mock == nil { - return errors.New("clock not mocked") - } - c.mock.Add(d) - return nil -} - -// Reset removes local clock.Mock. Returns any existing Mock if set in case -// lingering time operations are attached to it. -func (c *Clock) Reset() *clockapi.Mock { - existing := c.mock - c.mock = nil - return existing -} - -func (c *Clock) After(d time.Duration) <-chan time.Time { - m := c.mock - if m == nil { - return globalClock.After(d) - } - return m.After(d) -} - -func (c *Clock) AfterFunc(d time.Duration, f func()) *clockapi.Timer { - m := c.mock - if m == nil { - return globalClock.AfterFunc(d, f) - } - return m.AfterFunc(d, f) -} - -func (c *Clock) Now() time.Time { - m := c.mock - if m == nil { - return globalClock.Now() - } - return m.Now() -} - -func (c *Clock) Since(t time.Time) time.Duration { - m := c.mock - if m == nil { - return globalClock.Since(t) - } - return m.Since(t) -} - -func (c *Clock) Sleep(d time.Duration) { - m := c.mock - if m == nil { - globalClock.Sleep(d) - return - } - m.Sleep(d) -} - -func (c *Clock) Tick(d time.Duration) <-chan time.Time { - m := c.mock - if m == nil { - return globalClock.Tick(d) - } - return m.Tick(d) -} - -func (c *Clock) Ticker(d time.Duration) *clockapi.Ticker { - m := c.mock - if m == nil { - return globalClock.Ticker(d) - } - return m.Ticker(d) -} - -func (c *Clock) Timer(d time.Duration) *clockapi.Timer { - m := c.mock - if m == nil { - return globalClock.Timer(d) - } - return m.Timer(d) -} diff --git a/pkg/clock/clock_suite_test.go b/pkg/clock/clock_suite_test.go deleted file mode 100644 index 99d39f24..00000000 --- a/pkg/clock/clock_suite_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package clock_test - -import ( - "testing" - - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -func TestClockSuite(t *testing.T) { - logger.SetOutput(GinkgoWriter) - logger.SetErrOutput(GinkgoWriter) - - RegisterFailHandler(Fail) - RunSpecs(t, "Clock") -} diff --git a/pkg/clock/clock_test.go b/pkg/clock/clock_test.go deleted file mode 100644 index e1b6d440..00000000 --- a/pkg/clock/clock_test.go +++ /dev/null @@ -1,380 +0,0 @@ -package clock_test - -import ( - "sync" - "sync/atomic" - "time" - - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/clock" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -const ( - testGlobalEpoch = 1000000000 - testLocalEpoch = 1234567890 -) - -var _ = Describe("Clock suite", func() { - var testClock = clock.Clock{} - - AfterEach(func() { - clock.Reset() - testClock.Reset() - }) - - Context("Global time not overridden", func() { - It("errors when trying to Add", func() { - err := clock.Add(123 * time.Hour) - Expect(err).To(HaveOccurred()) - }) - - Context("Clock not mocked via Set", func() { - const ( - outsideTolerance = int32(0) - withinTolerance = int32(1) - ) - - It("uses time.After for After", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(30 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - - <-testClock.After(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - - <-testClock.After(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("uses time.AfterFunc for AfterFunc", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(30 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - - var wg sync.WaitGroup - wg.Add(1) - testClock.AfterFunc(20*time.Millisecond, func() { - wg.Done() - }) - wg.Wait() - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - - wg.Add(1) - testClock.AfterFunc(20*time.Millisecond, func() { - wg.Done() - }) - wg.Wait() - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("uses time.Now for Now", func() { - a := time.Now() - b := testClock.Now() - Expect(b.Sub(a).Round(10 * time.Millisecond)).To(Equal(0 * time.Millisecond)) - }) - - It("uses time.Since for Since", func() { - past := time.Now().Add(-60 * time.Second) - Expect(time.Since(past).Round(10 * time.Millisecond)). - To(Equal(60 * time.Second)) - }) - - It("uses time.Sleep for Sleep", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(30 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - - testClock.Sleep(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - - testClock.Sleep(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("uses time.Tick for Tick", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(50 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - ch := testClock.Tick(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - <-ch - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - <-ch - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - <-ch - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("uses time.Ticker for Ticker", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(50 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - ticker := testClock.Ticker(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - <-ticker.C - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - <-ticker.C - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - <-ticker.C - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("errors if Add is used", func() { - err := testClock.Add(100 * time.Second) - Expect(err).To(HaveOccurred()) - }) - }) - - Context("Clock mocked via Set", func() { - var now = time.Unix(testLocalEpoch, 0) - - BeforeEach(func() { - testClock.Set(now) - }) - - It("mocks After", func() { - var after int32 - ready := make(chan struct{}) - ch := testClock.After(10 * time.Second) - go func(ch <-chan time.Time) { - close(ready) - <-ch - atomic.StoreInt32(&after, 1) - }(ch) - <-ready - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(1))) - }) - - It("mocks AfterFunc", func() { - var after int32 - testClock.AfterFunc(10*time.Second, func() { - atomic.StoreInt32(&after, 1) - }) - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(1))) - }) - - It("mocks AfterFunc with a stopped timer", func() { - var after int32 - timer := testClock.AfterFunc(10*time.Second, func() { - atomic.StoreInt32(&after, 1) - }) - timer.Stop() - - err := testClock.Add(11 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - }) - - It("mocks Now", func() { - Expect(testClock.Now()).To(Equal(now)) - err := testClock.Add(123 * time.Hour) - Expect(err).ToNot(HaveOccurred()) - Expect(testClock.Now()).To(Equal(now.Add(123 * time.Hour))) - }) - - It("mocks Since", func() { - Expect(testClock.Since(time.Unix(testLocalEpoch-100, 0))). - To(Equal(100 * time.Second)) - }) - - It("mocks Sleep", func() { - var after int32 - ready := make(chan struct{}) - go func() { - close(ready) - testClock.Sleep(10 * time.Second) - atomic.StoreInt32(&after, 1) - }() - <-ready - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(1))) - }) - - It("mocks Tick", func() { - var ticks int32 - ready := make(chan struct{}) - go func() { - close(ready) - tick := testClock.Tick(10 * time.Second) - for ticks < 5 { - <-tick - atomic.AddInt32(&ticks, 1) - } - }() - <-ready - - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(0))) - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(1))) - - err = testClock.Add(30 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(4))) - - err = testClock.Add(10 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(5))) - }) - - It("mocks Ticker", func() { - var ticks int32 - ready := make(chan struct{}) - go func() { - ticker := testClock.Ticker(10 * time.Second) - close(ready) - for ticks < 5 { - <-ticker.C - atomic.AddInt32(&ticks, 1) - } - }() - <-ready - - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(0))) - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(1))) - - err = testClock.Add(30 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(4))) - - err = testClock.Add(10 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(5))) - }) - - It("mocks Timer", func() { - var after int32 - ready := make(chan struct{}) - go func() { - timer := testClock.Timer(10 * time.Second) - close(ready) - <-timer.C - atomic.AddInt32(&after, 1) - }() - <-ready - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(1))) - }) - }) - }) - - Context("Global time overridden", func() { - var ( - globalNow = time.Unix(testGlobalEpoch, 0) - localNow = time.Unix(testLocalEpoch, 0) - ) - - BeforeEach(func() { - clock.Set(globalNow) - }) - - Context("Clock not mocked via Set", func() { - It("uses globally mocked Now", func() { - Expect(testClock.Now()).To(Equal(globalNow)) - err := clock.Add(123 * time.Hour) - Expect(err).ToNot(HaveOccurred()) - Expect(testClock.Now()).To(Equal(globalNow.Add(123 * time.Hour))) - }) - - It("errors when Add is called on the local Clock", func() { - err := testClock.Add(100 * time.Hour) - Expect(err).To(HaveOccurred()) - }) - }) - - Context("Clock is mocked via Set", func() { - BeforeEach(func() { - testClock.Set(localNow) - }) - - It("uses the local mock and ignores the global", func() { - Expect(testClock.Now()).To(Equal(localNow)) - - err := clock.Add(456 * time.Hour) - Expect(err).ToNot(HaveOccurred()) - - err = testClock.Add(123 * time.Hour) - Expect(err).ToNot(HaveOccurred()) - - Expect(testClock.Now()).To(Equal(localNow.Add(123 * time.Hour))) - }) - }) - }) -}) diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go index 3b8efaf3..939578a2 100644 --- a/pkg/cookies/csrf.go +++ b/pkg/cookies/csrf.go @@ -10,7 +10,6 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/clock" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption" "github.com/vmihailenco/msgpack/v5" ) @@ -47,7 +46,7 @@ type csrf struct { CodeVerifier string `msgpack:"cv,omitempty"` cookieOpts *options.Cookie - time clock.Clock + clock func() time.Time } // csrtStateTrim will indicate the length of the state trimmed for the name of the csrf cookie @@ -70,6 +69,7 @@ func NewCSRF(opts *options.Cookie, codeVerifier string) (CSRF, error) { CodeVerifier: codeVerifier, cookieOpts: opts, + clock: time.Now, }, nil } @@ -187,7 +187,7 @@ func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *ht // delete the X oldest cookies slices.SortStableFunc(decodedCookies, func(a, b *csrf) int { - return a.time.Now().Compare(b.time.Now()) + return a.clock().Compare(b.clock()) }) for i := 0; i < len(decodedCookies)-opts.CSRFPerRequestLimit; i++ { @@ -223,7 +223,7 @@ func (c *csrf) encodeCookie() (string, error) { if err != nil { return "", fmt.Errorf("error getting cookie secret: %v", err) } - return encryption.SignedValue(secret, c.cookieName(), encrypted, c.time.Now()) + return encryption.SignedValue(secret, c.cookieName(), encrypted, c.clock()) } // decodeCSRFCookie validates the signature then decrypts and decodes a CSRF @@ -249,10 +249,10 @@ func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) // unmarshalCSRF unmarshals decrypted data into a CSRF struct func unmarshalCSRF(decrypted []byte, opts *options.Cookie, csrfTime time.Time) (*csrf, error) { - clock := clock.Clock{} - clock.Set(csrfTime) - - csrf := &csrf{cookieOpts: opts, time: clock} + csrf := &csrf{ + cookieOpts: opts, + clock: func() time.Time { return csrfTime }, + } if err := msgpack.Unmarshal(decrypted, csrf); err != nil { return nil, fmt.Errorf("error unmarshalling data to CSRF: %v", err) } diff --git a/pkg/cookies/csrf_per_request_test.go b/pkg/cookies/csrf_per_request_test.go index 9b7d4e59..6a17013b 100644 --- a/pkg/cookies/csrf_per_request_test.go +++ b/pkg/cookies/csrf_per_request_test.go @@ -128,7 +128,7 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { testNow := time.Unix(nowEpoch, 0) BeforeEach(func() { - privateCSRF.time.Set(testNow) + privateCSRF.clock = func() time.Time { return testNow } req = &http.Request{ Method: http.MethodGet, @@ -144,7 +144,7 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { }) AfterEach(func() { - privateCSRF.time.Reset() + privateCSRF.clock = time.Now }) Context("SetCookie", func() { @@ -200,17 +200,17 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { publicCSRF1, err := NewCSRF(cookieOpts, "verifier") Expect(err).ToNot(HaveOccurred()) privateCSRF1 := publicCSRF1.(*csrf) - privateCSRF1.time.Set(testNow) + privateCSRF1.clock = func() time.Time { return testNow } publicCSRF2, err := NewCSRF(cookieOpts, "verifier") Expect(err).ToNot(HaveOccurred()) privateCSRF2 := publicCSRF2.(*csrf) - privateCSRF2.time.Set(testNow.Add(time.Minute)) + privateCSRF2.clock = func() time.Time { return testNow.Add(time.Minute) } publicCSRF3, err := NewCSRF(cookieOpts, "verifier") Expect(err).ToNot(HaveOccurred()) privateCSRF3 := publicCSRF3.(*csrf) - privateCSRF3.time.Set(testNow.Add(time.Minute * 2)) + privateCSRF3.clock = func() time.Time { return testNow.Add(time.Minute * 2) } cookies := []string{} for _, csrf := range []*csrf{privateCSRF1, privateCSRF2, privateCSRF3} { diff --git a/pkg/cookies/csrf_test.go b/pkg/cookies/csrf_test.go index 37527bd0..085b91df 100644 --- a/pkg/cookies/csrf_test.go +++ b/pkg/cookies/csrf_test.go @@ -130,7 +130,7 @@ var _ = Describe("CSRF Cookie Tests", func() { testNow := time.Unix(nowEpoch, 0) BeforeEach(func() { - privateCSRF.time.Set(testNow) + privateCSRF.clock = func() time.Time { return testNow } req = &http.Request{ Method: http.MethodGet, @@ -146,7 +146,7 @@ var _ = Describe("CSRF Cookie Tests", func() { }) AfterEach(func() { - privateCSRF.time.Reset() + privateCSRF.clock = time.Now }) Context("SetCookie", func() { @@ -173,7 +173,7 @@ var _ = Describe("CSRF Cookie Tests", func() { Context("LoadCSRFCookie", func() { BeforeEach(func() { // we need to reset the time to ensure the cookie is valid - privateCSRF.time.Reset() + privateCSRF.clock = time.Now }) It("should return error when no cookie is set", func() { diff --git a/pkg/middleware/stored_session_test.go b/pkg/middleware/stored_session_test.go index 904c2028..d8e78f2f 100644 --- a/pkg/middleware/stored_session_test.go +++ b/pkg/middleware/stored_session_test.go @@ -11,7 +11,6 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/clock" "github.com/oauth2-proxy/oauth2-proxy/v7/providers" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -95,6 +94,7 @@ var _ = Describe("Stored Session Suite", func() { now := time.Now() createdPast := now.Add(-5 * time.Minute) createdFuture := now.Add(5 * time.Minute) + clock := func() time.Time { return now } var defaultRefreshFunc = func(_ context.Context, ss *sessionsapi.SessionState) (bool, error) { switch ss.RefreshToken { @@ -120,6 +120,7 @@ var _ = Describe("Stored Session Suite", func() { RefreshToken: noRefresh, CreatedAt: &createdPast, ExpiresOn: &createdFuture, + Clock: clock, }, nil case "_oauth2_proxy=InvalidNoRefreshSession": return &sessionsapi.SessionState{ @@ -127,24 +128,28 @@ var _ = Describe("Stored Session Suite", func() { RefreshToken: noRefresh, CreatedAt: &createdPast, ExpiresOn: &createdFuture, + Clock: clock, }, nil case "_oauth2_proxy=ExpiredNoRefreshSession": return &sessionsapi.SessionState{ RefreshToken: noRefresh, CreatedAt: &createdPast, ExpiresOn: &createdPast, + Clock: clock, }, nil case "_oauth2_proxy=RefreshSession": return &sessionsapi.SessionState{ RefreshToken: refresh, CreatedAt: &createdPast, ExpiresOn: &createdFuture, + Clock: clock, }, nil case "_oauth2_proxy=RefreshError": return &sessionsapi.SessionState{ RefreshToken: "RefreshError", CreatedAt: &createdPast, ExpiresOn: &createdFuture, + Clock: clock, }, nil case "_oauth2_proxy=NonExistent": return nil, fmt.Errorf("invalid cookie") @@ -154,14 +159,6 @@ var _ = Describe("Stored Session Suite", func() { }, } - BeforeEach(func() { - clock.Set(now) - }) - - AfterEach(func() { - clock.Reset() - }) - type storedSessionLoaderTableInput struct { requestHeaders http.Header existingSession *sessionsapi.SessionState @@ -200,7 +197,15 @@ var _ = Describe("Stored Session Suite", func() { })) handler.ServeHTTP(rw, req) - Expect(gotSession).To(Equal(in.expectedSession)) + // Compare, ignoring testing Clock. + if in.expectedSession == nil { + Expect(gotSession).To(BeNil()) + return + } + Expect(gotSession).ToNot(BeNil()) + got := *gotSession + got.Clock = nil + Expect(&got).To(Equal(in.expectedSession)) }, Entry("with no cookie", storedSessionLoaderTableInput{ requestHeaders: http.Header{}, diff --git a/providers/provider_default_test.go b/providers/provider_default_test.go index f678d13d..0fbe7abd 100644 --- a/providers/provider_default_test.go +++ b/providers/provider_default_test.go @@ -17,8 +17,9 @@ func TestRefresh(t *testing.T) { now := time.Unix(1234567890, 10) expires := time.Unix(1234567890, 0) - ss := &sessions.SessionState{} - ss.Clock.Set(now) + ss := &sessions.SessionState{ + Clock: func() time.Time { return now }, + } ss.SetExpiresOn(expires) refreshed, err := p.RefreshSession(context.Background(), ss) From 87827435ce895a8d7c6dfa03a879dd3399d36cce Mon Sep 17 00:00:00 2001 From: Drew Foehn Date: Fri, 7 Nov 2025 13:44:32 -0500 Subject: [PATCH 100/130] feat: added organizationId/employee id as preferred username (#3237) Signed-off-by: Drew Foehn Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/alpha_config.md | 2 + docs/docs/configuration/providers/google.md | 23 ++++-- pkg/apis/options/legacy_options.go | 6 ++ pkg/apis/options/providers.go | 4 + providers/google.go | 83 +++++++++++++++++++-- providers/google_test.go | 80 ++++++++++++++++++++ 7 files changed, 185 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e014aee3..dbb0974c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) - [#3244](https://github.com/oauth2-proxy/oauth2-proxy/pull/3244) chore(deps): upgrade to latest go1.25.3 (@tuunit) - [#3238](https://github.com/oauth2-proxy/oauth2-proxy/pull/3238) chore: Replace pkg/clock with narrowly targeted stub clocks (@dsymonds) +- [#3237](https://github.com/oauth2-proxy/oauth2-proxy/pull/3237) - feat: add option to use organization id for preferred username in Google Provider (@pixeldrew) # V7.12.0 diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 28645ceb..54ccb01e 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -252,6 +252,8 @@ Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". | `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | | `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | | `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | ### Header diff --git a/docs/docs/configuration/providers/google.md b/docs/docs/configuration/providers/google.md index ac2a7dfa..0de5bb74 100644 --- a/docs/docs/configuration/providers/google.md +++ b/docs/docs/configuration/providers/google.md @@ -5,13 +5,15 @@ title: Google (default) ## Config Options -| Flag | Toml Field | Type | Description | Default | -| ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | -| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | -| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | -| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | -| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | -| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | +| Flag | Toml Field | Type | Description | Default | +|-------------------------------------------------|----------------------------------------------| ------ |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------| +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | +| `--google-use-organization-id` | `google_use_organization_id` | bool | use organization id as preferred username | false | +| `--google-admin-api-user-scope` | `google_admin_api_user_scope` | string | the OAuth scope to use when querying the Google Admin SDK for organization id, can be 'readonly', 'user' or 'cloud'
| `readonly` | ## Usage @@ -73,3 +75,10 @@ can be leveraged through a feature called Workload Identity. Follow Google's [gu to set up Workload Identity. When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. + +##### Using Organization ID as Preferred Username (optional) +By default, the google provider uses the google id as username. If you would like to use an organization id instead, you can set the `google-use-organization-id` flag to true. +This requires that the service account used to query the Google Admin SDK has one of the following scopes granted in step 5 above: +- `https://www.googleapis.com/auth/admin.directory.user.readonly`, +- `https://www.googleapis.com/auth/admin.directory.user` +- `https://www.googleapis.com/auth/cloud-platform` diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 12975225..e22278fa 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -510,6 +510,8 @@ type LegacyProvider struct { GoogleServiceAccountJSON string `flag:"google-service-account-json" cfg:"google_service_account_json"` GoogleUseApplicationDefaultCredentials bool `flag:"google-use-application-default-credentials" cfg:"google_use_application_default_credentials"` GoogleTargetPrincipal string `flag:"google-target-principal" cfg:"google_target_principal"` + GoogleUseOrganizationID bool `flag:"google-use-organization-id" cfg:"google_use_organization_id"` + GoogleAdminAPIUserScope string `flag:"google-admin-api-user-scope" cfg:"google_admin_api_user_scope"` // These options allow for other providers besides Google, with // potential overrides. @@ -623,6 +625,8 @@ func legacyGoogleFlagSet() *pflag.FlagSet { flagSet.String("google-service-account-json", "", "the path to the service account json credentials") flagSet.String("google-use-application-default-credentials", "", "use application default credentials instead of service account json (i.e. GKE Workload Identity)") flagSet.String("google-target-principal", "", "the target principal to impersonate when using ADC") + flagSet.String("google-use-organization-id", "", "use organization id as preferred username") + flagSet.String("google-admin-api-user-scope", "", "authorization scope required to call users.get, can be one of ") return flagSet } @@ -770,6 +774,8 @@ func (l *LegacyProvider) convert() (Providers, error) { ServiceAccountJSON: l.GoogleServiceAccountJSON, UseApplicationDefaultCredentials: l.GoogleUseApplicationDefaultCredentials, TargetPrincipal: l.GoogleTargetPrincipal, + UseOrganizationID: l.GoogleUseOrganizationID, + AdminAPIUserScope: l.GoogleAdminAPIUserScope, } case "entra-id": provider.MicrosoftEntraIDConfig = MicrosoftEntraIDOptions{ diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 0f254575..3a5094da 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -230,6 +230,10 @@ type GoogleOptions struct { UseApplicationDefaultCredentials bool `json:"useApplicationDefaultCredentials,omitempty"` // TargetPrincipal is the Google Service Account used for Application Default Credentials TargetPrincipal string `json:"targetPrincipal,omitempty"` + // UseOrganizationId indicates whether to use the organization ID as the UserName claim + UseOrganizationID bool `json:"useOrganizationID,omitempty"` + // admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly + AdminAPIUserScope string `json:"adminAPIUserScope,omitempty"` } type OIDCOptions struct { diff --git a/providers/google.go b/providers/google.go index 097e3567..a6a9d283 100644 --- a/providers/google.go +++ b/providers/google.go @@ -40,6 +40,8 @@ type GoogleProvider struct { // Refresh. `Authorize` uses the results of this saved in `session.Groups` // Since it is called on every request. groupValidator func(*sessions.SessionState) bool + + setPreferredUsername func(s *sessions.SessionState) error } var _ Provider = (*GoogleProvider)(nil) @@ -100,17 +102,59 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv groupValidator: func(*sessions.SessionState) bool { return true }, + + setPreferredUsername: func(_ *sessions.SessionState) error { + return nil + }, } - if opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { - provider.configureGroups(opts) - } + if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { + // reuse admin service to avoid multiple calls for token + var adminService *admin.Service + + if opts.UseOrganizationID { + // add user scopes to admin api + userScope := getAdminAPIUserScope(opts.AdminAPIUserScope) + for index, scope := range possibleScopesList { + possibleScopesList[index] = scope + " " + userScope + } + + adminService = getAdminService(opts) + + provider.setPreferredUsername = func(s *sessions.SessionState) error { + userName, err := getUserInfo(adminService, s.Email) + if err != nil { + return err + } + s.PreferredUsername = userName + return nil + } + } + + if opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { + if adminService == nil { + adminService = getAdminService(opts) + } + provider.configureGroups(opts, adminService) + } + + } return provider, nil } -func (p *GoogleProvider) configureGroups(opts options.GoogleOptions) { - adminService := getAdminService(opts) +// by default can be readonly user scope +func getAdminAPIUserScope(scope string) string { + switch scope { + case "cloud": + return admin.CloudPlatformScope + case "user": + return admin.AdminDirectoryUserScope + } + return admin.AdminDirectoryUserReadonlyScope +} + +func (p *GoogleProvider) configureGroups(opts options.GoogleOptions, adminService *admin.Service) { // Backwards compatibility with `--google-group` option if len(opts.Groups) > 0 { p.setAllowedGroups(opts.Groups) @@ -204,6 +248,7 @@ func (p *GoogleProvider) Redeem(ctx context.Context, redirectURL, code, codeVeri // EnrichSession checks the listed Google Groups configured and adds any // that the user is a member of to session.Groups. +// if preferred username is configured to be organization ID, it sets that as well. func (p *GoogleProvider) EnrichSession(_ context.Context, s *sessions.SessionState) error { // TODO (@NickMeves) - Move to pure EnrichSession logic and stop // reusing legacy `groupValidator`. @@ -212,7 +257,7 @@ func (p *GoogleProvider) EnrichSession(_ context.Context, s *sessions.SessionSta // populating logic. p.groupValidator(s) - return nil + return p.setPreferredUsername(s) } // SetGroupRestriction configures the GoogleProvider to restrict access to the @@ -262,7 +307,7 @@ func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope if opts.UseApplicationDefaultCredentials { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), - Scopes: []string{scope}, + Scopes: strings.Split(scope, " "), Subject: opts.AdminEmail, }) if err != nil { @@ -364,6 +409,30 @@ func getTargetPrincipal(ctx context.Context, opts options.GoogleOptions) (target return targetPrincipal } +func getUserInfo(service *admin.Service, email string) (string, error) { + req := service.Users.Get(email) + user, err := req.Do() + if err != nil { + return "", fmt.Errorf("failed to get user details for %s: %v", email, err) + } + + ext, _ := user.ExternalIds.([]interface{}) + for _, v := range ext { + m, _ := v.(map[string]interface{}) + if m == nil { + continue + } + if t, _ := m["type"].(string); t != "organization" { + continue + } + if val, _ := m["value"].(string); val != "" { + return val, nil + } + } + + return "", fmt.Errorf("failed to get organization id for %s", email) +} + // getUserGroups retrieves all groups that a user is a member of using the Google Admin Directory API func getUserGroups(service *admin.Service, email string) ([]string, error) { var allGroups []string diff --git a/providers/google_test.go b/providers/google_test.go index dc061203..f168e31c 100644 --- a/providers/google_test.go +++ b/providers/google_test.go @@ -325,3 +325,83 @@ func TestGoogleProvider_getUserGroups(t *testing.T) { assert.NoError(t, err) assert.Equal(t, []string{"group1@example.com", "group2@example.com"}, groups) } + +func TestGoogleProvider_getUserInfo(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/admin/directory/v1/users/test@example.com" { + response := `{ + "kind": "admin#directory#user", + "id": "", + "etag": "\"\"", + "primaryEmail": "test@example.com", + "name": { + "givenName": "Test", + "familyName": "User", + "fullName": "Test User" + }, + "isAdmin": false, + "isDelegatedAdmin": false, + "lastLoginTime": "", + "creationTime": "", + "agreedToTerms": true, + "suspended": false, + "archived": false, + "changePasswordAtNextLogin": false, + "ipWhitelisted": false, + "emails": [ + { + "address": "test@example.com", + "primary": true + } + ], + "externalIds": [ + { + "value": "test.user", + "type": "organization" + } + ], + "organizations": [ + ], + "phones": [ + ], + "languages": [ + { + "languageCode": "en", + "preference": "preferred" + } + ], + "aliases": [ + "test.user@example.com" + ], + "nonEditableAliases": [ + "test.user@example.com" + ], + "gender": { + "type": "male" + }, + "customerId": "", + "orgUnitPath": "/", + "isMailboxSetup": true, + "isEnrolledIn2Sv": true, + "isEnforcedIn2Sv": false, + "includeInGlobalAddressList": true, + "thumbnailPhotoUrl": "", + "thumbnailPhotoEtag": "\"\"", + "recoveryEmail": "test.user@gmail.com", + "recoveryPhone": "+55555555555" + }` + fmt.Fprintln(w, response) + } else { + http.NotFound(w, r) + } + })) + defer ts.Close() + + client := &http.Client{} + adminService, err := admin.NewService(context.Background(), option.WithHTTPClient(client), option.WithEndpoint(ts.URL)) + assert.NoError(t, err) + + info, err := getUserInfo(adminService, "test@example.com") + assert.NoError(t, err) + assert.Equal(t, "test.user", info) +} From 5993067505cac4c8e80192787ccd1f4cba05d994 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 8 Nov 2025 12:42:45 +0100 Subject: [PATCH 101/130] Merge commit from fork Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/middleware/headers.go | 37 ++++++++++++++++++++++++++++++---- pkg/middleware/headers_test.go | 21 +++++++++++++++++++ 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbb0974c..20a8f67f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - [#3244](https://github.com/oauth2-proxy/oauth2-proxy/pull/3244) chore(deps): upgrade to latest go1.25.3 (@tuunit) - [#3238](https://github.com/oauth2-proxy/oauth2-proxy/pull/3238) chore: Replace pkg/clock with narrowly targeted stub clocks (@dsymonds) - [#3237](https://github.com/oauth2-proxy/oauth2-proxy/pull/3237) - feat: add option to use organization id for preferred username in Google Provider (@pixeldrew) +- [GHSA-vjrc-mh2v-45x6](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-vjrc-mh2v-45x6) fix: request header smuggling by stripping all normalized header variants (@tuunit) # V7.12.0 diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index 8d2f8e3e..f833848f 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -25,10 +25,10 @@ func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, erro } func newStripHeaders(headers []options.Header) alice.Constructor { - headersToStrip := []string{} + headersToStrip := []options.Header{} for _, header := range headers { if !header.PreserveRequestValue { - headersToStrip = append(headersToStrip, header.Name) + headersToStrip = append(headersToStrip, header) } } @@ -50,10 +50,10 @@ func flattenHeaders(headers http.Header) { } } -func stripHeaders(headers []string, next http.Handler) http.Handler { +func stripHeaders(headers []options.Header, next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { for _, header := range headers { - req.Header.Del(header) + stripNormalizedHeader(req, header) } next.ServeHTTP(rw, req) }) @@ -113,3 +113,32 @@ func injectResponseHeaders(injector header.Injector, next http.Handler) http.Han next.ServeHTTP(rw, req) }) } + +// normalizeHeaderName normalizes the header name by lowercasing it +// and replacing underscores with hyphens. +func normalizeHeaderName(headerName string) string { + headerName = strings.ToLower(headerName) + headerName = strings.ReplaceAll(headerName, "_", "-") + return headerName +} + +// stripNormalizedHeader removes any headers from the request that match +// the normalized version of the provided header's name. +func stripNormalizedHeader(req *http.Request, header options.Header) { + normalizedName := normalizeHeaderName(header.Name) + + toBeDeleted := []string{} + for h := range req.Header { + if normalizeHeaderName(h) == normalizedName { + // necessary to avoid modifying the map while iterating + toBeDeleted = append(toBeDeleted, h) + } + } + + for _, h := range toBeDeleted { + // necessary because req.Header.Del accesses the map via + // the header's canonicalized name. We need to delete by + // the original name. + delete(req.Header, h) + } +} diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 06440eea..14937955 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -205,6 +205,27 @@ var _ = Describe("Headers Suite", func() { expectedHeaders: nil, expectedErr: "error building request header injector: error building request injector: error building injector for header \"X-Auth-Request-Authorization\": error loading basicAuthPassword: secret source is invalid: exactly one entry required, specify either value, fromEnv or fromFile", }), + Entry("strips normalized variants before injecting (no preservation)", headersTableInput{ + headers: []options.Header{ + { + Name: "X-Auth-Request-User", + Values: []options.HeaderValue{ + { + ClaimSource: &options.ClaimSource{Claim: "user"}, + }, + }, + }, + }, + initialHeaders: http.Header{ + "X-Auth-Request-User": []string{"old"}, + "X-Auth_Request_User": []string{"evil"}, + }, + session: &sessionsapi.SessionState{User: "user-123"}, + expectedHeaders: http.Header{ + "X-Auth-Request-User": []string{"user-123"}, + }, + expectedErr: "", + }), ) DescribeTable("the response header injector", From f3f30fa976fb4bb97d6345ba4735cb6d86e24f95 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 8 Nov 2025 12:52:31 +0100 Subject: [PATCH 102/130] Merge commit from fork Signed-off-by: Jan Larwig --- docs/docs/configuration/alpha_config.md | 1 + pkg/apis/options/header.go | 10 ++++++++++ pkg/middleware/headers.go | 5 +++++ pkg/middleware/headers_test.go | 25 ++++++++++++++++++++++++- 4 files changed, 40 insertions(+), 1 deletion(-) diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 54ccb01e..9e6c2873 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -266,6 +266,7 @@ response header. | ----- | ---- | ----------- | | `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | | `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | | `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | ### HeaderValue diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 90e6445c..4299fd35 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -13,6 +13,16 @@ type Header struct { // Defaults to false (headers that match this header will be stripped). PreserveRequestValue bool `json:"preserveRequestValue,omitempty"` + // InsecureSkipHeaderNormalization disables normalizing the header name + // According to RFC 7230 Section 3.2 there aren't any rules about + // capitalization of header names, but the standard practice is to use + // Title-Case (e.g. X-Forwarded-For). By default, header names will be + // normalized to Title-Case and any incoming headers that match will be + // treated as the same header. Additionally underscores (_) in header names + // will be converted to dashes (-) when normalizing. + // Defaults to false (header names will be normalized). + InsecureSkipHeaderNormalization bool `json:"InsecureSkipHeaderNormalization,omitempty"` + // Values contains the desired values for this header Values []HeaderValue `json:"values,omitempty"` } diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index f833848f..623d50e9 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -53,6 +53,11 @@ func flattenHeaders(headers http.Header) { func stripHeaders(headers []options.Header, next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { for _, header := range headers { + if header.InsecureSkipHeaderNormalization { + req.Header.Del(header.Name) + continue + } + stripNormalizedHeader(req, header) } next.ServeHTTP(rw, req) diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 14937955..6a60ec01 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -205,7 +205,7 @@ var _ = Describe("Headers Suite", func() { expectedHeaders: nil, expectedErr: "error building request header injector: error building request injector: error building injector for header \"X-Auth-Request-Authorization\": error loading basicAuthPassword: secret source is invalid: exactly one entry required, specify either value, fromEnv or fromFile", }), - Entry("strips normalized variants before injecting (no preservation)", headersTableInput{ + Entry("strips normalized variants before injecting", headersTableInput{ headers: []options.Header{ { Name: "X-Auth-Request-User", @@ -226,6 +226,29 @@ var _ = Describe("Headers Suite", func() { }, expectedErr: "", }), + Entry("doesn't strip normalized variants before injecting", headersTableInput{ + headers: []options.Header{ + { + Name: "X-Auth-Request-User", + InsecureSkipHeaderNormalization: true, + Values: []options.HeaderValue{ + { + ClaimSource: &options.ClaimSource{Claim: "user"}, + }, + }, + }, + }, + initialHeaders: http.Header{ + "X-Auth-Request-User": []string{"old"}, + "X-Auth_Request_User": []string{"evil"}, + }, + session: &sessionsapi.SessionState{User: "user-123"}, + expectedHeaders: http.Header{ + "X-Auth-Request-User": []string{"user-123"}, + "X-Auth_Request_User": []string{"evil"}, + }, + expectedErr: "", + }), ) DescribeTable("the response header injector", From 22053dcadeb530d70f4a58fa1908cca489b4b39a Mon Sep 17 00:00:00 2001 From: Michi Gysel Date: Sat, 8 Nov 2025 13:49:48 +0100 Subject: [PATCH 103/130] fix: validation of refreshed sessions using the access_token in the OIDC provider (#1933) Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/apis/sessions/session_state.go | 5 +++-- providers/oidc.go | 27 +++++++++++++++++++++------ 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20a8f67f..cb4904c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - [#3238](https://github.com/oauth2-proxy/oauth2-proxy/pull/3238) chore: Replace pkg/clock with narrowly targeted stub clocks (@dsymonds) - [#3237](https://github.com/oauth2-proxy/oauth2-proxy/pull/3237) - feat: add option to use organization id for preferred username in Google Provider (@pixeldrew) - [GHSA-vjrc-mh2v-45x6](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-vjrc-mh2v-45x6) fix: request header smuggling by stripping all normalized header variants (@tuunit) +- [#1933](https://github.com/oauth2-proxy/oauth2-proxy/pull/1933) fix: validation of refreshed sessions using the access_token in the OIDC provider (@gysel / @tuunit) # V7.12.0 diff --git a/pkg/apis/sessions/session_state.go b/pkg/apis/sessions/session_state.go index 5b063c3f..a1f807ab 100644 --- a/pkg/apis/sessions/session_state.go +++ b/pkg/apis/sessions/session_state.go @@ -29,8 +29,9 @@ type SessionState struct { PreferredUsername string `msgpack:"pu,omitempty"` // Internal helpers, not serialized - Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing - Lock Lock `msgpack:"-"` + Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing + Lock Lock `msgpack:"-"` + Refreshed bool `msgpack:"-"` // indicates whether the session was refreshed } func (s *SessionState) now() time.Time { diff --git a/providers/oidc.go b/providers/oidc.go index 15598aba..eeac4073 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -110,11 +110,24 @@ func (p *OIDCProvider) EnrichSession(_ context.Context, s *sessions.SessionState return nil } -// ValidateSession checks that the session's IDToken is still valid +// ValidateSession checks that the session's id_token or access_token (when a ValidateURL is configured) is still valid func (p *OIDCProvider) ValidateSession(ctx context.Context, s *sessions.SessionState) bool { ctx = oidc.ClientContext(ctx, requests.DefaultHTTPClient) - _, err := p.Verifier.Verify(ctx, s.IDToken) - if err != nil { + + // https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse + // The ID Token is optional in the Refresh Token Response + // TODO: @tuunit remove dependency on refreshed flag and only rely on presence of access_token + // in accordance with the spec. For now, keep existing behavior. + if s.Refreshed { + if !validateToken(ctx, p, s.AccessToken, makeOIDCHeader(s.AccessToken)) { + logger.Errorf("access_token validation failed") + return false + } + + return true + } + + if _, err := p.Verifier.Verify(ctx, s.IDToken); err != nil { logger.Errorf("id_token verification failed: %v", err) return false } @@ -122,8 +135,8 @@ func (p *OIDCProvider) ValidateSession(ctx context.Context, s *sessions.SessionS if p.SkipNonce { return true } - err = p.checkNonce(s) - if err != nil { + + if err := p.checkNonce(s); err != nil { logger.Errorf("nonce verification failed: %v", err) return false } @@ -147,7 +160,8 @@ func (p *OIDCProvider) RefreshSession(ctx context.Context, s *sessions.SessionSt } // redeemRefreshToken uses a RefreshToken with the RedeemURL to refresh the -// Access Token and (probably) the ID Token. +// Access Token and (optionally) the ID Token. +// https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse func (p *OIDCProvider) redeemRefreshToken(ctx context.Context, s *sessions.SessionState) error { clientSecret, err := p.GetClientSecret() if err != nil { @@ -250,6 +264,7 @@ func (p *OIDCProvider) createSession(ctx context.Context, token *oauth2.Token, r ss.CreatedAtNow() ss.SetExpiresOn(token.Expiry) + ss.Refreshed = refresh return ss, nil } From fcc2db040e2da5781919f21577f721911a384419 Mon Sep 17 00:00:00 2001 From: Jacob Alberty Date: Sat, 8 Nov 2025 06:58:34 -0600 Subject: [PATCH 104/130] feat: add allowed_* constraint option to proxy endpoint query string (#2841) * Add check for constraints to the proxy endpoint * Add tests for allowed_groups query string * Add this feature to the changelog * Apply suggestions from code review Co-authored-by: Jan Larwig * Use explicit key names in TestProxyAllowedGroups * Document the query parameters on proxy endpoint * Comment was copied from the AuthOnly handler but on closer inspection is not relevant here replacing comment with one more relevant --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/features/endpoints.md | 12 ++++++ oauthproxy.go | 7 ++++ oauthproxy_test.go | 73 ++++++++++++++++++++++++++++++--- 4 files changed, 88 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb4904c5..7594b407 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - [#3237](https://github.com/oauth2-proxy/oauth2-proxy/pull/3237) - feat: add option to use organization id for preferred username in Google Provider (@pixeldrew) - [GHSA-vjrc-mh2v-45x6](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-vjrc-mh2v-45x6) fix: request header smuggling by stripping all normalized header variants (@tuunit) - [#1933](https://github.com/oauth2-proxy/oauth2-proxy/pull/1933) fix: validation of refreshed sessions using the access_token in the OIDC provider (@gysel / @tuunit) +- [#2841](https://github.com/oauth2-proxy/oauth2-proxy/pull/2841) feat: add allowed_* constraint option to proxy endpoint query string (@jacobalberty) # V7.12.0 diff --git a/docs/docs/features/endpoints.md b/docs/docs/features/endpoints.md index 3ec1e2aa..db00ba1e 100644 --- a/docs/docs/features/endpoints.md +++ b/docs/docs/features/endpoints.md @@ -5,6 +5,7 @@ title: Endpoints OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. +- / - the proxy endpoint provides authentication and returns the appropriate 40x error if not authenticated or authorized then passes the request upstream. - /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info - /ping - returns a 200 OK response, which is intended for use with health checks - /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected @@ -45,3 +46,14 @@ It can be configured using the following query parameters: - `allowed_groups`: comma separated list of allowed groups - `allowed_email_domains`: comma separated list of allowed email domains - `allowed_emails`: comma separated list of allowed emails + +### Proxy (/) + +This endpoint returns the upstream response if authenticated. +If unauthenticated it returns a 401 Unauthorized. If the authenticatd user +is not in one of the allowed groups, or emails then it returns a 403 forbidden + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/oauthproxy.go b/oauthproxy.go index 7526d641..c6db18a7 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -1012,6 +1012,13 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) { session, err := p.getAuthenticatedSession(rw, req) switch err { case nil: + // Check against our authorization constraints and return forbidden + // if this request fails to satisfy them. + if !authOnlyAuthorize(req, session) { + http.Error(rw, http.StatusText(http.StatusForbidden), http.StatusForbidden) + return + } + // we are authenticated p.addHeadersForProxying(rw, session) p.headersChain.Then(p.upstreamProxy).ServeHTTP(rw, req) diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 488b8cea..e05396cd 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -2938,12 +2938,75 @@ func TestProxyAllowedGroups(t *testing.T) { name string allowedGroups []string groups []string + querystring string expectUnauthorized bool }{ - {"NoAllowedGroups", []string{}, []string{}, false}, - {"NoAllowedGroupsUserHasGroups", []string{}, []string{"a", "b"}, false}, - {"UserInAllowedGroup", []string{"a"}, []string{"a", "b"}, false}, - {"UserNotInAllowedGroup", []string{"a"}, []string{"c"}, true}, + { + name: "NoAllowedGroups", + allowedGroups: []string{}, + groups: []string{}, + querystring: "", + expectUnauthorized: false}, + { + name: "NoAllowedGroupsUserHasGroups", + allowedGroups: []string{}, + groups: []string{"a", "b"}, + querystring: "", + expectUnauthorized: false}, + { + name: "UserInAllowedGroup", + allowedGroups: []string{"a"}, + groups: []string{"a", "b"}, + querystring: "", + expectUnauthorized: false}, + { + name: "UserNotInAllowedGroup", + allowedGroups: []string{"a"}, + groups: []string{"c"}, + querystring: "", + expectUnauthorized: true}, + { + name: "UserInQuerystringGroup", + allowedGroups: []string{"a", "b"}, + groups: []string{"a", "c"}, + querystring: "?allowed_groups=a", + expectUnauthorized: false}, + { + name: "UserInMultiParamQuerystringGroup", + allowedGroups: []string{"a", "b"}, + groups: []string{"b"}, + querystring: "?allowed_groups=a&allowed_groups=b,d", + expectUnauthorized: false}, + { + name: "UserInOnlyQuerystringGroup", + allowedGroups: []string{}, + groups: []string{"a", "c"}, + querystring: "?allowed_groups=a,b", + expectUnauthorized: false}, + { + name: "UserInDelimitedQuerystringGroup", + allowedGroups: []string{"a", "b", "c"}, + groups: []string{"c"}, + querystring: "?allowed_groups=a,c", + expectUnauthorized: false}, + { + name: "UserNotInQuerystringGroup", + allowedGroups: []string{}, + groups: []string{"c"}, + querystring: "?allowed_groups=a,b", + expectUnauthorized: true}, + { + name: "UserInConfigGroupNotInQuerystringGroup", + allowedGroups: []string{"a", "b", "c"}, + groups: []string{"c"}, + querystring: "?allowed_groups=a,b", + expectUnauthorized: true}, + { + name: "UserInQuerystringGroupNotInConfigGroup", + allowedGroups: []string{"a", "b"}, + groups: []string{"c"}, + querystring: "?allowed_groups=b,c", + expectUnauthorized: true}, } for _, tt := range tests { @@ -2979,7 +3042,7 @@ func TestProxyAllowedGroups(t *testing.T) { t.Fatal(err) } - test.req, _ = http.NewRequest("GET", "/", nil) + test.req, _ = http.NewRequest("GET", fmt.Sprintf("/%s", tt.querystring), nil) test.req.Header.Add("accept", applicationJSON) err = test.SaveSession(session) From 082b49aaeb656fea23ad9accdc5a4be9218bb0d4 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 8 Nov 2025 14:29:37 +0100 Subject: [PATCH 105/130] release: v7.13.0 (#3251) * add new docs version 7.13.x * update to release version v7.13.0 * doc: add release notes v7.13.0 Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 23 + .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- .../version-7.13.x/behaviour.md | 11 + .../version-7.13.x/community/contribution.md | 91 +++ .../version-7.13.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 568 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 310 ++++++++++ .../version-7.13.x/configuration/overview.md | 406 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/cidaas.md | 37 ++ .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 84 +++ .../configuration/providers/index.md | 45 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 ++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../configuration/providers/sourcehut.md | 25 + .../version-7.13.x/configuration/sessions.md | 99 +++ .../configuration/systemd_socket.md | 43 ++ .../version-7.13.x/configuration/tls.md | 85 +++ .../version-7.13.x/features/endpoints.md | 47 ++ .../version-7.13.x/installation.md | 32 + docs/versioned_docs/version-7.13.x/welcome.md | 23 + .../version-7.13.x-sidebars.json | 84 +++ docs/versions.json | 1 + 42 files changed, 3144 insertions(+), 7 deletions(-) create mode 100644 docs/versioned_docs/version-7.13.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.13.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.13.x/community/security.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.13.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/cidaas.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/sourcehut.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.13.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.13.x/installation.md create mode 100644 docs/versioned_docs/version-7.13.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.13.x-sidebars.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 7594b407..13ef6807 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,29 @@ ## Breaking Changes +## Changes since v7.13.0 + +# V7.13.0 + +## Release Highlights + +- 🕵️‍♀️ Vulnerabilities have been addressd + - [CVE-2025-47912](https://nvd.nist.gov/vuln/detail/CVE-2025-47912) + - [CVE-2025-58183](https://nvd.nist.gov/vuln/detail/CVE-2025-58183) + - [CVE-2025-58186](https://nvd.nist.gov/vuln/detail/CVE-2025-58186) + - [CVE-2025-64484](https://nvd.nist.gov/vuln/detail/CVE-2025-64484) +- 🐛 Squashed some bugs + +## Important Notes + +By default all specified headers will now be normalized, meaning that both capitalization and the use of underscores (_) versus dashes (-) will be ignored when matching headers to be stripped. For example, both `X-Forwarded-For` and `X_Forwarded-for` will now be treated as equivalent and stripped away. + +Please read our security advisory for CVE-2025-64484: [GHSA-vjrc-mh2v-45x6](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-vjrc-mh2v-45x6) + +Furthermore, we now use the access_token for validating refreshed sessions in OIDC providers instead of the id_token. This is to align with the [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) which states that id_tokens are not guaranteed to be issued when using refresh tokens. In future releases we might remove the id_token validation for sessions completely. + +## Breaking Changes + ## Changes since v7.12.0 - [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index a43dc457..57d33040 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index f506c4ac..5df6d471 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index faa1b47b..3aa13897 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 60343012..201bfe8d 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 8bff6b03..1ad4805c 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index ae9e3bf1..f1e7a23d 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index bba3f4c3..20a65614 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.12.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.13.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.13.x/behaviour.md b/docs/versioned_docs/version-7.13.x/behaviour.md new file mode 100644 index 00000000..e063d4f9 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/behaviour.md @@ -0,0 +1,11 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) +3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set +4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) + +Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). diff --git a/docs/versioned_docs/version-7.13.x/community/contribution.md b/docs/versioned_docs/version-7.13.x/community/contribution.md new file mode 100644 index 00000000..a8e47349 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/community/contribution.md @@ -0,0 +1,91 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +See the `go.mod` file in the root of this repository for the version of Go used by this project. +You can follow [the installation guide for Go](https://go.dev/doc/install), +and you can find this specific Go version on [the Go downloads page](https://go.dev/dl/). + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:5556 + diff --git a/docs/versioned_docs/version-7.13.x/community/security.md b/docs/versioned_docs/version-7.13.x/community/security.md new file mode 100644 index 00000000..c24b57d9 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md new file mode 100644 index 00000000..9e6c2873 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md @@ -0,0 +1,568 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### Duration +#### (`string` alias) + +(**Appears on:** [Upstream](#upstream)) + +Duration is as string representation of a period of time. +A duration string is a is a possibly signed sequence of decimal numbers, +each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md.tmpl new file mode 100644 index 00000000..8258201f --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.13.x/configuration/integration.md b/docs/versioned_docs/version-7.13.x/configuration/integration.md new file mode 100644 index 00000000..c57cfa6b --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/integration.md @@ -0,0 +1,310 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: + +```yaml +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" +``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.13.x/configuration/overview.md b/docs/versioned_docs/version-7.13.x/configuration/overview.md new file mode 100644 index 00000000..b159df09 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/overview.md @@ -0,0 +1,406 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--disable-keep-alives`
toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.13.x/configuration/providers/adfs.md new file mode 100644 index 00000000..ec8d72d2 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.13.x/configuration/providers/bitbucket.md new file mode 100644 index 00000000..e31de752 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/cidaas.md b/docs/versioned_docs/version-7.13.x/configuration/providers/cidaas.md new file mode 100644 index 00000000..7a987018 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/cidaas.md @@ -0,0 +1,37 @@ +--- +id: cidaas +title: Cidaas +--- + +[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services. +It supports various protocols including OpenID Connect, OAuth 2.0, and SAML. + +However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet. +The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy. + +Example of groups and roles in Cidaas: + +```json +{ + "groups": [ + { + "groupId": "group1", + "roles": ["role1", "role2"] + }, + { + "groupId": "group2", + "roles": ["role3"] + } + ] +} +``` + +This will be transformed into a flat list of groups: + +```json +{ + "groups": ["group1:role1", "group2:role2", "group2:role3"] +} +``` + +Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md). \ No newline at end of file diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.13.x/configuration/providers/digitalocean.md new file mode 100644 index 00000000..f6a1e891 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.13.x/configuration/providers/facebook.md new file mode 100644 index 00000000..352c95ce --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.13.x/configuration/providers/gitea.md new file mode 100644 index 00000000..6c679dd0 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea / Forgejo +--- + +:::note +This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/github.md b/docs/versioned_docs/version-7.13.x/configuration/providers/github.md new file mode 100644 index 00000000..cebca314 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md new file mode 100644 index 00000000..4cdbbbe1 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/google.md b/docs/versioned_docs/version-7.13.x/configuration/providers/google.md new file mode 100644 index 00000000..0de5bb74 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/google.md @@ -0,0 +1,84 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +|-------------------------------------------------|----------------------------------------------| ------ |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------| +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | +| `--google-use-organization-id` | `google_use_organization_id` | bool | use organization id as preferred username | false | +| `--google-admin-api-user-scope` | `google_admin_api_user_scope` | string | the OAuth scope to use when querying the Google Admin SDK for organization id, can be 'readonly', 'user' or 'cloud'
| `readonly` | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.member.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. + +##### Using Organization ID as Preferred Username (optional) +By default, the google provider uses the google id as username. If you would like to use an organization id instead, you can set the `google-use-organization-id` flag to true. +This requires that the service account used to query the Google Admin SDK has one of the following scopes granted in step 5 above: +- `https://www.googleapis.com/auth/admin.directory.user.readonly`, +- `https://www.googleapis.com/auth/admin.directory.user` +- `https://www.googleapis.com/auth/cloud-platform` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/index.md b/docs/versioned_docs/version-7.13.x/configuration/providers/index.md new file mode 100644 index 00000000..3d3938ff --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/index.md @@ -0,0 +1,45 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [Cidaas](cidaas.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak.md new file mode 100644 index 00000000..11a1abca --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 00000000..b29096e3 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.13.x/configuration/providers/linkedin.md new file mode 100644 index 00000000..7d26ec43 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.13.x/configuration/providers/login_gov.md new file mode 100644 index 00000000..badbe48e --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.13.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 00000000..4feefc68 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.13.x/configuration/providers/ms_entra_id.md new file mode 100644 index 00000000..95fb99bc --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.13.x/configuration/providers/nextcloud.md new file mode 100644 index 00000000..85ebff03 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.13.x/configuration/providers/openid_connect.md new file mode 100644 index 00000000..de170058 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.13.x/configuration/providers/sourcehut.md new file mode 100644 index 00000000..2c196bda --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](index.md#email-authentication). + diff --git a/docs/versioned_docs/version-7.13.x/configuration/sessions.md b/docs/versioned_docs/version-7.13.x/configuration/sessions.md new file mode 100644 index 00000000..e2037817 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.13.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.13.x/configuration/systemd_socket.md new file mode 100644 index 00000000..642e6f3f --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.13.x/configuration/tls.md b/docs/versioned_docs/version-7.13.x/configuration/tls.md new file mode 100644 index 00000000..68344b22 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.13.x/features/endpoints.md b/docs/versioned_docs/version-7.13.x/features/endpoints.md new file mode 100644 index 00000000..3ec1e2aa --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/features/endpoints.md @@ -0,0 +1,47 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.13.x/installation.md b/docs/versioned_docs/version-7.13.x/installation.md new file mode 100644 index 00000000..20a65614 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.13.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.13.x/welcome.md b/docs/versioned_docs/version-7.13.x/welcome.md new file mode 100644 index 00000000..7bceadd8 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.13.x-sidebars.json b/docs/versioned_sidebars/version-7.13.x-sidebars.json new file mode 100644 index 00000000..3f5eb854 --- /dev/null +++ b/docs/versioned_sidebars/version-7.13.x-sidebars.json @@ -0,0 +1,84 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect", + "configuration/providers/sourcehut" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index ada187c6..0d7ef696 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.13.x", "7.12.x", "7.11.x", "7.10.x", From fcf4e7947b86cda798c64bb9bb03ffeb3be90e3e Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 9 Nov 2025 20:14:54 +0100 Subject: [PATCH 106/130] fix: hmacauth dependency licensing issue (#3253) * fix: upstream licensing issue by adopting hmacauth library and changing asserting library for its test cases Signed-off-by: Jan Larwig * fix: golang code quality and linting issues for hmacauth Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig --- go.mod | 4 +- go.sum | 4 +- oauthproxy_test.go | 2 +- pkg/authentication/hmacauth/LICENSE.md | 5 + pkg/authentication/hmacauth/hmacauth.go | 237 +++++++++++++++ pkg/authentication/hmacauth/hmacauth_test.go | 302 +++++++++++++++++++ pkg/upstream/http.go | 4 +- pkg/validation/options.go | 2 +- 8 files changed, 551 insertions(+), 9 deletions(-) create mode 100644 pkg/authentication/hmacauth/LICENSE.md create mode 100644 pkg/authentication/hmacauth/hmacauth.go create mode 100644 pkg/authentication/hmacauth/hmacauth_test.go diff --git a/go.mod b/go.mod index 0e14464c..69ffc5fb 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,6 @@ require ( github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 - github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 github.com/onsi/ginkgo/v2 v2.23.4 github.com/onsi/gomega v1.37.0 @@ -30,7 +29,7 @@ require ( github.com/spf13/cast v1.9.2 github.com/spf13/pflag v1.0.7 github.com/spf13/viper v1.20.1 - github.com/stretchr/testify v1.10.0 + github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 golang.org/x/crypto v0.40.0 golang.org/x/net v0.42.0 @@ -45,7 +44,6 @@ require ( cloud.google.com/go/auth v0.16.2 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect github.com/beorn7/perks v1.0.1 // indirect - github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect diff --git a/go.sum b/go.sum index 8bc31660..863da770 100644 --- a/go.sum +++ b/go.sum @@ -18,8 +18,6 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow= github.com/bitly/go-simplejson v0.5.1/go.mod h1:YOPVLzCfwK14b4Sff3oP1AmGhI9T9Vsg84etUnlyp+Q= -github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY= -github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= @@ -142,6 +140,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= diff --git a/oauthproxy_test.go b/oauthproxy_test.go index e05396cd..44569a35 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -15,9 +15,9 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" - "github.com/mbland/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/cookies" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" diff --git a/pkg/authentication/hmacauth/LICENSE.md b/pkg/authentication/hmacauth/LICENSE.md new file mode 100644 index 00000000..4bc7272f --- /dev/null +++ b/pkg/authentication/hmacauth/LICENSE.md @@ -0,0 +1,5 @@ +Copyright (c) 2017 Mike Bland mbland@acm.org + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/pkg/authentication/hmacauth/hmacauth.go b/pkg/authentication/hmacauth/hmacauth.go new file mode 100644 index 00000000..77d2b9e2 --- /dev/null +++ b/pkg/authentication/hmacauth/hmacauth.go @@ -0,0 +1,237 @@ +package hmacauth + +import ( + "bytes" + "crypto" + "crypto/hmac" + "encoding/base64" + "errors" + "fmt" + "io" + "net/http" + "strings" +) + +// HmacAuth signs outbound requests and authenticates inbound requests. +type HmacAuth interface { + // Produces the string that will be prefixed to the request body and + // used to generate the signature. + StringToSign(req *http.Request) string + + // Adds a signature header to the request. + SignRequest(req *http.Request) + + // Generates a signature for the request. + RequestSignature(req *http.Request) string + + // Retrieves the signature included in the request header. + SignatureFromHeader(req *http.Request) string + + // Authenticates the request, returning the result code, the signature + // from the header, and the locally-computed signature. + AuthenticateRequest(request *http.Request) ( + result AuthenticationResult, + headerSignature, computedSignature string) +} + +var supportedAlgorithms = map[string]crypto.Hash{ + "md4": crypto.MD4, + "md5": crypto.MD5, + "sha1": crypto.SHA1, + "sha224": crypto.SHA224, + "sha256": crypto.SHA256, + "sha384": crypto.SHA384, + "sha512": crypto.SHA512, + "ripemd160": crypto.RIPEMD160, +} + +var algorithmName map[crypto.Hash]string + +func init() { + algorithmName = make(map[crypto.Hash]string) + for name, algorithm := range supportedAlgorithms { + algorithmName[algorithm] = name + // Make sure the algorithm is linked into the binary, per + // https://golang.org/pkg/crypto/#Hash.Available + // + // Note that both sides of the client/server connection must + // have an algorithm available in order to successfully + // authenticate using that algorithm + if !algorithm.Available() { + delete(supportedAlgorithms, name) + } + } +} + +// DigestNameToCryptoHash returns the crypto.Hash value corresponding to the +// algorithm name, or an error if the algorithm is not supported. +func DigestNameToCryptoHash(name string) (result crypto.Hash, err error) { + var supported bool + if result, supported = supportedAlgorithms[name]; !supported { + err = errors.New("hmacauth: hash algorithm not supported: " + + name) + } + return +} + +// CryptoHashToDigestName returns the algorithm name corresponding to the +// crypto.Hash ID, or an error if the algorithm is not supported. +func CryptoHashToDigestName(id crypto.Hash) (result string, err error) { + var supported bool + if result, supported = algorithmName[id]; !supported { + err = fmt.Errorf("hmacauth: unsupported crypto.Hash #%d", id) + } + return +} + +type hmacAuth struct { + hash crypto.Hash + key []byte + header string + headers []string +} + +// NewHmacAuth returns an HmacAuth object that can be used to sign or +// authenticate HTTP requests based on the supplied parameters. +func NewHmacAuth(hash crypto.Hash, key []byte, header string, + headers []string) HmacAuth { + if !hash.Available() { + var name string + var supported bool + if name, supported = algorithmName[hash]; !supported { + name = fmt.Sprintf("#%d", hash) + } + panic("hmacauth: hash algorithm " + name + " is unavailable") + } + canonicalHeaders := make([]string, len(headers)) + for i, h := range headers { + canonicalHeaders[i] = http.CanonicalHeaderKey(h) + } + return &hmacAuth{hash, key, header, canonicalHeaders} +} + +func (auth *hmacAuth) StringToSign(req *http.Request) string { + var buffer bytes.Buffer + _, _ = buffer.WriteString(req.Method) + _, _ = buffer.WriteString("\n") + + for _, header := range auth.headers { + values := req.Header[header] + lastIndex := len(values) - 1 + for i, value := range values { + _, _ = buffer.WriteString(value) + if i != lastIndex { + _, _ = buffer.WriteString(",") + } + } + _, _ = buffer.WriteString("\n") + } + _, _ = buffer.WriteString(req.URL.Path) + if req.URL.RawQuery != "" { + _, _ = buffer.WriteString("?") + _, _ = buffer.WriteString(req.URL.RawQuery) + } + if req.URL.Fragment != "" { + _, _ = buffer.WriteString("#") + _, _ = buffer.WriteString(req.URL.Fragment) + } + _, _ = buffer.WriteString("\n") + return buffer.String() +} + +func (auth *hmacAuth) SignRequest(req *http.Request) { + req.Header.Set(auth.header, auth.RequestSignature(req)) +} + +func (auth *hmacAuth) RequestSignature(req *http.Request) string { + return requestSignature(auth, req, auth.hash) +} + +func requestSignature(auth *hmacAuth, req *http.Request, + hashAlgorithm crypto.Hash) string { + h := hmac.New(hashAlgorithm.New, auth.key) + _, _ = h.Write([]byte(auth.StringToSign(req))) + + if req.Body != nil { + reqBody, _ := io.ReadAll(req.Body) + req.Body = io.NopCloser(bytes.NewBuffer(reqBody)) + _, _ = h.Write(reqBody) + } + + var sig []byte + sig = h.Sum(sig) + return algorithmName[hashAlgorithm] + " " + + base64.StdEncoding.EncodeToString(sig) +} + +func (auth *hmacAuth) SignatureFromHeader(req *http.Request) string { + return req.Header.Get(auth.header) +} + +// AuthenticationResult is a code used to identify the outcome of +// HmacAuth.AuthenticateRequest(). +type AuthenticationResult int + +const ( + // ResultNoSignature - the incoming result did not have a signature + // header. + ResultNoSignature AuthenticationResult = iota + + // ResultInvalidFormat - the signature header was not parseable. + ResultInvalidFormat + + // ResultUnsupportedAlgorithm - the signature header specified an + // unsupported algorithm. + ResultUnsupportedAlgorithm + + // ResultMatch - the signature from the request header matched the + // locally-computed signature. + ResultMatch + + // ResultMismatch - the signature from the request header did not match + // the locally-computed signature. + ResultMismatch +) + +var validationResultStrings = []string{ + "", + "ResultNoSignature", + "ResultInvalidFormat", + "ResultUnsupportedAlgorithm", + "ResultMatch", + "ResultMismatch", +} + +func (result AuthenticationResult) String() string { + return validationResultStrings[result] +} + +func (auth *hmacAuth) AuthenticateRequest(request *http.Request) ( + result AuthenticationResult, headerSignature, + computedSignature string) { + headerSignature = auth.SignatureFromHeader(request) + if headerSignature == "" { + result = ResultNoSignature + return + } + + components := strings.Split(headerSignature, " ") + if len(components) != 2 { + result = ResultInvalidFormat + return + } + + algorithm, err := DigestNameToCryptoHash(components[0]) + if err != nil { + result = ResultUnsupportedAlgorithm + return + } + + computedSignature = requestSignature(auth, request, algorithm) + if hmac.Equal([]byte(headerSignature), []byte(computedSignature)) { + result = ResultMatch + } else { + result = ResultMismatch + } + return +} diff --git a/pkg/authentication/hmacauth/hmacauth_test.go b/pkg/authentication/hmacauth/hmacauth_test.go new file mode 100644 index 00000000..84f257d9 --- /dev/null +++ b/pkg/authentication/hmacauth/hmacauth_test.go @@ -0,0 +1,302 @@ +package hmacauth + +import ( + "bufio" + "crypto" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// These correspond to the headers used in bitly/oauth2_proxy#147. +var HEADERS = []string{ + "Content-Length", + "Content-Md5", + "Content-Type", + "Date", + "Authorization", + "X-Forwarded-User", + "X-Forwarded-Email", + "X-Forwarded-Access-Token", + "Cookie", + "Gap-Auth", +} + +func TestSupportedHashAlgorithm(t *testing.T) { + algorithm, err := DigestNameToCryptoHash("sha1") + assert.Equal(t, err, nil) + assert.Equal(t, algorithm, crypto.SHA1) + assert.Equal(t, algorithm.Available(), true) +} + +func TestUnsupportedHashAlgorithm(t *testing.T) { + algorithm, err := DigestNameToCryptoHash("unsupported") + assert.NotEqual(t, err, nil) + assert.Equal(t, err.Error(), + "hmacauth: hash algorithm not supported: unsupported") + assert.Equal(t, algorithm, crypto.Hash(0)) + assert.Equal(t, algorithm.Available(), false) +} + +func TestResultUnsupportedAlgorithmWillCauseNewHmacAuthToPanic(t *testing.T) { + defer func() { + err := recover() + assert.Equal(t, err, + "hmacauth: hash algorithm #0 is unavailable") + }() + NewHmacAuth(crypto.Hash(0), nil, "", nil) +} + +func newTestRequest(request ...string) (req *http.Request) { + reqBuf := bufio.NewReader( + strings.NewReader(strings.Join(request, "\n"))) + if req, err := http.ReadRequest(reqBuf); err != nil { + panic(err) + } else { + return req + } +} + +func testHmacAuth() HmacAuth { + return NewHmacAuth( + crypto.SHA1, []byte("foobar"), "GAP-Signature", HEADERS) +} + +func TestRequestSignaturePost(t *testing.T) { + body := `{ "hello": "world!" }` + req := newTestRequest( + "POST /foo/bar HTTP/1.1", + "Content-Length: "+strconv.Itoa(len(body)), + "Content-MD5: deadbeef", + "Content-Type: application/json", + "Date: 2015-09-28", + "Authorization: trust me", + "X-Forwarded-User: mbland", + "X-Forwarded-Email: mbland@acm.org", + "X-Forwarded-Access-Token: feedbead", + "Cookie: foo; bar; baz=quux", + "Gap-Auth: mbland", + "", + body, + ) + + h := testHmacAuth() + assert.Equal(t, h.StringToSign(req), strings.Join([]string{ + "POST", + strconv.Itoa(len(body)), + "deadbeef", + "application/json", + "2015-09-28", + "trust me", + "mbland", + "mbland@acm.org", + "feedbead", + "foo; bar; baz=quux", + "mbland", + "/foo/bar", + }, "\n")+"\n") + assert.Equal(t, h.RequestSignature(req), + "sha1 K4IrVDtMCRwwW8Oms0VyZWMjXHI=") + + if requestBody, err := io.ReadAll(req.Body); err != nil { + panic(err) + } else { + assert.Equal(t, string(requestBody), body) + } +} + +func newGetRequest() *http.Request { + return newTestRequest( + "GET /foo/bar HTTP/1.1", + "Date: 2015-09-29", + "Cookie: foo; bar; baz=quux", + "Gap-Auth: mbland", + "", + "", + ) +} + +func TestRequestSignatureGetWithFullUrl(t *testing.T) { + req := newTestRequest( + "GET http://localhost/foo/bar?baz=quux%2Fxyzzy#plugh HTTP/1.1", + "Date: 2015-09-29", + "Cookie: foo; bar; baz=quux", + "Gap-Auth: mbland", + "", + "", + ) + + h := testHmacAuth() + assert.Equal(t, h.StringToSign(req), strings.Join([]string{ + "GET", + "", + "", + "", + "2015-09-29", + "", + "", + "", + "", + "foo; bar; baz=quux", + "mbland", + "/foo/bar?baz=quux%2Fxyzzy#plugh", + }, "\n")+"\n") + assert.Equal(t, h.RequestSignature(req), + "sha1 ih5Jce9nsltry63rR4ImNz2hdnk=") +} + +func TestRequestSignatureGetWithMultipleHeadersWithTheSameName(t *testing.T) { + // Just using "Cookie:" out of convenience. + req := newTestRequest( + "GET /foo/bar HTTP/1.1", + "Date: 2015-09-29", + "Cookie: foo", + "Cookie: bar", + "Cookie: baz=quux", + "Gap-Auth: mbland", + "", + "", + ) + + h := testHmacAuth() + assert.Equal(t, h.StringToSign(req), strings.Join([]string{ + "GET", + "", + "", + "", + "2015-09-29", + "", + "", + "", + "", + "foo,bar,baz=quux", + "mbland", + "/foo/bar", + }, "\n")+"\n") + assert.Equal(t, h.RequestSignature(req), + "sha1 JlRkes1X+qq3Bgc/GcRyLos+4aI=") +} + +func TestAuthenticateRequestResultNoSignature(t *testing.T) { + h := testHmacAuth() + req := newGetRequest() + result, header, computed := h.AuthenticateRequest(req) + assert.Equal(t, result, ResultNoSignature) + assert.Equal(t, header, "") + assert.Equal(t, computed, "") +} + +func TestAuthenticateRequestResultInvalidFormat(t *testing.T) { + h := testHmacAuth() + req := newGetRequest() + badValue := "should be algorithm and digest value" + req.Header.Set("GAP-Signature", badValue) + result, header, computed := h.AuthenticateRequest(req) + assert.Equal(t, result, ResultInvalidFormat) + assert.Equal(t, header, badValue) + assert.Equal(t, computed, "") +} + +func TestAuthenticateRequestResultUnsupportedAlgorithm(t *testing.T) { + h := testHmacAuth() + req := newGetRequest() + validSignature := h.RequestSignature(req) + components := strings.Split(validSignature, " ") + signatureWithResultUnsupportedAlgorithm := "unsupported " + + components[1] + req.Header.Set("GAP-Signature", signatureWithResultUnsupportedAlgorithm) + result, header, computed := h.AuthenticateRequest(req) + assert.Equal(t, result, ResultUnsupportedAlgorithm) + assert.Equal(t, header, signatureWithResultUnsupportedAlgorithm) + assert.Equal(t, computed, "") +} + +func TestAuthenticateRequestResultMatch(t *testing.T) { + h := testHmacAuth() + req := newGetRequest() + expected := h.RequestSignature(req) + h.SignRequest(req) + result, header, computed := h.AuthenticateRequest(req) + assert.Equal(t, result, ResultMatch) + assert.Equal(t, header, expected) + assert.Equal(t, computed, expected) +} + +func TestAuthenticateRequestMismatch(t *testing.T) { + foobarAuth := testHmacAuth() + barbazAuth := NewHmacAuth( + crypto.SHA1, []byte("barbaz"), "GAP-Signature", HEADERS) + req := newGetRequest() + foobarAuth.SignRequest(req) + result, header, computed := barbazAuth.AuthenticateRequest(req) + assert.Equal(t, result, ResultMismatch) + assert.Equal(t, header, foobarAuth.RequestSignature(req)) + assert.Equal(t, computed, barbazAuth.RequestSignature(req)) +} + +type SignatureAuthenticator struct { + auth HmacAuth +} + +func (v *SignatureAuthenticator) Authenticate( + w http.ResponseWriter, r *http.Request) { + result, headerSig, computedSig := v.auth.AuthenticateRequest(r) + switch result { + case ResultNoSignature: + w.Write([]byte("no signature received")) + case ResultMatch: + w.Write([]byte("signatures match")) + case ResultMismatch: + w.Write([]byte("signatures do not match:" + + "\n received: " + headerSig + + "\n computed: " + computedSig)) + default: + panic("Unknown result value: " + result.String()) + } +} + +// fakeNetConn simulates an http.Request.Body buffer that will be consumed +// when it is read by the hmacauth.HmacAuth if not handled properly. See: +// +// https://github.com/18F/hmacauth/pull/4 +type fakeNetConn struct { + reqBody string +} + +func (fnc *fakeNetConn) Read(p []byte) (n int, err error) { + if bodyLen := len(fnc.reqBody); bodyLen != 0 { + copy(p, fnc.reqBody) + fnc.reqBody = "" + return bodyLen, io.EOF + } + return 0, io.EOF +} + +func TestSendAuthenticatedPostRequestToServer(t *testing.T) { + key := "foobar" + payload := `{ "hello": "world!" }` + + auth := NewHmacAuth(crypto.SHA1, []byte(key), "X-Test-Signature", nil) + authenticator := &SignatureAuthenticator{auth: auth} + upstream := httptest.NewServer( + http.HandlerFunc(authenticator.Authenticate)) + + req, err := http.NewRequest("POST", upstream.URL+"/foo/bar", + io.NopCloser(&fakeNetConn{reqBody: payload})) + if err != nil { + panic(err) + } + auth.SignRequest(req) + if response, err := http.DefaultClient.Do(req); err != nil { + panic(err) + } else { + assert.Equal(t, response.StatusCode, http.StatusOK) + responseBody, _ := io.ReadAll(response.Body) + assert.Equal(t, "signatures match", string(responseBody)) + } +} diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 7a0e6e84..c1541265 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -8,9 +8,9 @@ import ( "net/url" "strings" - "github.com/mbland/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth" ) const ( @@ -86,7 +86,7 @@ func (h *httpUpstreamProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) // A scope should always be injected before this handler is called. scope.Upstream = h.upstream - // TODO (@NickMeves) - Deprecate GAP-Signature & remove GAP-Auth + // TODO (@tuunit) - Deprecate GAP-Signature & remove GAP-Auth if h.auth != nil { req.Header.Set("GAP-Auth", rw.Header().Get("GAP-Auth")) h.auth.SignRequest(req) diff --git a/pkg/validation/options.go b/pkg/validation/options.go index c720f47e..0f648d6c 100644 --- a/pkg/validation/options.go +++ b/pkg/validation/options.go @@ -8,8 +8,8 @@ import ( "net/url" "strings" - "github.com/mbland/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" From 0107d6da5bd166070ec10eba37dd7ced01fb58cb Mon Sep 17 00:00:00 2001 From: fossabot Date: Sun, 9 Nov 2025 14:20:20 -0500 Subject: [PATCH 107/130] Add license scan report and status (#3248) * Add license scan report and status Signed-off-by: fossabot * doc: fix fossa badge position Signed-off-by: Jan Larwig --------- Signed-off-by: fossabot Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index dfcdc7aa..72e976fb 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE) [![Maintainability](https://api.codeclimate.com/v1/badges/a58ff79407212e2beacb/maintainability)](https://codeclimate.com/github/oauth2-proxy/oauth2-proxy/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/a58ff79407212e2beacb/test_coverage)](https://codeclimate.com/github/oauth2-proxy/oauth2-proxy/test_coverage) +[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy?ref=badge_shield) ![OAuth2 Proxy](docs/static/img/logos/OAuth2_Proxy_horizontal.svg) @@ -84,3 +85,6 @@ See [open redirect vulnerability](https://github.com/oauth2-proxy/oauth2-proxy/s ## License OAuth2-Proxy is distributed under [The MIT License](LICENSE). + + +[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy?ref=badge_large) From 6a4255c21a43ea16a3ae84f50273d030d690307b Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 11 Nov 2025 20:33:50 +0100 Subject: [PATCH 108/130] chore(deps): update docker-compose (#3255) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 5df6d471..f6defb5a 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -39,7 +39,7 @@ services: httpbin: {} gitea: - image: gitea/gitea:1.24.7 + image: gitea/gitea:1.25.1 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 1ad4805c..1e6f6620 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.29 + image: traefik:v2.11.30 volumes: - "./traefik:/etc/traefik" ports: From e4becfdf1fee464624f6db0620c51a0f1094a3ae Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 11 Nov 2025 20:34:16 +0100 Subject: [PATCH 109/130] chore(deps): update dependency node to v24 (#3256) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/docs.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 6f8f7ad6..5f4bbe4f 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -23,7 +23,7 @@ jobs: - uses: actions/setup-node@v6 with: # renovate: datasource=node-version depName=node - node-version: 22 + node-version: 24 - name: Test Build working-directory: ./docs @@ -40,7 +40,7 @@ jobs: - uses: actions/setup-node@v6 with: # renovate: datasource=node-version depName=node - node-version: 22 + node-version: 24 - name: Build docusaurus working-directory: ./docs From 7cf69b27fa93923db4c3bc6104d21235f8d77712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Sampedro?= <5142014+rsrdesarrollo@users.noreply.github.com> Date: Tue, 11 Nov 2025 21:08:08 +0100 Subject: [PATCH 110/130] fix: NewRemoteKeySet is not using DefaultHTTPClient (#3197) * fix: NewRemoteKeySet is not using DefaultHTTPClient Signed-off-by: Jan Larwig * doc: add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 2 ++ pkg/providers/oidc/provider_verifier.go | 3 +++ 2 files changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13ef6807..2aa2ef46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.13.0 +- [#3197](https://github.com/oauth2-proxy/oauth2-proxy/pull/3197) fix: NewRemoteKeySet is not using DefaultHTTPClient (@rsrdesarrollo / @tuunit) + # V7.13.0 ## Release Highlights diff --git a/pkg/providers/oidc/provider_verifier.go b/pkg/providers/oidc/provider_verifier.go index b6b9a970..eac80a8c 100644 --- a/pkg/providers/oidc/provider_verifier.go +++ b/pkg/providers/oidc/provider_verifier.go @@ -10,6 +10,7 @@ import ( "os" "github.com/coreos/go-oidc/v3/oidc" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" k8serrors "k8s.io/apimachinery/pkg/util/errors" ) @@ -127,6 +128,8 @@ func NewProviderVerifier(ctx context.Context, opts ProviderVerifierOptions) (Pro type verifierBuilder func(*oidc.Config) *oidc.IDTokenVerifier func getVerifierBuilder(ctx context.Context, opts ProviderVerifierOptions) (verifierBuilder, DiscoveryProvider, error) { + ctx = oidc.ClientContext(ctx, requests.DefaultHTTPClient) + if opts.SkipDiscovery { var keySet oidc.KeySet var err error From 7c20001045b63a3cc506ce6dbc50bff252efac02 Mon Sep 17 00:00:00 2001 From: tuunit Date: Sat, 4 May 2024 16:41:54 +0200 Subject: [PATCH 111/130] introduce mapstructure decoder for yaml parsing remove color output in tests for better readability in github actions bugfix: remove google as default provider for alpha options fix conversion flow for toml to yaml revert ginkgo color deactivation revert claim- and secret source back to pointers regenerate alpha config Signed-off-by: Jan Larwig --- .golangci.yml | 2 +- docs/docs/configuration/alpha_config.md | 18 +--- main.go | 35 +++++--- main_test.go | 39 +++++---- oauthproxy_test.go | 6 +- pkg/apis/options/alpha_options.go | 25 ++++-- pkg/apis/options/common.go | 63 -------------- pkg/apis/options/duration.go | 43 +++++++++ pkg/apis/options/header.go | 4 +- pkg/apis/options/legacy_options.go | 6 +- pkg/apis/options/legacy_options_test.go | 12 +-- pkg/apis/options/load.go | 111 +++++++++++++++--------- pkg/apis/options/load_test.go | 24 ++--- pkg/apis/options/providers.go | 6 +- pkg/apis/options/secret_source.go | 14 +++ pkg/apis/options/upstreams.go | 4 +- pkg/apis/options/util/util.go | 2 +- pkg/apis/options/util/util_test.go | 2 +- pkg/header/injector_test.go | 16 ++-- pkg/http/http_suite_test.go | 12 +-- pkg/http/server_test.go | 8 +- pkg/middleware/headers_test.go | 8 +- pkg/upstream/http.go | 4 +- pkg/upstream/http_test.go | 24 ++--- pkg/validation/common_test.go | 4 +- pkg/validation/header.go | 2 - pkg/validation/header_test.go | 4 +- pkg/validation/upstreams.go | 2 +- pkg/validation/upstreams_test.go | 2 +- 29 files changed, 269 insertions(+), 233 deletions(-) delete mode 100644 pkg/apis/options/common.go create mode 100644 pkg/apis/options/duration.go create mode 100644 pkg/apis/options/secret_source.go diff --git a/.golangci.yml b/.golangci.yml index edab12d0..62e1df8e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -37,7 +37,7 @@ linters: - linters: - revive path: _test\.go - text: 'dot-imports:' + text: "dot-imports:" # # If we have tests in shared test folders, these can be less strictly linted - linters: - bodyclose diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 9e6c2873..67b3fe1b 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -204,16 +204,6 @@ ClaimSource allows loading a header value from a claim within the session | `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | | `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | -### Duration -#### (`string` alias) - -(**Appears on:** [Upstream](#upstream)) - -Duration is as string representation of a period of time. -A duration string is a is a possibly signed sequence of decimal numbers, -each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". -Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". - ### GitHubOptions (**Appears on:** [Provider](#provider)) @@ -278,7 +268,7 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `value` | _string_ | Value expects a base64 encoded string value. | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | | `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | @@ -490,7 +480,7 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `value` | _string_ | Value expects a base64 encoded string value. | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | @@ -550,10 +540,10 @@ Requests will be proxied to this upstream if the path matches the request path. | `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | | `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | | `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | -| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `flushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | | `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | | `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | -| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | | `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | ### UpstreamConfig diff --git a/main.go b/main.go index cf7e964c..d9fc406b 100644 --- a/main.go +++ b/main.go @@ -67,12 +67,17 @@ func main() { // loadConfiguration will load in the user's configuration. // It will either load the alpha configuration (if alphaConfig is given) // or the legacy configuration. -func loadConfiguration(config, alphaConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { - if alphaConfig != "" { - logger.Printf("WARNING: You are using alpha configuration. The structure in this configuration file may change without notice. You MUST remove conflicting options from your existing configuration.") - return loadAlphaOptions(config, alphaConfig, extraFlags, args) +func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { + opts, err := loadLegacyOptions(config, extraFlags, args) + if err != nil { + return nil, err } - return loadLegacyOptions(config, extraFlags, args) + + if yamlConfig != "" { + logger.Printf("WARNING: You are using alpha configuration. The structure in this configuration file may change without notice. You MUST remove conflicting options from your existing configuration.") + return loadYamlOptions(yamlConfig, config, extraFlags, args) + } + return opts, err } // loadLegacyOptions loads the old toml options using the legacy flagset @@ -97,17 +102,17 @@ func loadLegacyOptions(config string, extraFlags *pflag.FlagSet, args []string) return opts, nil } -// loadAlphaOptions loads the old style config excluding options converted to +// loadYamlOptions loads the old style config excluding options converted to // the new alpha format, then merges the alpha options, loaded from YAML, // into the core configuration. -func loadAlphaOptions(config, alphaConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { +func loadYamlOptions(yamlConfig, config string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { opts, err := loadOptions(config, extraFlags, args) if err != nil { return nil, fmt.Errorf("failed to load core options: %v", err) } - alphaOpts := &options.AlphaOptions{} - if err := options.LoadYAML(alphaConfig, alphaOpts); err != nil { + alphaOpts := options.NewAlphaOptions(opts) + if err := options.LoadYAML(yamlConfig, alphaOpts); err != nil { return nil, fmt.Errorf("failed to load alpha options: %v", err) } @@ -137,10 +142,16 @@ func loadOptions(config string, extraFlags *pflag.FlagSet, args []string) (*opti // printConvertedConfig extracts alpha options from the loaded configuration // and renders these to stdout in YAML format. func printConvertedConfig(opts *options.Options) error { - alphaConfig := &options.AlphaOptions{} - alphaConfig.ExtractFrom(opts) + alphaConfig := options.NewAlphaOptions(opts) - data, err := yaml.Marshal(alphaConfig) + // Generic interface for loading arbitrary yaml structure + var buffer map[string]interface{} + + if err := options.Decode(alphaConfig, &buffer); err != nil { + return fmt.Errorf("unable to decode alpha config into interface: %w", err) + } + + data, err := yaml.Marshal(buffer) if err != nil { return fmt.Errorf("unable to marshal config: %v", err) } diff --git a/main_test.go b/main_test.go index 8e40fe7f..a6ea83c2 100644 --- a/main_test.go +++ b/main_test.go @@ -43,29 +43,35 @@ upstreamConfig: injectRequestHeaders: - name: Authorization values: - - claim: user - prefix: "Basic " - basicAuthPassword: - value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: super-secret-password - name: X-Forwarded-Groups values: - - claim: groups + - claimSource: + claim: groups - name: X-Forwarded-User values: - - claim: user + - claimSource: + claim: user - name: X-Forwarded-Email values: - - claim: email + - claimSource: + claim: email - name: X-Forwarded-Preferred-Username values: - - claim: preferred_username + - claimSource: + claim: preferred_username injectResponseHeaders: - name: Authorization values: - - claim: user - prefix: "Basic " - basicAuthPassword: - value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: super-secret-password server: bindAddress: "127.0.0.1:4180" providers: @@ -100,9 +106,8 @@ redirect_url="http://localhost:4180/oauth2/callback" return &b } - durationPtr := func(d time.Duration) *options.Duration { - du := options.Duration(d) - return &du + durationPtr := func(d time.Duration) *time.Duration { + return &d } testExpectedOptions := func() *options.Options { @@ -136,7 +141,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Claim: "user", Prefix: "Basic ", BasicAuthPassword: &options.SecretSource{ - Value: []byte("super-secret-password"), + Value: "super-secret-password", }, }, }, @@ -226,7 +231,7 @@ redirect_url="http://localhost:4180/oauth2/callback" opts, err := loadConfiguration(configFileName, alphaConfigFileName, extraFlags, in.args) if in.expectedErr != nil { - Expect(err).To(MatchError(in.expectedErr.Error())) + Expect(err).To(MatchError(ContainSubstring(in.expectedErr.Error()))) } else { Expect(err).ToNot(HaveOccurred()) } diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 44569a35..d5fac782 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -215,7 +215,7 @@ func TestBasicAuthPassword(t *testing.T) { ClaimSource: &options.ClaimSource{ Claim: "email", BasicAuthPassword: &options.SecretSource{ - Value: []byte(basicAuthPassword), + Value: basicAuthPassword, }, }, }, @@ -1282,7 +1282,7 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte("This is a secure password"), + Value: "This is a secure password", }, }, }, @@ -2044,7 +2044,7 @@ func baseTestOptions() *options.Options { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("This is a secure password"))), + Value: base64.StdEncoding.EncodeToString([]byte("This is a secure password")), }, }, }, diff --git a/pkg/apis/options/alpha_options.go b/pkg/apis/options/alpha_options.go index a438518c..278db401 100644 --- a/pkg/apis/options/alpha_options.go +++ b/pkg/apis/options/alpha_options.go @@ -47,15 +47,11 @@ type AlphaOptions struct { Providers Providers `json:"providers,omitempty"` } -// MergeInto replaces alpha options in the Options struct with the values -// from the AlphaOptions -func (a *AlphaOptions) MergeInto(opts *Options) { - opts.UpstreamServers = a.UpstreamConfig - opts.InjectRequestHeaders = a.InjectRequestHeaders - opts.InjectResponseHeaders = a.InjectResponseHeaders - opts.Server = a.Server - opts.MetricsServer = a.MetricsServer - opts.Providers = a.Providers +// Initialize alpha options with default values and settings of the core options +func NewAlphaOptions(opts *Options) *AlphaOptions { + aOpts := &AlphaOptions{} + aOpts.ExtractFrom(opts) + return aOpts } // ExtractFrom populates the fields in the AlphaOptions with the values from @@ -68,3 +64,14 @@ func (a *AlphaOptions) ExtractFrom(opts *Options) { a.MetricsServer = opts.MetricsServer a.Providers = opts.Providers } + +// MergeInto replaces alpha options in the Options struct with the values +// from the AlphaOptions +func (a *AlphaOptions) MergeInto(opts *Options) { + opts.UpstreamServers = a.UpstreamConfig + opts.InjectRequestHeaders = a.InjectRequestHeaders + opts.InjectResponseHeaders = a.InjectResponseHeaders + opts.Server = a.Server + opts.MetricsServer = a.MetricsServer + opts.Providers = a.Providers +} diff --git a/pkg/apis/options/common.go b/pkg/apis/options/common.go deleted file mode 100644 index 88d24d82..00000000 --- a/pkg/apis/options/common.go +++ /dev/null @@ -1,63 +0,0 @@ -package options - -import ( - "fmt" - "strconv" - "time" -) - -// SecretSource references an individual secret value. -// Only one source within the struct should be defined at any time. -type SecretSource struct { - // Value expects a base64 encoded string value. - Value []byte `json:"value,omitempty"` - - // FromEnv expects the name of an environment variable. - FromEnv string `json:"fromEnv,omitempty"` - - // FromFile expects a path to a file containing the secret value. - FromFile string `json:"fromFile,omitempty"` -} - -// Duration is an alias for time.Duration so that we can ensure the marshalling -// and unmarshalling of string durations is done as users expect. -// Intentional blank line below to keep this first part of the comment out of -// any generated references. - -// Duration is as string representation of a period of time. -// A duration string is a is a possibly signed sequence of decimal numbers, -// each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". -// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". -// +reference-gen:alias-name=string -type Duration time.Duration - -// UnmarshalJSON parses the duration string and sets the value of duration -// to the value of the duration string. -func (d *Duration) UnmarshalJSON(data []byte) error { - input := string(data) - if unquoted, err := strconv.Unquote(input); err == nil { - input = unquoted - } - - du, err := time.ParseDuration(input) - if err != nil { - return err - } - *d = Duration(du) - return nil -} - -// MarshalJSON ensures that when the string is marshalled to JSON as a human -// readable string. -func (d *Duration) MarshalJSON() ([]byte, error) { - dStr := fmt.Sprintf("%q", d.Duration().String()) - return []byte(dStr), nil -} - -// Duration returns the time.Duration version of this Duration -func (d *Duration) Duration() time.Duration { - if d == nil { - return time.Duration(0) - } - return time.Duration(*d) -} diff --git a/pkg/apis/options/duration.go b/pkg/apis/options/duration.go new file mode 100644 index 00000000..da13d96e --- /dev/null +++ b/pkg/apis/options/duration.go @@ -0,0 +1,43 @@ +package options + +import ( + "reflect" + "time" + + "github.com/mitchellh/mapstructure" +) + +// Duration is an alias for time.Duration so that we can ensure the marshalling +// and unmarshalling of string durations is done as users expect. +// Intentional blank line below to keep this first part of the comment out of +// any generated references. + +// Duration is as string representation of a period of time. +// A duration string is a is a possibly signed sequence of decimal numbers, +// each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +// Conversion from string or floating point to golang duration type +// This way floating points will be converted to seconds and strings +// of type 3s or 5m will be parsed with time.ParseDuration +func toDurationHookFunc() mapstructure.DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if t != reflect.TypeOf(time.Duration(0)) { + return data, nil + } + + switch f.Kind() { + case reflect.String: + return time.ParseDuration(data.(string)) + case reflect.Float64: + return time.Duration(data.(float64) * float64(time.Second)), nil + case reflect.Int64: + return time.Duration(data.(int64)), nil + default: + return data, nil + } + } +} diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 4299fd35..164f9fee 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -31,10 +31,10 @@ type Header struct { // make up the header value type HeaderValue struct { // Allow users to load the value from a secret source - *SecretSource `json:",omitempty"` + *SecretSource `json:"secretSource,omitempty"` // Allow users to load the value from a session claim - *ClaimSource `json:",omitempty"` + *ClaimSource `json:"claimSource,omitempty"` } // ClaimSource allows loading a header value from a claim within the session diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index e22278fa..45e4b113 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -136,8 +136,8 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { u.Path = "/" } - flushInterval := Duration(l.FlushInterval) - timeout := Duration(l.Timeout) + flushInterval := l.FlushInterval + timeout := l.Timeout upstream := Upstream{ ID: u.Path, Path: u.Path, @@ -294,7 +294,7 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header Claim: claim, Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: []byte(basicAuthPassword), + Value: basicAuthPassword, }, }, }, diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 9481cf95..c5f0e4da 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -15,8 +15,8 @@ var _ = Describe("Legacy Options", func() { legacyOpts := NewLegacyOptions() // Set upstreams and related options to test their conversion - flushInterval := Duration(5 * time.Second) - timeout := Duration(5 * time.Second) + flushInterval := 5 * time.Second + timeout := 5 * time.Second legacyOpts.LegacyUpstreams.FlushInterval = time.Duration(flushInterval) legacyOpts.LegacyUpstreams.Timeout = time.Duration(timeout) legacyOpts.LegacyUpstreams.PassHostHeader = true @@ -147,8 +147,8 @@ var _ = Describe("Legacy Options", func() { skipVerify := true passHostHeader := false proxyWebSockets := true - flushInterval := Duration(5 * time.Second) - timeout := Duration(5 * time.Second) + flushInterval := 5 * time.Second + timeout := 5 * time.Second disableKeepAlives := true // Test cases and expected outcomes @@ -369,7 +369,7 @@ var _ = Describe("Legacy Options", func() { Claim: "user", Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: []byte(basicAuthSecret), + Value: basicAuthSecret, }, }, }, @@ -409,7 +409,7 @@ var _ = Describe("Legacy Options", func() { Claim: "email", Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: []byte(basicAuthSecret), + Value: basicAuthSecret, }, }, }, diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index c302e8e7..22e775a8 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -55,6 +55,76 @@ func Load(configFileName string, flagSet *pflag.FlagSet, into interface{}) error return nil } +// LoadYAML will load a YAML based configuration file into the options interface provided. +func LoadYAML(configFileName string, opts interface{}) error { + buffer, err := loadAndSubstituteEnvs(configFileName) + if err != nil { + return err + } + + // Generic interface for loading arbitrary yaml structure + var intermediate map[string]interface{} + + if err := yaml.Unmarshal(buffer, &intermediate); err != nil { + return fmt.Errorf("error unmarshalling config: %w", err) + } + + return Decode(intermediate, opts) +} + +func Decode(input interface{}, result interface{}) error { + // Using mapstructure to decode arbitrary yaml structure into options and + // merge with existing values instead of overwriting everything. This is especially + // important as we have a lot of default values for boolean which are supposed to be + // true by default. Normally by just parsing through yaml all booleans that aren't + // referenced in the config file would be parsed as false and we cannot identify after + // the fact if they have been explicitly set to false or have not been referenced. + decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ + DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), + Metadata: nil, // Don't track any metadata + Result: result, // Decode the result into the prefilled options + TagName: "json", // Parse all fields that use the yaml tag + ZeroFields: false, // Don't clean the default values from the result map (options) + ErrorUnused: true, // Throw an error if keys have been used that aren't mapped to any struct fields + IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with yaml + }) + + if err != nil { + return fmt.Errorf("error creating decoder for config: %w", err) + } + + if err := decoder.Decode(input); err != nil { + return fmt.Errorf("error decoding config: %w", err) + } + + return nil +} + +// loadAndSubstituteEnvs reads the yaml config into a generic byte buffer and +// substitute env references +func loadAndSubstituteEnvs(configFileName string) ([]byte, error) { + if configFileName == "" { + return nil, errors.New("no configuration file provided") + } + + unparsedBuffer, err := os.ReadFile(configFileName) + if err != nil { + return nil, fmt.Errorf("unable to load config file: %w", err) + } + + modifiedBuffer, err := normalizeSubstitution(unparsedBuffer) + if err != nil { + return nil, fmt.Errorf("error normalizing substitution string : %w", err) + } + + buffer, err := envsubst.Bytes(modifiedBuffer) + if err != nil { + return nil, fmt.Errorf("error in substituting env variables : %w", err) + } + + return buffer, nil +} + // registerFlags uses `cfg` and `flag` tags to associate flags in the flagSet // to the fields in the options interface provided. // Each exported field in the options must have a `cfg` tag otherwise an error will occur. @@ -140,47 +210,6 @@ func isUnexported(name string) bool { return first == strings.ToLower(first) } -// LoadYAML will load a YAML based configuration file into the options interface provided. -func LoadYAML(configFileName string, into interface{}) error { - buffer, err := loadAndParseYaml(configFileName) - if err != nil { - return err - } - - // UnmarshalStrict will return an error if the config includes options that are - // not mapped to fields of the into struct - if err := yaml.UnmarshalStrict(buffer, into, yaml.DisallowUnknownFields); err != nil { - return fmt.Errorf("error unmarshalling config: %w", err) - } - - return nil -} - -// loadAndParseYaml reads the config from the filesystem and -// execute the environment variable substitution -func loadAndParseYaml(configFileName string) ([]byte, error) { - if configFileName == "" { - return nil, errors.New("no configuration file provided") - } - - unparsedBuffer, err := os.ReadFile(configFileName) - if err != nil { - return nil, fmt.Errorf("unable to load config file: %w", err) - } - - modifiedBuffer, err := normalizeSubstitution(unparsedBuffer) - if err != nil { - return nil, fmt.Errorf("error normalizing substitution string : %w", err) - } - - buffer, err := envsubst.Bytes(modifiedBuffer) - if err != nil { - return nil, fmt.Errorf("error in substituting env variables : %w", err) - } - - return buffer, nil -} - // normalizeSubstitution normalizes dollar signs ($) with numerals like // $1 or $2 properly by correctly escaping them func normalizeSubstitution(unparsedBuffer []byte) ([]byte, error) { diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 06123c37..6f327a22 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -355,15 +355,15 @@ var _ = Describe("Load", func() { var _ = Describe("LoadYAML", func() { Context("with a testOptions structure", func() { type TestOptionSubStruct struct { - StringSliceOption []string `yaml:"stringSliceOption,omitempty"` + StringSliceOption []string `json:"stringSliceOption,omitempty"` } type TestOptions struct { - StringOption string `yaml:"stringOption,omitempty"` - Sub TestOptionSubStruct `yaml:"sub,omitempty"` + StringOption string `json:"stringOption,omitempty"` + Sub TestOptionSubStruct `json:"sub,omitempty"` // Check that embedded fields can be unmarshalled - TestOptionSubStruct `yaml:",inline,squash"` + TestOptionSubStruct `json:",inline,squash"` } var testOptionsConfigBytesFull = []byte(` @@ -416,7 +416,7 @@ sub: err := LoadYAML(configFileName, input) if in.expectedErr != nil { - Expect(err).To(MatchError(in.expectedErr.Error())) + Expect(err).To(MatchError(ContainSubstring(in.expectedErr.Error()))) } else { Expect(err).ToNot(HaveOccurred()) } @@ -459,13 +459,13 @@ sub: StringSliceOption: []string{"a", "b", "c"}, }, }, - expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: unknown field \"foo\""), + expectedErr: errors.New("has invalid keys: foo"), }), Entry("with an incorrect type for a string field", loadYAMLTableInput{ configFile: []byte(`stringOption: ["a", "b"]`), input: &TestOptions{}, expectedOutput: &TestOptions{}, - expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal array into Go struct field TestOptions.StringOption of type string"), + expectedErr: errors.New("'stringOption' expected type 'string', got unconvertible type"), }), Entry("with an incorrect type for an array field", loadYAMLTableInput{ configFile: []byte(`stringSliceOption: "a"`), @@ -526,11 +526,13 @@ upstreamConfig: injectRequestHeaders: - name: X-Forwarded-User values: - - claim: user + - claimSource: + claim: user injectResponseHeaders: - name: X-Secret values: - - value: c2VjcmV0 + - secretSource: + value: secret `) By("Creating a config file") @@ -548,7 +550,7 @@ injectResponseHeaders: into := &AlphaOptions{} Expect(LoadYAML(configFileName, into)).To(Succeed()) - flushInterval := Duration(500 * time.Millisecond) + flushInterval := 500 * time.Millisecond Expect(into).To(Equal(&AlphaOptions{ UpstreamConfig: UpstreamConfig{ @@ -579,7 +581,7 @@ injectResponseHeaders: Values: []HeaderValue{ { SecretSource: &SecretSource{ - Value: []byte("secret"), + Value: "secret", }, }, }, diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 3a5094da..c876f46b 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -242,16 +242,16 @@ type OIDCOptions struct { IssuerURL string `json:"issuerURL,omitempty"` // InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified // default set to 'false' - InsecureAllowUnverifiedEmail bool `json:"insecureAllowUnverifiedEmail,omitempty"` + InsecureAllowUnverifiedEmail bool `json:"insecureAllowUnverifiedEmail"` // InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL // default set to 'false' - InsecureSkipIssuerVerification bool `json:"insecureSkipIssuerVerification,omitempty"` + InsecureSkipIssuerVerification bool `json:"insecureSkipIssuerVerification"` // InsecureSkipNonce skips verifying the ID Token's nonce claim that must match // the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked // after the initial OAuth redeem & subsequent token refreshes. // default set to 'true' // Warning: In a future release, this will change to 'false' by default for enhanced security. - InsecureSkipNonce bool `json:"insecureSkipNonce,omitempty"` + InsecureSkipNonce bool `json:"insecureSkipNonce"` // SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints // default set to 'false' SkipDiscovery bool `json:"skipDiscovery,omitempty"` diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go new file mode 100644 index 00000000..2be4d890 --- /dev/null +++ b/pkg/apis/options/secret_source.go @@ -0,0 +1,14 @@ +package options + +// SecretSource references an individual secret value. +// Only one source within the struct should be defined at any time. +type SecretSource struct { + // Value expects a base64 encoded string value. + Value string `json:"value,omitempty"` + + // FromEnv expects the name of an environment variable. + FromEnv string `json:"fromEnv,omitempty"` + + // FromFile expects a path to a file containing the secret value. + FromFile string `json:"fromFile,omitempty"` +} diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index b3c7195f..1002ae07 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -79,7 +79,7 @@ type Upstream struct { // FlushInterval is the period between flushing the response buffer when // streaming response from the upstream. // Defaults to 1 second. - FlushInterval *Duration `json:"flushInterval,omitempty"` + FlushInterval *time.Duration `json:"flushInterval,omitempty"` // PassHostHeader determines whether the request host header should be proxied // to the upstream server. @@ -92,7 +92,7 @@ type Upstream struct { // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. - Timeout *Duration `json:"timeout,omitempty"` + Timeout *time.Duration `json:"timeout,omitempty"` // DisableKeepAlives disables HTTP keep-alive connections to the upstream server. // Defaults to false. diff --git a/pkg/apis/options/util/util.go b/pkg/apis/options/util/util.go index 03f0a134..794a6e91 100644 --- a/pkg/apis/options/util/util.go +++ b/pkg/apis/options/util/util.go @@ -11,7 +11,7 @@ import ( func GetSecretValue(source *options.SecretSource) ([]byte, error) { switch { case len(source.Value) > 0 && source.FromEnv == "" && source.FromFile == "": - return source.Value, nil + return []byte(source.Value), nil case len(source.Value) == 0 && source.FromEnv != "" && source.FromFile == "": return []byte(os.Getenv(source.FromEnv)), nil case len(source.Value) == 0 && source.FromEnv == "" && source.FromFile != "": diff --git a/pkg/apis/options/util/util_test.go b/pkg/apis/options/util/util_test.go index e84db1ec..5c4bfa6d 100644 --- a/pkg/apis/options/util/util_test.go +++ b/pkg/apis/options/util/util_test.go @@ -31,7 +31,7 @@ var _ = Describe("GetSecretValue", func() { It("returns the correct value from the string value", func() { value, err := GetSecretValue(&options.SecretSource{ - Value: []byte("secret-value-1"), + Value: "secret-value-1", }) Expect(err).ToNot(HaveOccurred()) Expect(string(value)).To(Equal("secret-value-1")) diff --git a/pkg/header/injector_test.go b/pkg/header/injector_test.go index 25c276dc..bb37261d 100644 --- a/pkg/header/injector_test.go +++ b/pkg/header/injector_test.go @@ -55,7 +55,7 @@ var _ = Describe("Injector Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte("super-secret"), + Value: "super-secret", }, }, }, @@ -199,7 +199,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte("basic-password"), + Value: "basic-password", }, }, }, @@ -227,7 +227,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), + Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), }, }, }, @@ -322,7 +322,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), + Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), FromEnv: "SECRET_ENV", }, }, @@ -348,7 +348,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte("basic-password"), + Value: "basic-password", }, }, }, @@ -379,17 +379,17 @@ var _ = Describe("Injector Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte("major=1"), + Value: "major=1", }, }, { SecretSource: &options.SecretSource{ - Value: []byte("minor=2"), + Value: "minor=2", }, }, { SecretSource: &options.SecretSource{ - Value: []byte("patch=3"), + Value: "patch=3", }, }, }, diff --git a/pkg/http/http_suite_test.go b/pkg/http/http_suite_test.go index 19d4d3ff..219f26ea 100644 --- a/pkg/http/http_suite_test.go +++ b/pkg/http/http_suite_test.go @@ -48,10 +48,10 @@ var _ = BeforeSuite(func() { certOut := new(bytes.Buffer) Expect(pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})).To(Succeed()) - ipv4CertDataSource.Value = certOut.Bytes() + ipv4CertDataSource.Value = certOut.String() keyOut := new(bytes.Buffer) Expect(pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})).To(Succeed()) - ipv4KeyDataSource.Value = keyOut.Bytes() + ipv4KeyDataSource.Value = keyOut.String() }) By("Generating a ipv6 self-signed cert for TLS tests", func() { @@ -61,16 +61,16 @@ var _ = BeforeSuite(func() { certOut := new(bytes.Buffer) Expect(pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})).To(Succeed()) - ipv6CertDataSource.Value = certOut.Bytes() + ipv6CertDataSource.Value = certOut.String() keyOut := new(bytes.Buffer) Expect(pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})).To(Succeed()) - ipv6KeyDataSource.Value = keyOut.Bytes() + ipv6KeyDataSource.Value = keyOut.String() }) By("Setting up a http client", func() { - ipv4cert, err := tls.X509KeyPair(ipv4CertDataSource.Value, ipv4KeyDataSource.Value) + ipv4cert, err := tls.X509KeyPair([]byte(ipv4CertDataSource.Value), []byte(ipv4KeyDataSource.Value)) Expect(err).ToNot(HaveOccurred()) - ipv6cert, err := tls.X509KeyPair(ipv6CertDataSource.Value, ipv6KeyDataSource.Value) + ipv6cert, err := tls.X509KeyPair([]byte(ipv6CertDataSource.Value), []byte(ipv6KeyDataSource.Value)) Expect(err).ToNot(HaveOccurred()) ipv4certificate, err := x509.ParseCertificate(ipv4cert.Certificate[0]) diff --git a/pkg/http/server_test.go b/pkg/http/server_test.go index 8dfa13af..6584b757 100644 --- a/pkg/http/server_test.go +++ b/pkg/http/server_test.go @@ -234,7 +234,7 @@ var _ = Describe("Server", func() { SecureBindAddress: "127.0.0.1:0", TLS: &options.TLS{ Key: &options.SecretSource{ - Value: []byte("invalid"), + Value: "invalid", }, Cert: &ipv4CertDataSource, }, @@ -250,7 +250,7 @@ var _ = Describe("Server", func() { TLS: &options.TLS{ Key: &ipv4KeyDataSource, Cert: &options.SecretSource{ - Value: []byte("invalid"), + Value: "invalid", }, }, }, @@ -506,7 +506,7 @@ var _ = Describe("Server", func() { SecureBindAddress: "[::1]:0", TLS: &options.TLS{ Key: &options.SecretSource{ - Value: []byte("invalid"), + Value: "invalid", }, Cert: &ipv6CertDataSource, }, @@ -523,7 +523,7 @@ var _ = Describe("Server", func() { TLS: &options.TLS{ Key: &ipv6KeyDataSource, Cert: &options.SecretSource{ - Value: []byte("invalid"), + Value: "invalid", }, }, }, diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 6a60ec01..cb8f9d11 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -188,7 +188,7 @@ var _ = Describe("Headers Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), + Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), FromEnv: "SECRET_ENV", }, }, @@ -304,7 +304,7 @@ var _ = Describe("Headers Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte("_oauth2_proxy=ey123123123"), + Value: "_oauth2_proxy=ey123123123", }, }, }, @@ -314,7 +314,7 @@ var _ = Describe("Headers Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte("oauth_user"), + Value: "oauth_user", }, }, }, @@ -460,7 +460,7 @@ var _ = Describe("Headers Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), + Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), FromEnv: "SECRET_ENV", }, }, diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index c1541265..f81f4ec0 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -137,12 +137,12 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Change default duration for waiting for an upstream response if upstream.Timeout != nil { - transport.ResponseHeaderTimeout = upstream.Timeout.Duration() + transport.ResponseHeaderTimeout = *upstream.Timeout } // Configure options on the SingleHostReverseProxy if upstream.FlushInterval != nil { - proxy.FlushInterval = upstream.FlushInterval.Duration() + proxy.FlushInterval = *upstream.FlushInterval } else { proxy.FlushInterval = options.DefaultUpstreamFlushInterval } diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index 31476df0..df264c33 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -21,8 +21,8 @@ import ( ) var _ = Describe("HTTP Upstream Suite", func() { - defaultFlushInterval := options.Duration(options.DefaultUpstreamFlushInterval) - defaultTimeout := options.Duration(options.DefaultUpstreamTimeout) + defaultFlushInterval := options.DefaultUpstreamFlushInterval + defaultTimeout := options.DefaultUpstreamTimeout truth := true falsum := false @@ -57,9 +57,9 @@ var _ = Describe("HTTP Upstream Suite", func() { req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{}) rw := httptest.NewRecorder() - flush := options.Duration(1 * time.Second) + flush := 1 * time.Second - timeout := options.Duration(options.DefaultUpstreamTimeout) + timeout := options.DefaultUpstreamTimeout upstream := options.Upstream{ ID: in.id, @@ -373,11 +373,11 @@ var _ = Describe("HTTP Upstream Suite", func() { type newUpstreamTableInput struct { proxyWebSockets bool - flushInterval options.Duration + flushInterval time.Duration skipVerify bool sigData *options.SignatureData errorHandler func(http.ResponseWriter, *http.Request, error) - timeout options.Duration + timeout time.Duration disableKeepAlives bool } @@ -406,10 +406,10 @@ var _ = Describe("HTTP Upstream Suite", func() { proxy, ok := upstreamProxy.handler.(*httputil.ReverseProxy) Expect(ok).To(BeTrue()) - Expect(proxy.FlushInterval).To(Equal(in.flushInterval.Duration())) + Expect(proxy.FlushInterval).To(Equal(in.flushInterval)) transport, ok := proxy.Transport.(*http.Transport) Expect(ok).To(BeTrue()) - Expect(transport.ResponseHeaderTimeout).To(Equal(in.timeout.Duration())) + Expect(transport.ResponseHeaderTimeout).To(Equal(in.timeout)) Expect(proxy.ErrorHandler != nil).To(Equal(in.errorHandler != nil)) if in.skipVerify { Expect(transport.TLSClientConfig.InsecureSkipVerify).To(Equal(true)) @@ -428,7 +428,7 @@ var _ = Describe("HTTP Upstream Suite", func() { }), Entry("with a non standard flush interval", &newUpstreamTableInput{ proxyWebSockets: false, - flushInterval: options.Duration(5 * time.Second), + flushInterval: 5 * time.Second, skipVerify: false, sigData: nil, errorHandler: nil, @@ -466,7 +466,7 @@ var _ = Describe("HTTP Upstream Suite", func() { skipVerify: false, sigData: nil, errorHandler: nil, - timeout: options.Duration(5 * time.Second), + timeout: 5 * time.Second, }), Entry("with a DisableKeepAlives", &newUpstreamTableInput{ proxyWebSockets: false, @@ -483,8 +483,8 @@ var _ = Describe("HTTP Upstream Suite", func() { var proxyServer *httptest.Server BeforeEach(func() { - flush := options.Duration(1 * time.Second) - timeout := options.Duration(options.DefaultUpstreamTimeout) + flush := 1 * time.Second + timeout := options.DefaultUpstreamTimeout upstream := options.Upstream{ ID: "websocketProxy", PassHostHeader: &truth, diff --git a/pkg/validation/common_test.go b/pkg/validation/common_test.go index 9e873c35..bb7c2dd6 100644 --- a/pkg/validation/common_test.go +++ b/pkg/validation/common_test.go @@ -9,12 +9,12 @@ import ( ) var _ = Describe("Common", func() { - var validSecretSourceValue []byte + var validSecretSourceValue string const validSecretSourceEnv = "OAUTH2_PROXY_TEST_SECRET_SOURCE_ENV" var validSecretSourceFile string BeforeEach(func() { - validSecretSourceValue = []byte("This is a secret source value") + validSecretSourceValue = "This is a secret source value" Expect(os.Setenv(validSecretSourceEnv, "This is a secret source env")).To(Succeed()) tmp, err := os.CreateTemp("", "oauth2-proxy-secret-source-test") Expect(err).ToNot(HaveOccurred()) diff --git a/pkg/validation/header.go b/pkg/validation/header.go index b1258144..713113f4 100644 --- a/pkg/validation/header.go +++ b/pkg/validation/header.go @@ -51,11 +51,9 @@ func validateHeaderValue(_ string, value options.HeaderValue) []string { func validateHeaderValueClaimSource(claim options.ClaimSource) []string { msgs := []string{} - if claim.Claim == "" { msgs = append(msgs, "claim should not be empty") } - if claim.BasicAuthPassword != nil { msgs = append(msgs, prefixValues("invalid basicAuthPassword: ", validateSecretSource(*claim.BasicAuthPassword))...) } diff --git a/pkg/validation/header_test.go b/pkg/validation/header_test.go index 2d9ef6dd..88849ea1 100644 --- a/pkg/validation/header_test.go +++ b/pkg/validation/header_test.go @@ -30,7 +30,7 @@ var _ = Describe("Headers", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))), + Value: base64.StdEncoding.EncodeToString([]byte("secret")), }, }, }, @@ -43,7 +43,7 @@ var _ = Describe("Headers", func() { ClaimSource: &options.ClaimSource{ Claim: "email", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))), + Value: base64.StdEncoding.EncodeToString([]byte("secret")), }, }, }, diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index bafed628..52facb4d 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -69,7 +69,7 @@ func validateStaticUpstream(upstream options.Upstream) []string { if upstream.InsecureSkipTLSVerify { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.FlushInterval != nil && upstream.FlushInterval.Duration() != options.DefaultUpstreamFlushInterval { + if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } if upstream.PassHostHeader != nil { diff --git a/pkg/validation/upstreams_test.go b/pkg/validation/upstreams_test.go index fe431d27..67991b76 100644 --- a/pkg/validation/upstreams_test.go +++ b/pkg/validation/upstreams_test.go @@ -14,7 +14,7 @@ var _ = Describe("Upstreams", func() { errStrings []string } - flushInterval := options.Duration(5 * time.Second) + flushInterval := 5 * time.Second staticCode200 := 200 truth := true From 676f56a35e135ef304e6cff6886e59cd2151baa0 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 1 Feb 2025 15:57:23 +0100 Subject: [PATCH 112/130] apply review suggestions Signed-off-by: Jan Larwig --- main.go | 2 +- pkg/apis/options/load.go | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index d9fc406b..2a09b3ce 100644 --- a/main.go +++ b/main.go @@ -70,7 +70,7 @@ func main() { func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { opts, err := loadLegacyOptions(config, extraFlags, args) if err != nil { - return nil, err + return nil, fmt.Errorf("couldn't load legacy options: %w", err) } if yamlConfig != "" { diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 22e775a8..878199ed 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -83,12 +83,11 @@ func Decode(input interface{}, result interface{}) error { DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), Metadata: nil, // Don't track any metadata Result: result, // Decode the result into the prefilled options - TagName: "json", // Parse all fields that use the yaml tag + TagName: "json", // Parse all fields that use the json tag ZeroFields: false, // Don't clean the default values from the result map (options) ErrorUnused: true, // Throw an error if keys have been used that aren't mapped to any struct fields - IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with yaml + IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with json }) - if err != nil { return fmt.Errorf("error creating decoder for config: %w", err) } From 6720d8da608774fdc6c435f91dd9564af4ee5ba9 Mon Sep 17 00:00:00 2001 From: tuunit Date: Sun, 9 Feb 2025 16:44:07 +0100 Subject: [PATCH 113/130] add duration test Signed-off-by: Jan Larwig --- pkg/apis/options/common_test.go | 87 ------------------------------- pkg/apis/options/duration_test.go | 82 +++++++++++++++++++++++++++++ pkg/apis/options/load.go | 17 ++++-- 3 files changed, 95 insertions(+), 91 deletions(-) delete mode 100644 pkg/apis/options/common_test.go create mode 100644 pkg/apis/options/duration_test.go diff --git a/pkg/apis/options/common_test.go b/pkg/apis/options/common_test.go deleted file mode 100644 index db33a58b..00000000 --- a/pkg/apis/options/common_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package options - -import ( - "encoding/json" - "errors" - "time" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -var _ = Describe("Common", func() { - Context("Duration", func() { - type marshalJSONTableInput struct { - duration Duration - expectedJSON string - } - - DescribeTable("MarshalJSON", - func(in marshalJSONTableInput) { - data, err := in.duration.MarshalJSON() - Expect(err).ToNot(HaveOccurred()) - Expect(string(data)).To(Equal(in.expectedJSON)) - - var d Duration - Expect(json.Unmarshal(data, &d)).To(Succeed()) - Expect(d).To(Equal(in.duration)) - }, - Entry("30 seconds", marshalJSONTableInput{ - duration: Duration(30 * time.Second), - expectedJSON: "\"30s\"", - }), - Entry("1 minute", marshalJSONTableInput{ - duration: Duration(1 * time.Minute), - expectedJSON: "\"1m0s\"", - }), - Entry("1 hour 15 minutes", marshalJSONTableInput{ - duration: Duration(75 * time.Minute), - expectedJSON: "\"1h15m0s\"", - }), - Entry("A zero Duration", marshalJSONTableInput{ - duration: Duration(0), - expectedJSON: "\"0s\"", - }), - ) - - type unmarshalJSONTableInput struct { - json string - expectedErr error - expectedDuration Duration - } - - DescribeTable("UnmarshalJSON", - func(in unmarshalJSONTableInput) { - // A duration must be initialised pointer before UnmarshalJSON will work. - zero := Duration(0) - d := &zero - - err := d.UnmarshalJSON([]byte(in.json)) - if in.expectedErr != nil { - Expect(err).To(MatchError(in.expectedErr.Error())) - } else { - Expect(err).ToNot(HaveOccurred()) - } - Expect(d).ToNot(BeNil()) - Expect(*d).To(Equal(in.expectedDuration)) - }, - Entry("1m", unmarshalJSONTableInput{ - json: "\"1m\"", - expectedDuration: Duration(1 * time.Minute), - }), - Entry("30s", unmarshalJSONTableInput{ - json: "\"30s\"", - expectedDuration: Duration(30 * time.Second), - }), - Entry("1h15m", unmarshalJSONTableInput{ - json: "\"1h15m\"", - expectedDuration: Duration(75 * time.Minute), - }), - Entry("am", unmarshalJSONTableInput{ - json: "\"am\"", - expectedErr: errors.New("time: invalid duration \"am\""), - expectedDuration: Duration(0), - }), - ) - }) -}) diff --git a/pkg/apis/options/duration_test.go b/pkg/apis/options/duration_test.go new file mode 100644 index 00000000..fc1e77e3 --- /dev/null +++ b/pkg/apis/options/duration_test.go @@ -0,0 +1,82 @@ +package options + +import ( + "testing" + "time" +) + +func TestDecode(t *testing.T) { + type result struct { + Duration time.Duration `json:"duration"` + } + + tests := []struct { + name string + input map[string]interface{} + out result + expected time.Duration + expectedErr bool + }{ + { + name: "Valid String Duration with single unit", + input: map[string]interface{}{"duration": "3s"}, + out: result{}, + expected: 3 * time.Second, + expectedErr: false, + }, + { + name: "Valid String Duration with multiple units", + input: map[string]interface{}{"duration": "1h20m30s"}, + out: result{}, + expected: 1*time.Hour + 20*time.Minute + 30*time.Second, + expectedErr: false, + }, + { + name: "Valid Float Duration", + input: map[string]interface{}{"duration": 2.5}, + out: result{}, + expected: 2500 * time.Millisecond, + expectedErr: false, + }, + { + name: "Valid Int64 Duration", + input: map[string]interface{}{"duration": int64(5000000000)}, + out: result{}, + expected: 5 * time.Second, + expectedErr: false, + }, + { + name: "Invalid String", + input: map[string]interface{}{"duration": "invalid"}, + out: result{}, + expected: 0, + expectedErr: true, + }, + { + name: "Unsupported Type", + input: map[string]interface{}{"duration": true}, + out: result{}, + expected: 0, + expectedErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var result struct { + Duration time.Duration `json:"duration"` + } + + err := Decode(tt.input, &result) + if (err != nil) != tt.expectedErr { + t.Errorf("expected error: %v, got: %v", tt.expectedErr, err) + } + + if !tt.expectedErr { + if result.Duration != tt.expected { + t.Errorf("expected: %v, got: %v", tt.expected, result.Duration) + } + } + }) + } +} diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 878199ed..2905af5f 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -69,16 +69,25 @@ func LoadYAML(configFileName string, opts interface{}) error { return fmt.Errorf("error unmarshalling config: %w", err) } - return Decode(intermediate, opts) -} - -func Decode(input interface{}, result interface{}) error { // Using mapstructure to decode arbitrary yaml structure into options and // merge with existing values instead of overwriting everything. This is especially // important as we have a lot of default values for boolean which are supposed to be // true by default. Normally by just parsing through yaml all booleans that aren't // referenced in the config file would be parsed as false and we cannot identify after // the fact if they have been explicitly set to false or have not been referenced. + return Decode(intermediate, opts) +} + +// Decode processes an input map and decodes it into a given struct while preserving default values. +// It ensures proper conversion of duration values from strings, floats, and int64 into time.Duration. +// +// Parameters: +// - input: A map[string]interface{} representing the input data. +// - result: A pointer to a struct where the decoded values will be stored. +// +// Returns: +// - An error if decoding fails or if there are unmapped keys. +func Decode(input interface{}, result interface{}) error { decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), Metadata: nil, // Don't track any metadata From c186d40675ac706cd286106b969998063e2c8fd4 Mon Sep 17 00:00:00 2001 From: tuunit Date: Sun, 9 Feb 2025 17:23:03 +0100 Subject: [PATCH 114/130] use official upstream yaml library v3 Signed-off-by: Jan Larwig --- docs/docs/configuration/alpha_config.md | 214 +++++++++++------------ go.mod | 15 +- go.sum | 31 ++-- main.go | 2 +- main_test.go | 4 +- pkg/apis/options/alpha_options.go | 12 +- pkg/apis/options/duration_test.go | 4 +- pkg/apis/options/header.go | 16 +- pkg/apis/options/load.go | 4 +- pkg/apis/options/load_test.go | 10 +- pkg/apis/options/login_url_parameters.go | 10 +- pkg/apis/options/providers.go | 136 +++++++------- pkg/apis/options/secret_source.go | 6 +- pkg/apis/options/server.go | 14 +- pkg/apis/options/upstreams.go | 28 +-- pkg/requests/result_test.go | 4 +- 16 files changed, 250 insertions(+), 260 deletions(-) diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 67b3fe1b..54dfb9f1 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -148,7 +148,7 @@ You must remove these options before starting OAuth2 Proxy with `--alpha-config` | Field | Type | Description | | ----- | ---- | ----------- | -| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | +| `SkipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | ### AlphaOptions @@ -163,12 +163,12 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | -| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | -| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | -| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | +| `UpstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `InjectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `InjectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `Server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `MetricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `Providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | ### AzureOptions @@ -178,8 +178,8 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | -| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | +| `Tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `GraphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | ### BitbucketOptions @@ -189,8 +189,8 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `team` | _string_ | Team sets restrict logins to members of this team | -| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | +| `Team` | _string_ | Team sets restrict logins to members of this team | +| `Repository` | _string_ | Repository sets restrict logins to user with access to this repository | ### ClaimSource @@ -200,9 +200,9 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | -| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | -| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | +| `Claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `Prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `BasicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | ### GitHubOptions @@ -212,11 +212,11 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `org` | _string_ | Org sets restrict logins to members of this organisation | -| `team` | _string_ | Team sets restrict logins to members of this team | -| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | -| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | -| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | +| `Org` | _string_ | Org sets restrict logins to members of this organisation | +| `Team` | _string_ | Team sets restrict logins to members of this team | +| `Repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `Token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `Users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | ### GitLabOptions @@ -226,8 +226,8 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `group` | _[]string_ | Group sets restrict logins to members of this group | -| `projects` | _[]string_ | Projects restricts logins to members of these projects | +| `Group` | _[]string_ | Group sets restrict logins to members of this group | +| `Projects` | _[]string_ | Projects restricts logins to members of these projects | ### GoogleOptions @@ -237,13 +237,13 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | -| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | -| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | -| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | -| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | -| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | -| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | +| `Groups` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `AdminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `ServiceAccountJSON` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `UseApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `TargetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `UseOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `AdminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | ### Header @@ -254,10 +254,10 @@ response header. | Field | Type | Description | | ----- | ---- | ----------- | -| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | -| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `Name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `PreserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | | `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | -| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | +| `Values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | ### HeaderValue @@ -268,12 +268,12 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | Value expects a base64 encoded string value. | -| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | -| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | -| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | -| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | -| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | +| `Value` | _string_ | Value expects a base64 encoded string value. | +| `FromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `FromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `Claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `Prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `BasicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | ### KeycloakOptions @@ -283,8 +283,8 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | -| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | +| `Groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `Roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | ### LoginGovOptions @@ -294,9 +294,9 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | -| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | -| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | +| `JWTKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `JWTKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `PubJWKURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | ### LoginURLParameter @@ -374,9 +374,9 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `name` | _string_ | Name specifies the name of the query parameter. | -| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | -| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | +| `Name` | _string_ | Name specifies the name of the query parameter. | +| `Default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `Allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | ### MicrosoftEntraIDOptions @@ -386,8 +386,8 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | -| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | +| `AllowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `FederatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | ### OIDCOptions @@ -397,18 +397,18 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | -| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | -| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | -| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | -| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | -| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | -| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | -| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | -| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | -| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | -| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | -| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | +| `IssuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `InsecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `InsecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `InsecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `SkipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `JwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `PublicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `EmailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `GroupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `UserIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `AudienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `ExtraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | ### Provider @@ -418,36 +418,36 @@ Provider holds all configuration for a single provider | Field | Type | Description | | ----- | ---- | ----------- | -| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | -| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | -| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | -| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | -| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | -| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ClientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `ClientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `ClientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `KeycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `AzureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `MicrosoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | | `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | -| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | -| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | -| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | -| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | -| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | -| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | -| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | -| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | -| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | -| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | -| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | -| `loginURL` | _string_ | LoginURL is the authentication endpoint | -| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | -| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | -| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | -| `profileURL` | _string_ | ProfileURL is the profile access endpoint | -| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | -| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | -| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | -| `scope` | _string_ | Scope is the OAuth scope specification | -| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | -| `code_challenge_method` | _string_ | The code challenge method | -| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | +| `BitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `GitHubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `GitLabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `GoogleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `OIDCConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `LoginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `ID` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `Type` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `Name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `CAFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `UseSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `LoginURL` | _string_ | LoginURL is the authentication endpoint | +| `LoginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `AuthRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `RedeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `ProfileURL` | _string_ | ProfileURL is the profile access endpoint | +| `SkipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `ProtectedResource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `ValidateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `Scope` | _string_ | Scope is the OAuth scope specification | +| `AllowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `CodeChallengeMethod` | _string_ | The code challenge method | +| `BackendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | ### ProviderType #### (`string` alias) @@ -480,9 +480,9 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | Value expects a base64 encoded string value. | -| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | -| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `Value` | _string_ | Value expects a base64 encoded string value. | +| `FromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `FromFile` | _string_ | FromFile expects a path to a file containing the secret value. | ### Server @@ -521,8 +521,8 @@ login URL. Either Value or Pattern should be supplied, not both. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | A Value rule matches just this specific value | -| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | +| `Value` | _string_ | A Value rule matches just this specific value | +| `Pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | ### Upstream @@ -533,18 +533,18 @@ Requests will be proxied to this upstream if the path matches the request path. | Field | Type | Description | | ----- | ---- | ----------- | -| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | -| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | -| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | -| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | -| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | -| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | -| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | -| `flushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | -| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | -| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | -| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | -| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | +| `ID` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `Path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `RewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `URI` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `InsecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `Static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `StaticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `FlushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `PassHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `ProxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `Timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `DisableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | ### UpstreamConfig @@ -554,5 +554,5 @@ UpstreamConfig is a collection of definitions for upstream servers. | Field | Type | Description | | ----- | ---- | ----------- | -| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | -| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | +| `ProxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `Upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/go.mod b/go.mod index 69ffc5fb..9e353b0a 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,6 @@ require ( github.com/coreos/go-oidc/v3 v3.14.1 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 - github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/go-jose/go-jose/v3 v3.0.4 github.com/go-viper/mapstructure/v2 v2.4.0 github.com/golang-jwt/jwt/v5 v5.2.3 @@ -20,9 +19,10 @@ require ( github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 + github.com/mitchellh/mapstructure v1.5.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 github.com/onsi/ginkgo/v2 v2.23.4 - github.com/onsi/gomega v1.37.0 + github.com/onsi/gomega v1.38.0 github.com/pierrec/lz4/v4 v4.1.22 github.com/prometheus/client_golang v1.22.0 github.com/redis/go-redis/v9 v9.11.0 @@ -35,13 +35,14 @@ require ( golang.org/x/net v0.42.0 golang.org/x/oauth2 v0.30.0 golang.org/x/sync v0.16.0 - google.golang.org/api v0.242.0 + google.golang.org/api v0.243.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 + gopkg.in/yaml.v3 v3.0.1 k8s.io/apimachinery v0.33.3 ) require ( - cloud.google.com/go/auth v0.16.2 // indirect + cloud.google.com/go/auth v0.16.3 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect @@ -80,9 +81,7 @@ require ( golang.org/x/sys v0.34.0 // indirect golang.org/x/text v0.27.0 // indirect golang.org/x/tools v0.35.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 // indirect - google.golang.org/grpc v1.73.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074 // indirect + google.golang.org/grpc v1.74.2 // indirect google.golang.org/protobuf v1.36.6 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 863da770..34aca12f 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -cloud.google.com/go/auth v0.16.2 h1:QvBAGFPLrDeoiNjyfVunhQ10HKNYuOwZ5noee0M5df4= -cloud.google.com/go/auth v0.16.2/go.mod h1:sRBas2Y1fB1vZTdurouM0AzuYQBMZinrUYL8EufhtEA= +cloud.google.com/go/auth v0.16.3 h1:kabzoQ9/bobUmnseYnBO6qQG7q4a/CffFRlJSxv2wCc= +cloud.google.com/go/auth v0.16.3/go.mod h1:NucRGjaXfzP1ltpcQ7On/VTZ0H4kWB5Jy+Y9Dnm76fA= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU= @@ -44,8 +44,6 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4= -github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI= @@ -93,16 +91,16 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= -github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa h1:hI1uC2A3vJFjwvBn0G0a7QBRdBUp6Y048BtLAHRTKPo= -github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa/go.mod h1:8vxFeeg++MqgCHwehSuwTlYCF0ALyDJbYJ1JsKi7v6s= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus= github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8= -github.com/onsi/gomega v1.37.0 h1:CdEG8g0S133B4OswTDC/5XPSzE1OeP29QOioj2PID2Y= -github.com/onsi/gomega v1.37.0/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= +github.com/onsi/gomega v1.38.0 h1:c/WX+w8SLAinvuKKQFh77WEucCnPk4j2OTUr7lt7BeY= +github.com/onsi/gomega v1.38.0/go.mod h1:OcXcwId0b9QsE7Y49u+BTrL4IdKOBOKnD6VQNTJEB6o= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= @@ -138,8 +136,6 @@ github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= @@ -227,16 +223,16 @@ golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.242.0 h1:7Lnb1nfnpvbkCiZek6IXKdJ0MFuAZNAJKQfA1ws62xg= -google.golang.org/api v0.242.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= +google.golang.org/api v0.243.0 h1:sw+ESIJ4BVnlJcWu9S+p2Z6Qq1PjG77T8IJ1xtp4jZQ= +google.golang.org/api v0.243.0/go.mod h1:GE4QtYfaybx1KmeHMdBnNnyLzBZCVihGBXAmJu/uUr8= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822/go.mod h1:h3c4v36UTKzUiuaOKQ6gr3S+0hovBtUrXzTG/i3+XEc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 h1:pFyd6EwwL2TqFf8emdthzeX+gZE1ElRq3iM8pui4KBY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= -google.golang.org/grpc v1.73.0 h1:VIWSmpI2MegBtTuFt5/JWy2oXxtjJ/e89Z70ImfD2ok= -google.golang.org/grpc v1.73.0/go.mod h1:50sbHOUqWoCQGI8V2HQLJM0B+LMlIUjNSZmow7EVBQc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074 h1:qJW29YvkiJmXOYMu5Tf8lyrTp3dOS+K4z6IixtLaCf8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/grpc v1.74.2 h1:WoosgB65DlWVC9FqI82dGsZhWFNBSLjQ84bjROOpMu4= +google.golang.org/grpc v1.74.2/go.mod h1:CtQ+BGjaAIXHs/5YS3i473GqwBBa1zGQNevxdeBEXrM= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -244,9 +240,6 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 2a09b3ce..a9def2f6 100644 --- a/main.go +++ b/main.go @@ -5,12 +5,12 @@ import ( "os" "runtime" - "github.com/ghodss/yaml" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version" "github.com/spf13/pflag" + "gopkg.in/yaml.v3" ) func main() { diff --git a/main_test.go b/main_test.go index a6ea83c2..7de1ac72 100644 --- a/main_test.go +++ b/main_test.go @@ -2,9 +2,7 @@ package main import ( "errors" - "fmt" "os" - "strings" "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" @@ -256,7 +254,7 @@ redirect_url="http://localhost:4180/oauth2/callback" configContent: testCoreConfig, alphaConfigContent: testAlphaConfig + ":", expectedOptions: func() *options.Options { return nil }, - expectedErr: fmt.Errorf("failed to load alpha options: error unmarshalling config: error converting YAML to JSON: yaml: line %d: did not find expected key", strings.Count(testAlphaConfig, "\n")), + expectedErr: errors.New("failed to load alpha options: error unmarshalling config: yaml: line 1: did not find expected key"), }), Entry("with alpha configuration and bad core configuration", loadConfigurationTableInput{ configContent: testCoreConfig + "unknown_field=\"something\"", diff --git a/pkg/apis/options/alpha_options.go b/pkg/apis/options/alpha_options.go index 278db401..0c78359a 100644 --- a/pkg/apis/options/alpha_options.go +++ b/pkg/apis/options/alpha_options.go @@ -12,13 +12,13 @@ type AlphaOptions struct { // UpstreamConfig is used to configure upstream servers. // Once a user is authenticated, requests to the server will be proxied to // these upstream servers based on the path mappings defined in this list. - UpstreamConfig UpstreamConfig `json:"upstreamConfig,omitempty"` + UpstreamConfig UpstreamConfig `yaml:"upstreamConfig,omitempty"` // InjectRequestHeaders is used to configure headers that should be added // to requests to upstream servers. // Headers may source values from either the authenticated user's session // or from a static secret value. - InjectRequestHeaders []Header `json:"injectRequestHeaders,omitempty"` + InjectRequestHeaders []Header `yaml:"injectRequestHeaders,omitempty"` // InjectResponseHeaders is used to configure headers that should be added // to responses from the proxy. @@ -27,24 +27,24 @@ type AlphaOptions struct { // auth_request module. // Headers may source values from either the authenticated user's session // or from a static secret value. - InjectResponseHeaders []Header `json:"injectResponseHeaders,omitempty"` + InjectResponseHeaders []Header `yaml:"injectResponseHeaders,omitempty"` // Server is used to configure the HTTP(S) server for the proxy application. // You may choose to run both HTTP and HTTPS servers simultaneously. // This can be done by setting the BindAddress and the SecureBindAddress simultaneously. // To use the secure server you must configure a TLS certificate and key. - Server Server `json:"server,omitempty"` + Server Server `yaml:"server,omitempty"` // MetricsServer is used to configure the HTTP(S) server for metrics. // You may choose to run both HTTP and HTTPS servers simultaneously. // This can be done by setting the BindAddress and the SecureBindAddress simultaneously. // To use the secure server you must configure a TLS certificate and key. - MetricsServer Server `json:"metricsServer,omitempty"` + MetricsServer Server `yaml:"metricsServer,omitempty"` // Providers is used to configure your provider. **Multiple-providers is not // yet working.** [This feature is tracked in // #925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) - Providers Providers `json:"providers,omitempty"` + Providers Providers `yaml:"providers,omitempty"` } // Initialize alpha options with default values and settings of the core options diff --git a/pkg/apis/options/duration_test.go b/pkg/apis/options/duration_test.go index fc1e77e3..63f203a8 100644 --- a/pkg/apis/options/duration_test.go +++ b/pkg/apis/options/duration_test.go @@ -7,7 +7,7 @@ import ( func TestDecode(t *testing.T) { type result struct { - Duration time.Duration `json:"duration"` + Duration time.Duration `yaml:"duration"` } tests := []struct { @@ -64,7 +64,7 @@ func TestDecode(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var result struct { - Duration time.Duration `json:"duration"` + Duration time.Duration `yaml:"duration"` } err := Decode(tt.input, &result) diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 164f9fee..ab391677 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -5,13 +5,13 @@ package options type Header struct { // Name is the header name to be used for this set of values. // Names should be unique within a list of Headers. - Name string `json:"name,omitempty"` + Name string `yaml:"name,omitempty"` // PreserveRequestValue determines whether any values for this header // should be preserved for the request to the upstream server. // This option only applies to injected request headers. // Defaults to false (headers that match this header will be stripped). - PreserveRequestValue bool `json:"preserveRequestValue,omitempty"` + PreserveRequestValue bool `yaml:"preserveRequestValue,omitempty"` // InsecureSkipHeaderNormalization disables normalizing the header name // According to RFC 7230 Section 3.2 there aren't any rules about @@ -24,17 +24,17 @@ type Header struct { InsecureSkipHeaderNormalization bool `json:"InsecureSkipHeaderNormalization,omitempty"` // Values contains the desired values for this header - Values []HeaderValue `json:"values,omitempty"` + Values []HeaderValue `yaml:"values,omitempty"` } // HeaderValue represents a single header value and the sources that can // make up the header value type HeaderValue struct { // Allow users to load the value from a secret source - *SecretSource `json:"secretSource,omitempty"` + *SecretSource `yaml:"secretSource,omitempty"` // Allow users to load the value from a session claim - *ClaimSource `json:"claimSource,omitempty"` + *ClaimSource `yaml:"claimSource,omitempty"` } // ClaimSource allows loading a header value from a claim within the session @@ -42,14 +42,14 @@ type ClaimSource struct { // Claim is the name of the claim in the session that the value should be // loaded from. Available claims: `access_token` `id_token` `created_at` // `expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. - Claim string `json:"claim,omitempty"` + Claim string `yaml:"claim,omitempty"` // Prefix is an optional prefix that will be prepended to the value of the // claim if it is non-empty. - Prefix string `json:"prefix,omitempty"` + Prefix string `yaml:"prefix,omitempty"` // BasicAuthPassword converts this claim into a basic auth header. // Note the value of claim will become the basic auth username and the // basicAuthPassword will be used as the password value. - BasicAuthPassword *SecretSource `json:"basicAuthPassword,omitempty"` + BasicAuthPassword *SecretSource `yaml:"basicAuthPassword,omitempty"` } diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 2905af5f..af7f76d9 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -9,10 +9,10 @@ import ( "strings" "github.com/a8m/envsubst" - "github.com/ghodss/yaml" "github.com/go-viper/mapstructure/v2" "github.com/spf13/pflag" "github.com/spf13/viper" + "gopkg.in/yaml.v3" ) // Load reads in the config file at the path given, then merges in environment @@ -92,7 +92,7 @@ func Decode(input interface{}, result interface{}) error { DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), Metadata: nil, // Don't track any metadata Result: result, // Decode the result into the prefilled options - TagName: "json", // Parse all fields that use the json tag + TagName: "yaml", // Parse all fields that use the json tag ZeroFields: false, // Don't clean the default values from the result map (options) ErrorUnused: true, // Throw an error if keys have been used that aren't mapped to any struct fields IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with json diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 6f327a22..a0079267 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -355,15 +355,15 @@ var _ = Describe("Load", func() { var _ = Describe("LoadYAML", func() { Context("with a testOptions structure", func() { type TestOptionSubStruct struct { - StringSliceOption []string `json:"stringSliceOption,omitempty"` + StringSliceOption []string `yaml:"stringSliceOption,omitempty"` } type TestOptions struct { - StringOption string `json:"stringOption,omitempty"` - Sub TestOptionSubStruct `json:"sub,omitempty"` + StringOption string `yaml:"stringOption,omitempty"` + Sub TestOptionSubStruct `yaml:"sub,omitempty"` // Check that embedded fields can be unmarshalled - TestOptionSubStruct `json:",inline,squash"` + TestOptionSubStruct `yaml:",inline,squash"` } var testOptionsConfigBytesFull = []byte(` @@ -445,7 +445,7 @@ sub: configFile: []byte("\tfoo: bar"), input: &TestOptions{}, expectedOutput: &TestOptions{}, - expectedErr: errors.New("error unmarshalling config: error converting YAML to JSON: yaml: found character that cannot start any token"), + expectedErr: errors.New("error unmarshalling config: yaml: found character that cannot start any token"), }), Entry("with extra fields in the YAML", loadYAMLTableInput{ configFile: append(testOptionsConfigBytesFull, []byte("foo: bar\n")...), diff --git a/pkg/apis/options/login_url_parameters.go b/pkg/apis/options/login_url_parameters.go index 1cb763b9..02729760 100644 --- a/pkg/apis/options/login_url_parameters.go +++ b/pkg/apis/options/login_url_parameters.go @@ -71,19 +71,19 @@ package options // character. type LoginURLParameter struct { // Name specifies the name of the query parameter. - Name string `json:"name"` + Name string `yaml:"name"` // Default specifies a default value or values that will be // passed to the IdP if not overridden. //+optional - Default []string `json:"default,omitempty"` + Default []string `yaml:"default,omitempty"` // Allow specifies rules about how the default (if any) may be // overridden via the query string to `/oauth2/start`. Only // values that match one or more of the allow rules will be // forwarded to the IdP. //+optional - Allow []URLParameterRule `json:"allow,omitempty"` + Allow []URLParameterRule `yaml:"allow,omitempty"` } // URLParameterRule represents a rule by which query parameters @@ -92,11 +92,11 @@ type LoginURLParameter struct { // login URL. Either Value or Pattern should be supplied, not both. type URLParameterRule struct { // A Value rule matches just this specific value - Value *string `json:"value,omitempty"` + Value *string `yaml:"value,omitempty"` // A Pattern rule gives a regular expression that must be matched by // some substring of the value. The expression is _not_ automatically // anchored to the start and end of the value, if you _want_ to restrict // the whole parameter value you must anchor it yourself with `^` and `$`. - Pattern *string `json:"pattern,omitempty"` + Pattern *string `yaml:"pattern,omitempty"` } diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index c876f46b..0a0796e9 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -22,78 +22,78 @@ type Providers []Provider type Provider struct { // ClientID is the OAuth Client ID that is defined in the provider // This value is required for all providers. - ClientID string `json:"clientID,omitempty"` + ClientID string `yaml:"clientID,omitempty"` // ClientSecret is the OAuth Client Secret that is defined in the provider // This value is required for all providers. - ClientSecret string `json:"clientSecret,omitempty"` + ClientSecret string `yaml:"clientSecret,omitempty"` // ClientSecretFile is the name of the file // containing the OAuth Client Secret, it will be used if ClientSecret is not set. - ClientSecretFile string `json:"clientSecretFile,omitempty"` + ClientSecretFile string `yaml:"clientSecretFile,omitempty"` // KeycloakConfig holds all configurations for Keycloak provider. - KeycloakConfig KeycloakOptions `json:"keycloakConfig,omitempty"` + KeycloakConfig KeycloakOptions `yaml:"keycloakConfig,omitempty"` // AzureConfig holds all configurations for Azure provider. - AzureConfig AzureOptions `json:"azureConfig,omitempty"` + AzureConfig AzureOptions `yaml:"azureConfig,omitempty"` // MicrosoftEntraIDConfig holds all configurations for Entra ID provider. - MicrosoftEntraIDConfig MicrosoftEntraIDOptions `json:"microsoftEntraIDConfig,omitempty"` + MicrosoftEntraIDConfig MicrosoftEntraIDOptions `yaml:"microsoftEntraIDConfig,omitempty"` // ADFSConfig holds all configurations for ADFS provider. - ADFSConfig ADFSOptions `json:"ADFSConfig,omitempty"` + ADFSConfig ADFSOptions `yaml:"ADFSConfig,omitempty"` // BitbucketConfig holds all configurations for Bitbucket provider. - BitbucketConfig BitbucketOptions `json:"bitbucketConfig,omitempty"` + BitbucketConfig BitbucketOptions `yaml:"bitbucketConfig,omitempty"` // GitHubConfig holds all configurations for GitHubC provider. - GitHubConfig GitHubOptions `json:"githubConfig,omitempty"` + GitHubConfig GitHubOptions `yaml:"githubConfig,omitempty"` // GitLabConfig holds all configurations for GitLab provider. - GitLabConfig GitLabOptions `json:"gitlabConfig,omitempty"` + GitLabConfig GitLabOptions `yaml:"gitlabConfig,omitempty"` // GoogleConfig holds all configurations for Google provider. - GoogleConfig GoogleOptions `json:"googleConfig,omitempty"` + GoogleConfig GoogleOptions `yaml:"googleConfig,omitempty"` // OIDCConfig holds all configurations for OIDC provider // or providers utilize OIDC configurations. - OIDCConfig OIDCOptions `json:"oidcConfig,omitempty"` + OIDCConfig OIDCOptions `yaml:"oidcConfig,omitempty"` // LoginGovConfig holds all configurations for LoginGov provider. - LoginGovConfig LoginGovOptions `json:"loginGovConfig,omitempty"` + LoginGovConfig LoginGovOptions `yaml:"loginGovConfig,omitempty"` // ID should be a unique identifier for the provider. // This value is required for all providers. - ID string `json:"id,omitempty"` + ID string `yaml:"id,omitempty"` // Type is the OAuth provider // must be set from the supported providers group, // otherwise 'Google' is set as default - Type ProviderType `json:"provider,omitempty"` + Type ProviderType `yaml:"provider,omitempty"` // Name is the providers display name // if set, it will be shown to the users in the login page. - Name string `json:"name,omitempty"` + Name string `yaml:"name,omitempty"` // CAFiles is a list of paths to CA certificates that should be used when connecting to the provider. // If not specified, the default Go trust sources are used instead - CAFiles []string `json:"caFiles,omitempty"` + CAFiles []string `yaml:"caFiles,omitempty"` // UseSystemTrustStore determines if your custom CA files and the system trust store are used // If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. - UseSystemTrustStore bool `json:"useSystemTrustStore,omitempty"` + UseSystemTrustStore bool `yaml:"useSystemTrustStore,omitempty"` // LoginURL is the authentication endpoint - LoginURL string `json:"loginURL,omitempty"` + LoginURL string `yaml:"loginURL,omitempty"` // LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL - LoginURLParameters []LoginURLParameter `json:"loginURLParameters,omitempty"` + LoginURLParameters []LoginURLParameter `yaml:"loginURLParameters,omitempty"` // AuthRequestResponseMode defines the response mode to request during authorization request - AuthRequestResponseMode string `json:"authRequestResponseMode,omitempty"` + AuthRequestResponseMode string `yaml:"authRequestResponseMode,omitempty"` // RedeemURL is the token redemption endpoint - RedeemURL string `json:"redeemURL,omitempty"` + RedeemURL string `yaml:"redeemURL,omitempty"` // ProfileURL is the profile access endpoint - ProfileURL string `json:"profileURL,omitempty"` + ProfileURL string `yaml:"profileURL,omitempty"` // SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token // default set to 'false' - SkipClaimsFromProfileURL bool `json:"skipClaimsFromProfileURL,omitempty"` + SkipClaimsFromProfileURL bool `yaml:"skipClaimsFromProfileURL,omitempty"` // ProtectedResource is the resource that is protected (Azure AD and ADFS only) - ProtectedResource string `json:"resource,omitempty"` + ProtectedResource string `yaml:"resource,omitempty"` // ValidateURL is the access token validation endpoint - ValidateURL string `json:"validateURL,omitempty"` + ValidateURL string `yaml:"validateURL,omitempty"` // Scope is the OAuth scope specification - Scope string `json:"scope,omitempty"` + Scope string `yaml:"scope,omitempty"` // AllowedGroups is a list of restrict logins to members of this group - AllowedGroups []string `json:"allowedGroups,omitempty"` + AllowedGroups []string `yaml:"allowedGroups,omitempty"` // The code challenge method - CodeChallengeMethod string `json:"code_challenge_method,omitempty"` + CodeChallengeMethod string `yaml:"code_challenge_method,omitempty"` // URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session - BackendLogoutURL string `json:"backendLogoutURL"` + BackendLogoutURL string `yaml:"backendLogoutURL"` } // ProviderType is used to enumerate the different provider type options @@ -157,19 +157,19 @@ const ( type KeycloakOptions struct { // Group enables to restrict login to members of indicated group - Groups []string `json:"groups,omitempty"` + Groups []string `yaml:"groups,omitempty"` // Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) - Roles []string `json:"roles,omitempty"` + Roles []string `yaml:"roles,omitempty"` } type AzureOptions struct { // Tenant directs to a tenant-specific or common (tenant-independent) endpoint // Default value is 'common' - Tenant string `json:"tenant,omitempty"` + Tenant string `yaml:"tenant,omitempty"` // GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph // Default value is 'id' - GraphGroupField string `json:"graphGroupField,omitempty"` + GraphGroupField string `yaml:"graphGroupField,omitempty"` } type MicrosoftEntraIDOptions struct { @@ -177,114 +177,114 @@ type MicrosoftEntraIDOptions struct { // issued by different issuers and OIDC issuer verification needs to be disabled. // When not specified, all tenants are allowed. Redundant for single-tenant apps // (regular ID token validation matches the issuer). - AllowedTenants []string `json:"allowedTenants,omitempty"` + AllowedTenants []string `yaml:"allowedTenants,omitempty"` // FederatedTokenAuth enable oAuth2 client authentication with federated token projected // by Entra Workload Identity plugin, instead of client secret. - FederatedTokenAuth bool `json:"federatedTokenAuth,omitempty"` + FederatedTokenAuth bool `yaml:"federatedTokenAuth,omitempty"` } type ADFSOptions struct { // Skip adding the scope parameter in login request // Default value is 'false' - SkipScope bool `json:"skipScope,omitempty"` + SkipScope bool `yaml:"skipScope,omitempty"` } type BitbucketOptions struct { // Team sets restrict logins to members of this team - Team string `json:"team,omitempty"` + Team string `yaml:"team,omitempty"` // Repository sets restrict logins to user with access to this repository - Repository string `json:"repository,omitempty"` + Repository string `yaml:"repository,omitempty"` } type GitHubOptions struct { // Org sets restrict logins to members of this organisation - Org string `json:"org,omitempty"` + Org string `yaml:"org,omitempty"` // Team sets restrict logins to members of this team - Team string `json:"team,omitempty"` + Team string `yaml:"team,omitempty"` // Repo sets restrict logins to collaborators of this repository - Repo string `json:"repo,omitempty"` + Repo string `yaml:"repo,omitempty"` // Token is the token to use when verifying repository collaborators // it must have push access to the repository - Token string `json:"token,omitempty"` + Token string `yaml:"token,omitempty"` // Users allows users with these usernames to login // even if they do not belong to the specified org and team or collaborators - Users []string `json:"users,omitempty"` + Users []string `yaml:"users,omitempty"` } type GitLabOptions struct { // Group sets restrict logins to members of this group - Group []string `json:"group,omitempty"` + Group []string `yaml:"group,omitempty"` // Projects restricts logins to members of these projects - Projects []string `json:"projects,omitempty"` + Projects []string `yaml:"projects,omitempty"` } type GoogleOptions struct { // Groups sets restrict logins to members of this Google group - Groups []string `json:"group,omitempty"` + Groups []string `yaml:"group,omitempty"` // AdminEmail is the Google admin to impersonate for api calls - AdminEmail string `json:"adminEmail,omitempty"` + AdminEmail string `yaml:"adminEmail,omitempty"` // ServiceAccountJSON is the path to the service account json credentials - ServiceAccountJSON string `json:"serviceAccountJson,omitempty"` + ServiceAccountJSON string `yaml:"serviceAccountJson,omitempty"` // UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON - UseApplicationDefaultCredentials bool `json:"useApplicationDefaultCredentials,omitempty"` + UseApplicationDefaultCredentials bool `yaml:"useApplicationDefaultCredentials,omitempty"` // TargetPrincipal is the Google Service Account used for Application Default Credentials - TargetPrincipal string `json:"targetPrincipal,omitempty"` + TargetPrincipal string `yaml:"targetPrincipal,omitempty"` // UseOrganizationId indicates whether to use the organization ID as the UserName claim - UseOrganizationID bool `json:"useOrganizationID,omitempty"` + UseOrganizationID bool `yaml:"useOrganizationID,omitempty"` // admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly - AdminAPIUserScope string `json:"adminAPIUserScope,omitempty"` + AdminAPIUserScope string `yaml:"adminAPIUserScope,omitempty"` } type OIDCOptions struct { // IssuerURL is the OpenID Connect issuer URL // eg: https://accounts.google.com - IssuerURL string `json:"issuerURL,omitempty"` + IssuerURL string `yaml:"issuerURL,omitempty"` // InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified // default set to 'false' - InsecureAllowUnverifiedEmail bool `json:"insecureAllowUnverifiedEmail"` + InsecureAllowUnverifiedEmail bool `yaml:"insecureAllowUnverifiedEmail"` // InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL // default set to 'false' - InsecureSkipIssuerVerification bool `json:"insecureSkipIssuerVerification"` + InsecureSkipIssuerVerification bool `yaml:"insecureSkipIssuerVerification"` // InsecureSkipNonce skips verifying the ID Token's nonce claim that must match // the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked // after the initial OAuth redeem & subsequent token refreshes. // default set to 'true' // Warning: In a future release, this will change to 'false' by default for enhanced security. - InsecureSkipNonce bool `json:"insecureSkipNonce"` + InsecureSkipNonce bool `yaml:"insecureSkipNonce"` // SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints // default set to 'false' - SkipDiscovery bool `json:"skipDiscovery,omitempty"` + SkipDiscovery bool `yaml:"skipDiscovery,omitempty"` // JwksURL is the OpenID Connect JWKS URL // eg: https://www.googleapis.com/oauth2/v3/certs - JwksURL string `json:"jwksURL,omitempty"` + JwksURL string `yaml:"jwksURL,omitempty"` // PublicKeyFiles is a list of paths pointing to public key files in PEM format to use // for verifying JWT tokens - PublicKeyFiles []string `json:"publicKeyFiles,omitempty"` + PublicKeyFiles []string `yaml:"publicKeyFiles,omitempty"` // EmailClaim indicates which claim contains the user email, // default set to 'email' - EmailClaim string `json:"emailClaim,omitempty"` + EmailClaim string `yaml:"emailClaim,omitempty"` // GroupsClaim indicates which claim contains the user groups // default set to 'groups' - GroupsClaim string `json:"groupsClaim,omitempty"` + GroupsClaim string `yaml:"groupsClaim,omitempty"` // UserIDClaim indicates which claim contains the user ID // default set to 'email' - UserIDClaim string `json:"userIDClaim,omitempty"` + UserIDClaim string `yaml:"userIDClaim,omitempty"` // AudienceClaim allows to define any claim that is verified against the client id // By default `aud` claim is used for verification. - AudienceClaims []string `json:"audienceClaims,omitempty"` + AudienceClaims []string `yaml:"audienceClaims,omitempty"` // ExtraAudiences is a list of additional audiences that are allowed // to pass verification in addition to the client id. - ExtraAudiences []string `json:"extraAudiences,omitempty"` + ExtraAudiences []string `yaml:"extraAudiences,omitempty"` } type LoginGovOptions struct { // JWTKey is a private key in PEM format used to sign JWT, - JWTKey string `json:"jwtKey,omitempty"` + JWTKey string `yaml:"jwtKey,omitempty"` // JWTKeyFile is a path to the private key file in PEM format used to sign the JWT - JWTKeyFile string `json:"jwtKeyFile,omitempty"` + JWTKeyFile string `yaml:"jwtKeyFile,omitempty"` // PubJWKURL is the JWK pubkey access endpoint - PubJWKURL string `json:"pubjwkURL,omitempty"` + PubJWKURL string `yaml:"pubjwkURL,omitempty"` } func providerDefaults() Providers { diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go index 2be4d890..9d82c605 100644 --- a/pkg/apis/options/secret_source.go +++ b/pkg/apis/options/secret_source.go @@ -4,11 +4,11 @@ package options // Only one source within the struct should be defined at any time. type SecretSource struct { // Value expects a base64 encoded string value. - Value string `json:"value,omitempty"` + Value string `yaml:"value,omitempty"` // FromEnv expects the name of an environment variable. - FromEnv string `json:"fromEnv,omitempty"` + FromEnv string `yaml:"fromEnv,omitempty"` // FromFile expects a path to a file containing the secret value. - FromFile string `json:"fromFile,omitempty"` + FromFile string `yaml:"fromFile,omitempty"` } diff --git a/pkg/apis/options/server.go b/pkg/apis/options/server.go index f423ef2c..8fa41af8 100644 --- a/pkg/apis/options/server.go +++ b/pkg/apis/options/server.go @@ -4,15 +4,15 @@ package options type Server struct { // BindAddress is the address on which to serve traffic. // Leave blank or set to "-" to disable. - BindAddress string + BindAddress string `yaml:"bindAddress,omitempty"` // SecureBindAddress is the address on which to serve secure traffic. // Leave blank or set to "-" to disable. - SecureBindAddress string + SecureBindAddress string `yaml:"secureBindAddress,omitempty"` // TLS contains the information for loading the certificate and key for the // secure traffic and further configuration for the TLS server. - TLS *TLS + TLS *TLS `yaml:"tls,omitempty"` } // TLS contains the information for loading a TLS certificate and key @@ -20,15 +20,15 @@ type Server struct { type TLS struct { // Key is the TLS key data to use. // Typically this will come from a file. - Key *SecretSource + Key *SecretSource `yaml:"key,omitempty"` // Cert is the TLS certificate data to use. // Typically this will come from a file. - Cert *SecretSource + Cert *SecretSource `yaml:"cert,omitempty"` // MinVersion is the minimal TLS version that is acceptable. // E.g. Set to "TLS1.3" to select TLS version 1.3 - MinVersion string + MinVersion string `yaml:"minVersion,omitempty"` // CipherSuites is a list of TLS cipher suites that are allowed. // E.g.: @@ -36,5 +36,5 @@ type TLS struct { // - TLS_RSA_WITH_AES_256_GCM_SHA384 // If not specified, the default Go safe cipher list is used. // List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). - CipherSuites []string + CipherSuites []string `yaml:"cipherSuites,omitempty"` } diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index 1002ae07..b32cc27d 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -14,11 +14,11 @@ const ( type UpstreamConfig struct { // ProxyRawPath will pass the raw url path to upstream allowing for urls // like: "/%2F/" which would otherwise be redirected to "/" - ProxyRawPath bool `json:"proxyRawPath,omitempty"` + ProxyRawPath bool `yaml:"proxyRawPath,omitempty"` // Upstreams represents the configuration for the upstream servers. // Requests will be proxied to this upstream if the path matches the request path. - Upstreams []Upstream `json:"upstreams,omitempty"` + Upstreams []Upstream `yaml:"upstreams,omitempty"` } // Upstream represents the configuration for an upstream server. @@ -26,7 +26,7 @@ type UpstreamConfig struct { type Upstream struct { // ID should be a unique identifier for the upstream. // This value is required for all upstreams. - ID string `json:"id,omitempty"` + ID string `yaml:"id,omitempty"` // Path is used to map requests to the upstream server. // The closest match will take precedence and all Paths must be unique. @@ -36,7 +36,7 @@ type Upstream struct { // - `^/foo$`: Match only the explicit path `/foo` // - `^/bar/$`: Match any path prefixed with `/bar/` // - `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget - Path string `json:"path,omitempty"` + Path string `yaml:"path,omitempty"` // RewriteTarget allows users to rewrite the request path before it is sent to // the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem @@ -46,7 +46,7 @@ type Upstream struct { // the request `/baz/abc/123` to `/foo/abc/123` before proxying to the // upstream server. Or if the upstream were `file:///app`, a request for // `/baz/info.html` would return the contents of the file `/app/foo/info.html`. - RewriteTarget string `json:"rewriteTarget,omitempty"` + RewriteTarget string `yaml:"rewriteTarget,omitempty"` // The URI of the upstream server. This may be an HTTP(S) server of a File // based URL. It may include a path, in which case all requests will be served @@ -58,43 +58,43 @@ type Upstream struct { // - file://host/path // If the URI's path is "/base" and the incoming request was for "/dir", // the upstream request will be for "/base/dir". - URI string `json:"uri,omitempty"` + URI string `yaml:"uri,omitempty"` // InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts. // This option is insecure and will allow potential Man-In-The-Middle attacks // between OAuth2 Proxy and the upstream server. // Defaults to false. - InsecureSkipTLSVerify bool `json:"insecureSkipTLSVerify,omitempty"` + InsecureSkipTLSVerify bool `yaml:"insecureSkipTLSVerify,omitempty"` // Static will make all requests to this upstream have a static response. // The response will have a body of "Authenticated" and a response code // matching StaticCode. // If StaticCode is not set, the response will return a 200 response. - Static bool `json:"static,omitempty"` + Static bool `yaml:"static,omitempty"` // StaticCode determines the response code for the Static response. // This option can only be used with Static enabled. - StaticCode *int `json:"staticCode,omitempty"` + StaticCode *int `yaml:"staticCode,omitempty"` // FlushInterval is the period between flushing the response buffer when // streaming response from the upstream. // Defaults to 1 second. - FlushInterval *time.Duration `json:"flushInterval,omitempty"` + FlushInterval *time.Duration `yaml:"flushInterval,omitempty"` // PassHostHeader determines whether the request host header should be proxied // to the upstream server. // Defaults to true. - PassHostHeader *bool `json:"passHostHeader,omitempty"` + PassHostHeader *bool `yaml:"passHostHeader,omitempty"` // ProxyWebSockets enables proxying of websockets to upstream servers // Defaults to true. - ProxyWebSockets *bool `json:"proxyWebSockets,omitempty"` + ProxyWebSockets *bool `yaml:"proxyWebSockets,omitempty"` // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. - Timeout *time.Duration `json:"timeout,omitempty"` + Timeout *time.Duration `yaml:"timeout,omitempty"` // DisableKeepAlives disables HTTP keep-alive connections to the upstream server. // Defaults to false. - DisableKeepAlives bool `json:"disableKeepAlives,omitempty"` + DisableKeepAlives bool `yaml:"disableKeepAlives,omitempty"` } diff --git a/pkg/requests/result_test.go b/pkg/requests/result_test.go index b6ecee74..76073975 100644 --- a/pkg/requests/result_test.go +++ b/pkg/requests/result_test.go @@ -104,8 +104,8 @@ var _ = Describe("Result suite", func() { Context("UnmarshalInto", func() { type testStruct struct { - A string `json:"a"` - B int `json:"b"` + A string `yaml:"a"` + B int `yaml:"b"` } type unmarshalIntoTableInput struct { From 4c0dd28f129d9ac402c4f8eabe0b88f0d10b393b Mon Sep 17 00:00:00 2001 From: tuunit Date: Sun, 9 Feb 2025 19:29:06 +0100 Subject: [PATCH 115/130] fix alpha config example Signed-off-by: Jan Larwig --- .../oauth2-proxy-alpha-config.cfg | 3 +- .../oauth2-proxy-alpha-config.yaml | 50 +++++++++++-------- 2 files changed, 30 insertions(+), 23 deletions(-) diff --git a/contrib/local-environment/oauth2-proxy-alpha-config.cfg b/contrib/local-environment/oauth2-proxy-alpha-config.cfg index 89e5a5b2..c913ec4f 100644 --- a/contrib/local-environment/oauth2-proxy-alpha-config.cfg +++ b/contrib/local-environment/oauth2-proxy-alpha-config.cfg @@ -1,5 +1,4 @@ -http_address="0.0.0.0:4180" cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" email_domains="example.com" cookie_secure="false" -redirect_url="http://localhost:4180/oauth2/callback" +redirect_url="http://oauth2-proxy.localtest.me:4180/oauth2/callback" diff --git a/contrib/local-environment/oauth2-proxy-alpha-config.yaml b/contrib/local-environment/oauth2-proxy-alpha-config.yaml index b2c9f6a8..41f07a03 100644 --- a/contrib/local-environment/oauth2-proxy-alpha-config.yaml +++ b/contrib/local-environment/oauth2-proxy-alpha-config.yaml @@ -1,23 +1,31 @@ -upstreams: - - id: httpbin - path: / - uri: http://httpbin +server: + bindAddress: "0.0.0.0:4180" +upstreamConfig: + upstreams: + - id: httpbin + path: / + uri: http://httpbin.localtest.me:8080 injectRequestHeaders: -- name: X-Forwarded-Groups - values: - - claim: groups -- name: X-Forwarded-User - values: - - claim: user -- name: X-Forwarded-Email - values: - - claim: email -- name: X-Forwarded-Preferred-Username - values: - - claim: preferred_username + - name: X-Forwarded-Groups + values: + - claimSource: + claim: groups + - name: X-Forwarded-User + values: + - claimSource: + claim: user + - name: X-Forwarded-Email + values: + - claimSource: + claim: email + - name: X-Forwarded-Preferred-Username + values: + - claimSource: + claim: preferred_username providers: -- provider: oidc - clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK - clientID: oauth2-proxy - oidcConfig: - issuerURL: http://dex.localhost:5556/dex + - id: oidc + provider: oidc + clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK + clientID: oauth2-proxy + oidcConfig: + issuerURL: http://dex.localhost:5556/dex From 18fc89812914991648664e707fb55b2f434fa53a Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 24 May 2025 17:05:33 +0200 Subject: [PATCH 116/130] resolve cipher deprecation and update mapstructures v2 Signed-off-by: Jan Larwig --- go.mod | 1 - go.sum | 2 -- pkg/apis/options/duration.go | 2 +- pkg/encryption/cipher.go | 2 +- 4 files changed, 2 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 9e353b0a..be7de03b 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,6 @@ require ( github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 - github.com/mitchellh/mapstructure v1.5.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 github.com/onsi/ginkgo/v2 v2.23.4 github.com/onsi/gomega v1.38.0 diff --git a/go.sum b/go.sum index 34aca12f..09282969 100644 --- a/go.sum +++ b/go.sum @@ -91,8 +91,6 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= diff --git a/pkg/apis/options/duration.go b/pkg/apis/options/duration.go index da13d96e..15f8776d 100644 --- a/pkg/apis/options/duration.go +++ b/pkg/apis/options/duration.go @@ -4,7 +4,7 @@ import ( "reflect" "time" - "github.com/mitchellh/mapstructure" + "github.com/go-viper/mapstructure/v2" ) // Duration is an alias for time.Duration so that we can ensure the marshalling diff --git a/pkg/encryption/cipher.go b/pkg/encryption/cipher.go index 300bba3a..ae5b50a3 100644 --- a/pkg/encryption/cipher.go +++ b/pkg/encryption/cipher.go @@ -79,7 +79,7 @@ func (c *cfbCipher) Decrypt(ciphertext []byte) ([]byte, error) { iv, ciphertext := ciphertext[:aes.BlockSize], ciphertext[aes.BlockSize:] plaintext := make([]byte, len(ciphertext)) - stream := cipher.NewCFBDecrypter(c.Block, iv) //nolint:staticcheck + stream := cipher.NewCFBEncrypter(c.Block, iv) //nolint:staticcheck stream.XORKeyStream(plaintext, ciphertext) return plaintext, nil From aaf1889b97ec265c6692a5a6663a812b83008ae8 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 24 May 2025 20:06:36 +0200 Subject: [PATCH 117/130] fix alpha config Signed-off-by: Jan Larwig --- docs/docs/configuration/alpha_config.md | 228 ++++++++++++------------ pkg/apis/options/doc.go | 2 +- pkg/encryption/cipher.go | 2 +- 3 files changed, 116 insertions(+), 116 deletions(-) diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 54dfb9f1..da48fafb 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -148,7 +148,7 @@ You must remove these options before starting OAuth2 Proxy with `--alpha-config` | Field | Type | Description | | ----- | ---- | ----------- | -| `SkipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | ### AlphaOptions @@ -163,12 +163,12 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `UpstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | -| `InjectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | -| `InjectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | -| `Server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `MetricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `Providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | ### AzureOptions @@ -178,8 +178,8 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `Tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | -| `GraphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | ### BitbucketOptions @@ -189,8 +189,8 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `Team` | _string_ | Team sets restrict logins to members of this team | -| `Repository` | _string_ | Repository sets restrict logins to user with access to this repository | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | ### ClaimSource @@ -200,9 +200,9 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `Claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | -| `Prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | -| `BasicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | ### GitHubOptions @@ -212,11 +212,11 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `Org` | _string_ | Org sets restrict logins to members of this organisation | -| `Team` | _string_ | Team sets restrict logins to members of this team | -| `Repo` | _string_ | Repo sets restrict logins to collaborators of this repository | -| `Token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | -| `Users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | ### GitLabOptions @@ -226,8 +226,8 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `Group` | _[]string_ | Group sets restrict logins to members of this group | -| `Projects` | _[]string_ | Projects restricts logins to members of these projects | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | ### GoogleOptions @@ -237,13 +237,13 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `Groups` | _[]string_ | Groups sets restrict logins to members of this Google group | -| `AdminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | -| `ServiceAccountJSON` | _string_ | ServiceAccountJSON is the path to the service account json credentials | -| `UseApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | -| `TargetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | -| `UseOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | -| `AdminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | ### Header @@ -254,10 +254,10 @@ response header. | Field | Type | Description | | ----- | ---- | ----------- | -| `Name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | -| `PreserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | | `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | -| `Values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | ### HeaderValue @@ -268,12 +268,12 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `Value` | _string_ | Value expects a base64 encoded string value. | -| `FromEnv` | _string_ | FromEnv expects the name of an environment variable. | -| `FromFile` | _string_ | FromFile expects a path to a file containing the secret value. | -| `Claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | -| `Prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | -| `BasicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | +| `value` | _string_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | ### KeycloakOptions @@ -283,8 +283,8 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `Groups` | _[]string_ | Group enables to restrict login to members of indicated group | -| `Roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | ### LoginGovOptions @@ -294,9 +294,9 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `JWTKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | -| `JWTKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | -| `PubJWKURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | ### LoginURLParameter @@ -374,9 +374,9 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `Name` | _string_ | Name specifies the name of the query parameter. | -| `Default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | -| `Allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | ### MicrosoftEntraIDOptions @@ -386,8 +386,8 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `AllowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | -| `FederatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | ### OIDCOptions @@ -397,18 +397,18 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `IssuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | -| `InsecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | -| `InsecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | -| `InsecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | -| `SkipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | -| `JwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | -| `PublicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | -| `EmailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | -| `GroupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | -| `UserIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | -| `AudienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | -| `ExtraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | ### Provider @@ -418,36 +418,36 @@ Provider holds all configuration for a single provider | Field | Type | Description | | ----- | ---- | ----------- | -| `ClientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | -| `ClientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | -| `ClientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | -| `KeycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | -| `AzureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | -| `MicrosoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | | `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | -| `BitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | -| `GitHubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | -| `GitLabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | -| `GoogleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | -| `OIDCConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | -| `LoginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | -| `ID` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | -| `Type` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | -| `Name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | -| `CAFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | -| `UseSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | -| `LoginURL` | _string_ | LoginURL is the authentication endpoint | -| `LoginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | -| `AuthRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | -| `RedeemURL` | _string_ | RedeemURL is the token redemption endpoint | -| `ProfileURL` | _string_ | ProfileURL is the profile access endpoint | -| `SkipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | -| `ProtectedResource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | -| `ValidateURL` | _string_ | ValidateURL is the access token validation endpoint | -| `Scope` | _string_ | Scope is the OAuth scope specification | -| `AllowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | -| `CodeChallengeMethod` | _string_ | The code challenge method | -| `BackendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | ### ProviderType #### (`string` alias) @@ -480,9 +480,9 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `Value` | _string_ | Value expects a base64 encoded string value. | -| `FromEnv` | _string_ | FromEnv expects the name of an environment variable. | -| `FromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `value` | _string_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | ### Server @@ -492,9 +492,9 @@ Server represents the configuration for an HTTP(S) server | Field | Type | Description | | ----- | ---- | ----------- | -| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | -| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | -| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | +| `bindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `tls` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | ### TLS @@ -505,10 +505,10 @@ as well as an optional minimal TLS version that is acceptable. | Field | Type | Description | | ----- | ---- | ----------- | -| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | -| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | -| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | -| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | +| `key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `minVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `cipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | ### URLParameterRule @@ -521,8 +521,8 @@ login URL. Either Value or Pattern should be supplied, not both. | Field | Type | Description | | ----- | ---- | ----------- | -| `Value` | _string_ | A Value rule matches just this specific value | -| `Pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | ### Upstream @@ -533,18 +533,18 @@ Requests will be proxied to this upstream if the path matches the request path. | Field | Type | Description | | ----- | ---- | ----------- | -| `ID` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | -| `Path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | -| `RewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | -| `URI` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | -| `InsecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | -| `Static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | -| `StaticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | -| `FlushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | -| `PassHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | -| `ProxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | -| `Timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | -| `DisableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | ### UpstreamConfig @@ -554,5 +554,5 @@ UpstreamConfig is a collection of definitions for upstream servers. | Field | Type | Description | | ----- | ---- | ----------- | -| `ProxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | -| `Upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/pkg/apis/options/doc.go b/pkg/apis/options/doc.go index 8ef112dd..d4b8862d 100644 --- a/pkg/apis/options/doc.go +++ b/pkg/apis/options/doc.go @@ -1,3 +1,3 @@ -//go:generate -command reference-gen go run github.com/oauth2-proxy/tools/reference-gen/cmd/reference-gen@v0.0.0-20220223111546-d3b50d1a591a +//go:generate -command reference-gen go run github.com/oauth2-proxy/tools/reference-gen/cmd/reference-gen@v0.0.0-20250404153144-32055bc45bc3 //go:generate reference-gen --package github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options --types AlphaOptions --header-file ../../../docs/docs/configuration/alpha_config.md.tmpl --out-file ../../../docs/docs/configuration/alpha_config.md package options diff --git a/pkg/encryption/cipher.go b/pkg/encryption/cipher.go index ae5b50a3..300bba3a 100644 --- a/pkg/encryption/cipher.go +++ b/pkg/encryption/cipher.go @@ -79,7 +79,7 @@ func (c *cfbCipher) Decrypt(ciphertext []byte) ([]byte, error) { iv, ciphertext := ciphertext[:aes.BlockSize], ciphertext[aes.BlockSize:] plaintext := make([]byte, len(ciphertext)) - stream := cipher.NewCFBEncrypter(c.Block, iv) //nolint:staticcheck + stream := cipher.NewCFBDecrypter(c.Block, iv) //nolint:staticcheck stream.XORKeyStream(plaintext, ciphertext) return plaintext, nil From 810f629ee8844dc56db3605588cc5fdf0e82fbbe Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 25 Jul 2025 13:29:22 +0200 Subject: [PATCH 118/130] revert: secrets as []byte instead of string Signed-off-by: Jan Larwig --- docs/docs/configuration/alpha_config.md | 4 ++-- main_test.go | 2 +- oauthproxy_test.go | 6 +++--- pkg/apis/options/legacy_options.go | 2 +- pkg/apis/options/legacy_options_test.go | 4 ++-- pkg/apis/options/load_test.go | 2 +- pkg/apis/options/secret_source.go | 4 ++-- pkg/apis/options/util/util.go | 2 +- pkg/apis/options/util/util_test.go | 2 +- pkg/header/injector_test.go | 16 ++++++++-------- pkg/http/http_suite_test.go | 12 ++++++------ pkg/http/server_test.go | 8 ++++---- pkg/middleware/headers_test.go | 8 ++++---- pkg/validation/common_test.go | 4 ++-- pkg/validation/header.go | 2 ++ pkg/validation/header_test.go | 4 ++-- 16 files changed, 42 insertions(+), 40 deletions(-) diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index da48fafb..c2c0aca6 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -268,7 +268,7 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | Value expects a base64 encoded string value. | +| `value` | _[]byte_ | Value expects a base64 encoded []byte | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | | `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | @@ -480,7 +480,7 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | Value expects a base64 encoded string value. | +| `value` | _[]byte_ | Value expects a base64 encoded []byte | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | diff --git a/main_test.go b/main_test.go index 7de1ac72..60b7eafd 100644 --- a/main_test.go +++ b/main_test.go @@ -139,7 +139,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Claim: "user", Prefix: "Basic ", BasicAuthPassword: &options.SecretSource{ - Value: "super-secret-password", + Value: []byte("super-secret-password"), }, }, }, diff --git a/oauthproxy_test.go b/oauthproxy_test.go index d5fac782..44569a35 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -215,7 +215,7 @@ func TestBasicAuthPassword(t *testing.T) { ClaimSource: &options.ClaimSource{ Claim: "email", BasicAuthPassword: &options.SecretSource{ - Value: basicAuthPassword, + Value: []byte(basicAuthPassword), }, }, }, @@ -1282,7 +1282,7 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: "This is a secure password", + Value: []byte("This is a secure password"), }, }, }, @@ -2044,7 +2044,7 @@ func baseTestOptions() *options.Options { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("This is a secure password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("This is a secure password"))), }, }, }, diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 45e4b113..ec779d84 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -294,7 +294,7 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header Claim: claim, Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: basicAuthPassword, + Value: []byte(basicAuthPassword), }, }, }, diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index c5f0e4da..98a89601 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -369,7 +369,7 @@ var _ = Describe("Legacy Options", func() { Claim: "user", Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: basicAuthSecret, + Value: []byte(basicAuthSecret), }, }, }, @@ -409,7 +409,7 @@ var _ = Describe("Legacy Options", func() { Claim: "email", Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: basicAuthSecret, + Value: []byte(basicAuthSecret), }, }, }, diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index a0079267..29d6511e 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -581,7 +581,7 @@ injectResponseHeaders: Values: []HeaderValue{ { SecretSource: &SecretSource{ - Value: "secret", + Value: []byte("secret"), }, }, }, diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go index 9d82c605..e73d019f 100644 --- a/pkg/apis/options/secret_source.go +++ b/pkg/apis/options/secret_source.go @@ -3,8 +3,8 @@ package options // SecretSource references an individual secret value. // Only one source within the struct should be defined at any time. type SecretSource struct { - // Value expects a base64 encoded string value. - Value string `yaml:"value,omitempty"` + // Value expects a base64 encoded []byte + Value []byte `yaml:"value,omitempty"` // FromEnv expects the name of an environment variable. FromEnv string `yaml:"fromEnv,omitempty"` diff --git a/pkg/apis/options/util/util.go b/pkg/apis/options/util/util.go index 794a6e91..03f0a134 100644 --- a/pkg/apis/options/util/util.go +++ b/pkg/apis/options/util/util.go @@ -11,7 +11,7 @@ import ( func GetSecretValue(source *options.SecretSource) ([]byte, error) { switch { case len(source.Value) > 0 && source.FromEnv == "" && source.FromFile == "": - return []byte(source.Value), nil + return source.Value, nil case len(source.Value) == 0 && source.FromEnv != "" && source.FromFile == "": return []byte(os.Getenv(source.FromEnv)), nil case len(source.Value) == 0 && source.FromEnv == "" && source.FromFile != "": diff --git a/pkg/apis/options/util/util_test.go b/pkg/apis/options/util/util_test.go index 5c4bfa6d..e84db1ec 100644 --- a/pkg/apis/options/util/util_test.go +++ b/pkg/apis/options/util/util_test.go @@ -31,7 +31,7 @@ var _ = Describe("GetSecretValue", func() { It("returns the correct value from the string value", func() { value, err := GetSecretValue(&options.SecretSource{ - Value: "secret-value-1", + Value: []byte("secret-value-1"), }) Expect(err).ToNot(HaveOccurred()) Expect(string(value)).To(Equal("secret-value-1")) diff --git a/pkg/header/injector_test.go b/pkg/header/injector_test.go index bb37261d..25c276dc 100644 --- a/pkg/header/injector_test.go +++ b/pkg/header/injector_test.go @@ -55,7 +55,7 @@ var _ = Describe("Injector Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: "super-secret", + Value: []byte("super-secret"), }, }, }, @@ -199,7 +199,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: "basic-password", + Value: []byte("basic-password"), }, }, }, @@ -227,7 +227,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), }, }, }, @@ -322,7 +322,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), FromEnv: "SECRET_ENV", }, }, @@ -348,7 +348,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: "basic-password", + Value: []byte("basic-password"), }, }, }, @@ -379,17 +379,17 @@ var _ = Describe("Injector Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: "major=1", + Value: []byte("major=1"), }, }, { SecretSource: &options.SecretSource{ - Value: "minor=2", + Value: []byte("minor=2"), }, }, { SecretSource: &options.SecretSource{ - Value: "patch=3", + Value: []byte("patch=3"), }, }, }, diff --git a/pkg/http/http_suite_test.go b/pkg/http/http_suite_test.go index 219f26ea..19d4d3ff 100644 --- a/pkg/http/http_suite_test.go +++ b/pkg/http/http_suite_test.go @@ -48,10 +48,10 @@ var _ = BeforeSuite(func() { certOut := new(bytes.Buffer) Expect(pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})).To(Succeed()) - ipv4CertDataSource.Value = certOut.String() + ipv4CertDataSource.Value = certOut.Bytes() keyOut := new(bytes.Buffer) Expect(pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})).To(Succeed()) - ipv4KeyDataSource.Value = keyOut.String() + ipv4KeyDataSource.Value = keyOut.Bytes() }) By("Generating a ipv6 self-signed cert for TLS tests", func() { @@ -61,16 +61,16 @@ var _ = BeforeSuite(func() { certOut := new(bytes.Buffer) Expect(pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})).To(Succeed()) - ipv6CertDataSource.Value = certOut.String() + ipv6CertDataSource.Value = certOut.Bytes() keyOut := new(bytes.Buffer) Expect(pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})).To(Succeed()) - ipv6KeyDataSource.Value = keyOut.String() + ipv6KeyDataSource.Value = keyOut.Bytes() }) By("Setting up a http client", func() { - ipv4cert, err := tls.X509KeyPair([]byte(ipv4CertDataSource.Value), []byte(ipv4KeyDataSource.Value)) + ipv4cert, err := tls.X509KeyPair(ipv4CertDataSource.Value, ipv4KeyDataSource.Value) Expect(err).ToNot(HaveOccurred()) - ipv6cert, err := tls.X509KeyPair([]byte(ipv6CertDataSource.Value), []byte(ipv6KeyDataSource.Value)) + ipv6cert, err := tls.X509KeyPair(ipv6CertDataSource.Value, ipv6KeyDataSource.Value) Expect(err).ToNot(HaveOccurred()) ipv4certificate, err := x509.ParseCertificate(ipv4cert.Certificate[0]) diff --git a/pkg/http/server_test.go b/pkg/http/server_test.go index 6584b757..8dfa13af 100644 --- a/pkg/http/server_test.go +++ b/pkg/http/server_test.go @@ -234,7 +234,7 @@ var _ = Describe("Server", func() { SecureBindAddress: "127.0.0.1:0", TLS: &options.TLS{ Key: &options.SecretSource{ - Value: "invalid", + Value: []byte("invalid"), }, Cert: &ipv4CertDataSource, }, @@ -250,7 +250,7 @@ var _ = Describe("Server", func() { TLS: &options.TLS{ Key: &ipv4KeyDataSource, Cert: &options.SecretSource{ - Value: "invalid", + Value: []byte("invalid"), }, }, }, @@ -506,7 +506,7 @@ var _ = Describe("Server", func() { SecureBindAddress: "[::1]:0", TLS: &options.TLS{ Key: &options.SecretSource{ - Value: "invalid", + Value: []byte("invalid"), }, Cert: &ipv6CertDataSource, }, @@ -523,7 +523,7 @@ var _ = Describe("Server", func() { TLS: &options.TLS{ Key: &ipv6KeyDataSource, Cert: &options.SecretSource{ - Value: "invalid", + Value: []byte("invalid"), }, }, }, diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index cb8f9d11..6a60ec01 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -188,7 +188,7 @@ var _ = Describe("Headers Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), FromEnv: "SECRET_ENV", }, }, @@ -304,7 +304,7 @@ var _ = Describe("Headers Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: "_oauth2_proxy=ey123123123", + Value: []byte("_oauth2_proxy=ey123123123"), }, }, }, @@ -314,7 +314,7 @@ var _ = Describe("Headers Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: "oauth_user", + Value: []byte("oauth_user"), }, }, }, @@ -460,7 +460,7 @@ var _ = Describe("Headers Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), FromEnv: "SECRET_ENV", }, }, diff --git a/pkg/validation/common_test.go b/pkg/validation/common_test.go index bb7c2dd6..9e873c35 100644 --- a/pkg/validation/common_test.go +++ b/pkg/validation/common_test.go @@ -9,12 +9,12 @@ import ( ) var _ = Describe("Common", func() { - var validSecretSourceValue string + var validSecretSourceValue []byte const validSecretSourceEnv = "OAUTH2_PROXY_TEST_SECRET_SOURCE_ENV" var validSecretSourceFile string BeforeEach(func() { - validSecretSourceValue = "This is a secret source value" + validSecretSourceValue = []byte("This is a secret source value") Expect(os.Setenv(validSecretSourceEnv, "This is a secret source env")).To(Succeed()) tmp, err := os.CreateTemp("", "oauth2-proxy-secret-source-test") Expect(err).ToNot(HaveOccurred()) diff --git a/pkg/validation/header.go b/pkg/validation/header.go index 713113f4..b1258144 100644 --- a/pkg/validation/header.go +++ b/pkg/validation/header.go @@ -51,9 +51,11 @@ func validateHeaderValue(_ string, value options.HeaderValue) []string { func validateHeaderValueClaimSource(claim options.ClaimSource) []string { msgs := []string{} + if claim.Claim == "" { msgs = append(msgs, "claim should not be empty") } + if claim.BasicAuthPassword != nil { msgs = append(msgs, prefixValues("invalid basicAuthPassword: ", validateSecretSource(*claim.BasicAuthPassword))...) } diff --git a/pkg/validation/header_test.go b/pkg/validation/header_test.go index 88849ea1..2d9ef6dd 100644 --- a/pkg/validation/header_test.go +++ b/pkg/validation/header_test.go @@ -30,7 +30,7 @@ var _ = Describe("Headers", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("secret")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))), }, }, }, @@ -43,7 +43,7 @@ var _ = Describe("Headers", func() { ClaimSource: &options.ClaimSource{ Claim: "email", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("secret")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))), }, }, }, From 48bd2d7d3824682ce94b1aabb16f8e7e149c1961 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 25 Jul 2025 15:08:50 +0200 Subject: [PATCH 119/130] fix merge problems and test cases Signed-off-by: Jan Larwig --- main.go | 2 +- main_test.go | 16 ++++++++-------- pkg/apis/options/header.go | 2 +- pkg/apis/options/{duration.go => hooks.go} | 14 ++++++++++++++ .../options/{duration_test.go => hooks_test.go} | 16 +++++++++++++++- pkg/apis/options/load.go | 5 ++++- pkg/apis/options/load_test.go | 4 ++-- pkg/apis/options/providers.go | 12 ++++++------ pkg/apis/options/upstreams.go | 10 +++++----- 9 files changed, 56 insertions(+), 25 deletions(-) rename pkg/apis/options/{duration.go => hooks.go} (78%) rename pkg/apis/options/{duration_test.go => hooks_test.go} (83%) diff --git a/main.go b/main.go index a9def2f6..7142ae0b 100644 --- a/main.go +++ b/main.go @@ -70,7 +70,7 @@ func main() { func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { opts, err := loadLegacyOptions(config, extraFlags, args) if err != nil { - return nil, fmt.Errorf("couldn't load legacy options: %w", err) + return nil, fmt.Errorf("failed to load legacy options: %w", err) } if yamlConfig != "" { diff --git a/main_test.go b/main_test.go index 60b7eafd..709c6857 100644 --- a/main_test.go +++ b/main_test.go @@ -22,7 +22,7 @@ var _ = Describe("Configuration Loading Suite", func() { http_address="127.0.0.1:4180" upstreams="http://httpbin" set_basic_auth="true" -basic_auth_password="super-secret-password" +basic_auth_password="c3VwZXItc2VjcmV0LXBhc3N3b3Jk" client_id="oauth2-proxy" client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" ` @@ -45,7 +45,7 @@ injectRequestHeaders: claim: user prefix: "Basic " basicAuthPassword: - value: super-secret-password + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk - name: X-Forwarded-Groups values: - claimSource: @@ -69,12 +69,12 @@ injectResponseHeaders: claim: user prefix: "Basic " basicAuthPassword: - value: super-secret-password + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk server: bindAddress: "127.0.0.1:4180" providers: -- provider: google - ID: google=oauth2-proxy +- id: google=oauth2-proxy + provider: google clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK clientID: oauth2-proxy azureConfig: @@ -139,7 +139,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Claim: "user", Prefix: "Basic ", BasicAuthPassword: &options.SecretSource{ - Value: []byte("super-secret-password"), + Value: []byte("c3VwZXItc2VjcmV0LXBhc3N3b3Jk"), }, }, }, @@ -248,7 +248,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Entry("with bad legacy configuration", loadConfigurationTableInput{ configContent: testCoreConfig + "unknown_field=\"something\"", expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), }), Entry("with bad alpha configuration", loadConfigurationTableInput{ configContent: testCoreConfig, @@ -260,7 +260,7 @@ redirect_url="http://localhost:4180/oauth2/callback" configContent: testCoreConfig + "unknown_field=\"something\"", alphaConfigContent: testAlphaConfig, expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load core options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), }), ) }) diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index ab391677..a695d7d4 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -11,7 +11,7 @@ type Header struct { // should be preserved for the request to the upstream server. // This option only applies to injected request headers. // Defaults to false (headers that match this header will be stripped). - PreserveRequestValue bool `yaml:"preserveRequestValue,omitempty"` + PreserveRequestValue bool `yaml:"preserveRequestValue"` // InsecureSkipHeaderNormalization disables normalizing the header name // According to RFC 7230 Section 3.2 there aren't any rules about diff --git a/pkg/apis/options/duration.go b/pkg/apis/options/hooks.go similarity index 78% rename from pkg/apis/options/duration.go rename to pkg/apis/options/hooks.go index 15f8776d..79653ecb 100644 --- a/pkg/apis/options/duration.go +++ b/pkg/apis/options/hooks.go @@ -41,3 +41,17 @@ func toDurationHookFunc() mapstructure.DecodeHookFunc { } } } + +// StringToBytesHookFunc returns a DecodeHookFunc that converts string to []byte. +func stringToBytesHookFunc() mapstructure.DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() == reflect.String && t == reflect.TypeOf([]byte{}) { + return []byte(data.(string)), nil + } + return data, nil + } +} diff --git a/pkg/apis/options/duration_test.go b/pkg/apis/options/hooks_test.go similarity index 83% rename from pkg/apis/options/duration_test.go rename to pkg/apis/options/hooks_test.go index 63f203a8..99514a7c 100644 --- a/pkg/apis/options/duration_test.go +++ b/pkg/apis/options/hooks_test.go @@ -5,7 +5,7 @@ import ( "time" ) -func TestDecode(t *testing.T) { +func TestToDurationHook(t *testing.T) { type result struct { Duration time.Duration `yaml:"duration"` } @@ -80,3 +80,17 @@ func TestDecode(t *testing.T) { }) } } + +func TestStringToBytesHook(t *testing.T) { + var result struct { + Value []byte `yaml:"value"` + } + + if err := Decode(map[string]interface{}{"value": "hello-world"}, &result); err != nil { + t.Fatal(err) + } + + if string(result.Value) != "hello-world" { + t.Errorf("expected %q, got %q", "hello-world", string(result.Value)) + } +} diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index af7f76d9..fdd20c7a 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -89,7 +89,10 @@ func LoadYAML(configFileName string, opts interface{}) error { // - An error if decoding fails or if there are unmapped keys. func Decode(input interface{}, result interface{}) error { decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ - DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), + DecodeHook: mapstructure.ComposeDecodeHookFunc( + toDurationHookFunc(), + stringToBytesHookFunc(), + ), Metadata: nil, // Don't track any metadata Result: result, // Decode the result into the prefilled options TagName: "yaml", // Parse all fields that use the json tag diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 29d6511e..42083f76 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -155,7 +155,7 @@ var _ = Describe("Load", func() { } err := Load(configFileName, flagSet, input) if o.expectedErr != nil { - Expect(err).To(MatchError(o.expectedErr.Error())) + Expect(err).To(MatchError(ContainSubstring(o.expectedErr.Error()))) } else { Expect(err).ToNot(HaveOccurred()) } @@ -471,7 +471,7 @@ sub: configFile: []byte(`stringSliceOption: "a"`), input: &TestOptions{}, expectedOutput: &TestOptions{}, - expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go struct field TestOptions.TestOptionSubStruct.StringSliceOption of type []string"), + expectedErr: errors.New("error decoding config: decoding failed due to the following error(s):\n\n'stringSliceOption' source data must be an array or slice, got string"), }), Entry("with a config file containing environment variable references", loadYAMLTableInput{ configFile: []byte("stringOption: ${TESTUSER}"), diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 0a0796e9..9ddc2a84 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -67,7 +67,7 @@ type Provider struct { CAFiles []string `yaml:"caFiles,omitempty"` // UseSystemTrustStore determines if your custom CA files and the system trust store are used // If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. - UseSystemTrustStore bool `yaml:"useSystemTrustStore,omitempty"` + UseSystemTrustStore bool `yaml:"useSystemTrustStore"` // LoginURL is the authentication endpoint LoginURL string `yaml:"loginURL,omitempty"` // LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL @@ -80,7 +80,7 @@ type Provider struct { ProfileURL string `yaml:"profileURL,omitempty"` // SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token // default set to 'false' - SkipClaimsFromProfileURL bool `yaml:"skipClaimsFromProfileURL,omitempty"` + SkipClaimsFromProfileURL bool `yaml:"skipClaimsFromProfileURL"` // ProtectedResource is the resource that is protected (Azure AD and ADFS only) ProtectedResource string `yaml:"resource,omitempty"` // ValidateURL is the access token validation endpoint @@ -181,13 +181,13 @@ type MicrosoftEntraIDOptions struct { // FederatedTokenAuth enable oAuth2 client authentication with federated token projected // by Entra Workload Identity plugin, instead of client secret. - FederatedTokenAuth bool `yaml:"federatedTokenAuth,omitempty"` + FederatedTokenAuth bool `yaml:"federatedTokenAuth"` } type ADFSOptions struct { // Skip adding the scope parameter in login request // Default value is 'false' - SkipScope bool `yaml:"skipScope,omitempty"` + SkipScope bool `yaml:"skipScope"` } type BitbucketOptions struct { @@ -227,7 +227,7 @@ type GoogleOptions struct { // ServiceAccountJSON is the path to the service account json credentials ServiceAccountJSON string `yaml:"serviceAccountJson,omitempty"` // UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON - UseApplicationDefaultCredentials bool `yaml:"useApplicationDefaultCredentials,omitempty"` + UseApplicationDefaultCredentials bool `yaml:"useApplicationDefaultCredentials"` // TargetPrincipal is the Google Service Account used for Application Default Credentials TargetPrincipal string `yaml:"targetPrincipal,omitempty"` // UseOrganizationId indicates whether to use the organization ID as the UserName claim @@ -254,7 +254,7 @@ type OIDCOptions struct { InsecureSkipNonce bool `yaml:"insecureSkipNonce"` // SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints // default set to 'false' - SkipDiscovery bool `yaml:"skipDiscovery,omitempty"` + SkipDiscovery bool `yaml:"skipDiscovery"` // JwksURL is the OpenID Connect JWKS URL // eg: https://www.googleapis.com/oauth2/v3/certs JwksURL string `yaml:"jwksURL,omitempty"` diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index b32cc27d..2b90e632 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -14,7 +14,7 @@ const ( type UpstreamConfig struct { // ProxyRawPath will pass the raw url path to upstream allowing for urls // like: "/%2F/" which would otherwise be redirected to "/" - ProxyRawPath bool `yaml:"proxyRawPath,omitempty"` + ProxyRawPath bool `yaml:"proxyRawPath"` // Upstreams represents the configuration for the upstream servers. // Requests will be proxied to this upstream if the path matches the request path. @@ -64,13 +64,13 @@ type Upstream struct { // This option is insecure and will allow potential Man-In-The-Middle attacks // between OAuth2 Proxy and the upstream server. // Defaults to false. - InsecureSkipTLSVerify bool `yaml:"insecureSkipTLSVerify,omitempty"` + InsecureSkipTLSVerify bool `yaml:"insecureSkipTLSVerify"` // Static will make all requests to this upstream have a static response. // The response will have a body of "Authenticated" and a response code // matching StaticCode. // If StaticCode is not set, the response will return a 200 response. - Static bool `yaml:"static,omitempty"` + Static bool `yaml:"static"` // StaticCode determines the response code for the Static response. // This option can only be used with Static enabled. @@ -84,11 +84,11 @@ type Upstream struct { // PassHostHeader determines whether the request host header should be proxied // to the upstream server. // Defaults to true. - PassHostHeader *bool `yaml:"passHostHeader,omitempty"` + PassHostHeader *bool `yaml:"passHostHeader"` // ProxyWebSockets enables proxying of websockets to upstream servers // Defaults to true. - ProxyWebSockets *bool `yaml:"proxyWebSockets,omitempty"` + ProxyWebSockets *bool `yaml:"proxyWebSockets"` // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. From 955ab6b41bec78ac384b0b1f7bbbc6f297898734 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 26 Jul 2025 12:46:17 +0200 Subject: [PATCH 120/130] fix test setup and add local image build make target Signed-off-by: Jan Larwig --- Makefile | 4 ++ .../docker-compose-alpha-config.yaml | 49 ++++++++++++++++++- contrib/local-environment/docker-compose.yaml | 2 +- .../oauth2-proxy-alpha-config.yaml | 12 +---- docs/docs/configuration/alpha_config.md | 4 +- pkg/apis/options/secret_source.go | 2 +- 6 files changed, 58 insertions(+), 15 deletions(-) diff --git a/Makefile b/Makefile index 06471100..38b2f949 100644 --- a/Makefile +++ b/Makefile @@ -74,6 +74,10 @@ DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --pus .PHONY: build-docker build-docker: build-distroless build-alpine ## Build multi architecture docker images in both flavours (distroless / alpine) +.PHONY: build-docker-local +build-docker-local: ## Build distroless docker image and locally load into docker images + $(DOCKER_BUILDX) --load -t $(REGISTRY)/$(REPOSITORY):${VERSION}-local . + .PHONY: build-distroless build-distroless: ## Build multi architecture distroless based docker image $(DOCKER_BUILDX_X_PLATFORM) -t $(REGISTRY)/$(REPOSITORY):latest -t $(REGISTRY)/$(REPOSITORY):${VERSION} . diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 57d33040..16e6a3ca 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -10,11 +10,58 @@ # make alpha-config- (eg make nginx-up, make nginx-down) # # Access http://localhost:4180 to initiate a login cycle -version: '3.0' +version: "3.0" services: oauth2-proxy: + container_name: oauth2-proxy image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml + hostname: oauth2-proxy volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" - "./oauth2-proxy-alpha-config.yaml:/oauth2-proxy-alpha-config.yaml" + restart: unless-stopped + ports: + - 4180:4180/tcp + networks: + dex: {} + httpbin: {} + depends_on: + - dex + - httpbin + dex: + container_name: dex + image: ghcr.io/dexidp/dex:v2.43.1 + command: dex serve /dex.yaml + hostname: dex + volumes: + - "./dex.yaml:/dex.yaml" + restart: unless-stopped + ports: + - 5556:5556/tcp + networks: + dex: + aliases: + - dex.localtest.me + etcd: {} + depends_on: + - etcd + httpbin: + container_name: httpbin + image: kennethreitz/httpbin + ports: [] + networks: + httpbin: {} + etcd: + container_name: etcd + image: gcr.io/etcd-development/etcd:v3.6.2 + entrypoint: /usr/local/bin/etcd + command: + - --listen-client-urls=http://0.0.0.0:2379 + - --advertise-client-urls=http://etcd:2379 + networks: + etcd: {} +networks: + dex: {} + etcd: {} + httpbin: {} diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index f1e7a23d..fef0e32f 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -9,7 +9,7 @@ # make (eg. make up, make down) # # Access http://oauth2-proxy.localtest.me:4180 to initiate a login cycle -version: '3.0' +version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy diff --git a/contrib/local-environment/oauth2-proxy-alpha-config.yaml b/contrib/local-environment/oauth2-proxy-alpha-config.yaml index 41f07a03..e423db98 100644 --- a/contrib/local-environment/oauth2-proxy-alpha-config.yaml +++ b/contrib/local-environment/oauth2-proxy-alpha-config.yaml @@ -4,12 +4,8 @@ upstreamConfig: upstreams: - id: httpbin path: / - uri: http://httpbin.localtest.me:8080 + uri: http://httpbin injectRequestHeaders: - - name: X-Forwarded-Groups - values: - - claimSource: - claim: groups - name: X-Forwarded-User values: - claimSource: @@ -18,14 +14,10 @@ injectRequestHeaders: values: - claimSource: claim: email - - name: X-Forwarded-Preferred-Username - values: - - claimSource: - claim: preferred_username providers: - id: oidc provider: oidc clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK clientID: oauth2-proxy oidcConfig: - issuerURL: http://dex.localhost:5556/dex + issuerURL: http://dex.localtest.me:5556/dex diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index c2c0aca6..495bc206 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -268,7 +268,7 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _[]byte_ | Value expects a base64 encoded []byte | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | | `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | @@ -480,7 +480,7 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _[]byte_ | Value expects a base64 encoded []byte | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go index e73d019f..848f1635 100644 --- a/pkg/apis/options/secret_source.go +++ b/pkg/apis/options/secret_source.go @@ -3,7 +3,7 @@ package options // SecretSource references an individual secret value. // Only one source within the struct should be defined at any time. type SecretSource struct { - // Value expects a base64 encoded []byte + // Value expects a base64 encoded string value. Value []byte `yaml:"value,omitempty"` // FromEnv expects the name of an environment variable. From 50414356e83506ff1965fca6ccbcab45cf731024 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 19 Aug 2025 14:43:32 +0200 Subject: [PATCH 121/130] return nil directly Signed-off-by: Jan Larwig --- main.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 7142ae0b..1525e94c 100644 --- a/main.go +++ b/main.go @@ -77,7 +77,8 @@ func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, arg logger.Printf("WARNING: You are using alpha configuration. The structure in this configuration file may change without notice. You MUST remove conflicting options from your existing configuration.") return loadYamlOptions(yamlConfig, config, extraFlags, args) } - return opts, err + + return opts, nil } // loadLegacyOptions loads the old toml options using the legacy flagset From 9d70e04262f91739f78c25f3e61015410e412ceb Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 19 Aug 2025 16:27:53 +0200 Subject: [PATCH 122/130] feat: migrate all alpha config booleans to pointers Signed-off-by: Jan Larwig --- main_test.go | 73 +++++++++++++------- oauthproxy_test.go | 5 +- pkg/apis/options/header.go | 2 +- pkg/apis/options/legacy_options.go | 29 ++++---- pkg/apis/options/legacy_options_test.go | 88 ++++++++++++------------- pkg/apis/options/providers.go | 26 ++++---- pkg/apis/options/upstreams.go | 12 ++-- pkg/middleware/headers.go | 2 +- pkg/middleware/headers_test.go | 9 +-- pkg/upstream/http.go | 6 +- pkg/upstream/http_test.go | 23 ++++--- pkg/upstream/proxy.go | 4 +- pkg/upstream/proxy_test.go | 11 ++-- pkg/util/ptr/ptr.go | 14 ++++ pkg/util/ptr/ptr_test.go | 38 +++++++++++ pkg/validation/options.go | 2 +- pkg/validation/options_test.go | 5 +- pkg/validation/providers.go | 7 +- pkg/validation/upstreams.go | 10 +-- pkg/validation/upstreams_test.go | 12 ++-- providers/adfs.go | 2 +- providers/adfs_test.go | 3 +- providers/google.go | 5 +- providers/ms_entra_id.go | 2 +- providers/ms_entra_id_test.go | 7 +- providers/oidc.go | 2 +- providers/oidc_test.go | 2 +- providers/providers.go | 8 +-- providers/providers_test.go | 9 +-- 29 files changed, 253 insertions(+), 165 deletions(-) create mode 100644 pkg/util/ptr/ptr.go create mode 100644 pkg/util/ptr/ptr_test.go diff --git a/main_test.go b/main_test.go index 709c6857..b9ec39fb 100644 --- a/main_test.go +++ b/main_test.go @@ -7,6 +7,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/format" @@ -25,11 +26,12 @@ set_basic_auth="true" basic_auth_password="c3VwZXItc2VjcmV0LXBhc3N3b3Jk" client_id="oauth2-proxy" client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" +google_admin_email="admin@example.com" +google_target_principal="principal" ` const testAlphaConfig = ` upstreamConfig: - proxyrawpath: false upstreams: - id: / path: / @@ -38,8 +40,11 @@ upstreamConfig: passHostHeader: true proxyWebSockets: true timeout: 30s + insecureSkipTLSVerify: false + disableKeepAlives: false injectRequestHeaders: - name: Authorization + preserveRequestValue: false values: - claimSource: claim: user @@ -47,18 +52,22 @@ injectRequestHeaders: basicAuthPassword: value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk - name: X-Forwarded-Groups + preserveRequestValue: false values: - claimSource: claim: groups - name: X-Forwarded-User + preserveRequestValue: false values: - claimSource: claim: user - name: X-Forwarded-Email + preserveRequestValue: false values: - claimSource: claim: email - name: X-Forwarded-Preferred-Username + preserveRequestValue: false values: - claimSource: claim: preferred_username @@ -77,12 +86,17 @@ providers: provider: google clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK clientID: oauth2-proxy - azureConfig: - tenant: common + useSystemTrustStore: false + skipClaimsFromProfileURL: false + googleConfig: + adminEmail: admin@example.com + targetPrincipal: principal + useApplicationDefaultCredentials: false oidcConfig: groupsClaim: groups emailClaim: email userIDClaim: email + insecureSkipIssuerVerification: false insecureSkipNonce: true audienceClaims: [aud] extraAudiences: [] @@ -100,10 +114,6 @@ cookie_secure="false" redirect_url="http://localhost:4180/oauth2/callback" ` - boolPtr := func(b bool) *bool { - return &b - } - durationPtr := func(d time.Duration) *time.Duration { return &d } @@ -120,13 +130,15 @@ redirect_url="http://localhost:4180/oauth2/callback" opts.UpstreamServers = options.UpstreamConfig{ Upstreams: []options.Upstream{ { - ID: "/", - Path: "/", - URI: "http://httpbin", - FlushInterval: durationPtr(options.DefaultUpstreamFlushInterval), - PassHostHeader: boolPtr(true), - ProxyWebSockets: boolPtr(true), - Timeout: durationPtr(options.DefaultUpstreamTimeout), + ID: "/", + Path: "/", + URI: "http://httpbin", + FlushInterval: durationPtr(options.DefaultUpstreamFlushInterval), + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), + Timeout: durationPtr(options.DefaultUpstreamTimeout), + InsecureSkipTLSVerify: ptr.Ptr(false), + DisableKeepAlives: ptr.Ptr(false), }, }, } @@ -146,25 +158,38 @@ redirect_url="http://localhost:4180/oauth2/callback" }, } + authHeader.PreserveRequestValue = ptr.Ptr(false) opts.InjectRequestHeaders = append([]options.Header{authHeader}, opts.InjectRequestHeaders...) + + authHeader.PreserveRequestValue = nil opts.InjectResponseHeaders = append(opts.InjectResponseHeaders, authHeader) opts.Providers = options.Providers{ options.Provider{ - ID: "google=oauth2-proxy", - Type: "google", - ClientSecret: "b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK", - ClientID: "oauth2-proxy", + ID: "google=oauth2-proxy", + Type: "google", + ClientSecret: "b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK", + ClientID: "oauth2-proxy", + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), + GoogleConfig: options.GoogleOptions{ + AdminEmail: "admin@example.com", + UseApplicationDefaultCredentials: ptr.Ptr(false), + TargetPrincipal: "principal", + }, AzureConfig: options.AzureOptions{ Tenant: "common", }, OIDCConfig: options.OIDCOptions{ - GroupsClaim: "groups", - EmailClaim: "email", - UserIDClaim: "email", - AudienceClaims: []string{"aud"}, - ExtraAudiences: []string{}, - InsecureSkipNonce: true, + GroupsClaim: "groups", + EmailClaim: "email", + UserIDClaim: "email", + AudienceClaims: []string{"aud"}, + ExtraAudiences: []string{}, + InsecureSkipNonce: ptr.Ptr(true), + InsecureAllowUnverifiedEmail: ptr.Ptr(false), + InsecureSkipIssuerVerification: ptr.Ptr(false), + SkipDiscovery: ptr.Ptr(false), }, LoginURLParameters: []options.LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 44569a35..0463c9dd 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -23,6 +23,7 @@ import ( internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" sessionscookie "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/cookie" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/upstream" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation" "github.com/oauth2-proxy/oauth2-proxy/v7/providers" "github.com/stretchr/testify/assert" @@ -506,7 +507,7 @@ func TestStaticProxyUpstream(t *testing.T) { ProxyUpstream: options.Upstream{ ID: "static-proxy", Path: "/static-proxy", - Static: true, + Static: ptr.Ptr(true), }, }) if err != nil { @@ -2223,7 +2224,7 @@ func TestTrustedIPs(t *testing.T) { { ID: "static", Path: "/", - Static: true, + Static: ptr.Ptr(true), }, }, } diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index a695d7d4..048b1974 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -11,7 +11,7 @@ type Header struct { // should be preserved for the request to the upstream server. // This option only applies to injected request headers. // Defaults to false (headers that match this header will be stripped). - PreserveRequestValue bool `yaml:"preserveRequestValue"` + PreserveRequestValue *bool `yaml:"preserveRequestValue,omitempty"` // InsecureSkipHeaderNormalization disables normalizing the header name // According to RFC 7230 Section 3.2 there aren't any rules about diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index ec779d84..672d6c63 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -9,6 +9,7 @@ import ( "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/spf13/pflag" ) @@ -142,12 +143,12 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { ID: u.Path, Path: u.Path, URI: upstreamString, - InsecureSkipTLSVerify: l.SSLUpstreamInsecureSkipVerify, + InsecureSkipTLSVerify: &l.SSLUpstreamInsecureSkipVerify, PassHostHeader: &l.PassHostHeader, ProxyWebSockets: &l.ProxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, - DisableKeepAlives: l.DisableKeepAlives, + DisableKeepAlives: &l.DisableKeepAlives, } switch u.Scheme { @@ -164,7 +165,7 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { logger.Errorf("unable to convert %q to int, use default \"200\"", u.Host) responseCode = 200 } - upstream.Static = true + upstream.Static = ptr.Ptr(true) upstream.StaticCode = &responseCode // This is not allowed to be empty and must be unique @@ -175,12 +176,12 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { // Force defaults compatible with static responses upstream.URI = "" - upstream.InsecureSkipTLSVerify = false + upstream.InsecureSkipTLSVerify = ptr.Ptr(false) upstream.PassHostHeader = nil upstream.ProxyWebSockets = nil upstream.FlushInterval = nil upstream.Timeout = nil - upstream.DisableKeepAlives = false + upstream.DisableKeepAlives = ptr.Ptr(false) case "unix": upstream.Path = "/" } @@ -253,7 +254,7 @@ func (l *LegacyHeaders) getRequestHeaders() []Header { } for i := range requestHeaders { - requestHeaders[i].PreserveRequestValue = !l.SkipAuthStripHeaders + requestHeaders[i].PreserveRequestValue = ptr.Ptr(!l.SkipAuthStripHeaders) } return requestHeaders @@ -684,11 +685,11 @@ func (l *LegacyProvider) convert() (Providers, error) { ClientSecretFile: l.ClientSecretFile, Type: ProviderType(l.ProviderType), CAFiles: l.ProviderCAFiles, - UseSystemTrustStore: l.UseSystemTrustStore, + UseSystemTrustStore: &l.UseSystemTrustStore, LoginURL: l.LoginURL, RedeemURL: l.RedeemURL, ProfileURL: l.ProfileURL, - SkipClaimsFromProfileURL: l.SkipClaimsFromProfileURL, + SkipClaimsFromProfileURL: &l.SkipClaimsFromProfileURL, ProtectedResource: l.ProtectedResource, ValidateURL: l.ValidateURL, Scope: l.Scope, @@ -701,10 +702,10 @@ func (l *LegacyProvider) convert() (Providers, error) { // This part is out of the switch section for all providers that support OIDC provider.OIDCConfig = OIDCOptions{ IssuerURL: l.OIDCIssuerURL, - InsecureAllowUnverifiedEmail: l.InsecureOIDCAllowUnverifiedEmail, - InsecureSkipIssuerVerification: l.InsecureOIDCSkipIssuerVerification, - InsecureSkipNonce: l.InsecureOIDCSkipNonce, - SkipDiscovery: l.SkipOIDCDiscovery, + InsecureAllowUnverifiedEmail: &l.InsecureOIDCAllowUnverifiedEmail, + InsecureSkipIssuerVerification: &l.InsecureOIDCSkipIssuerVerification, + InsecureSkipNonce: &l.InsecureOIDCSkipNonce, + SkipDiscovery: &l.SkipOIDCDiscovery, JwksURL: l.OIDCJwksURL, UserIDClaim: l.UserIDClaim, EmailClaim: l.OIDCEmailClaim, @@ -772,7 +773,7 @@ func (l *LegacyProvider) convert() (Providers, error) { Groups: l.GoogleGroups, AdminEmail: l.GoogleAdminEmail, ServiceAccountJSON: l.GoogleServiceAccountJSON, - UseApplicationDefaultCredentials: l.GoogleUseApplicationDefaultCredentials, + UseApplicationDefaultCredentials: &l.GoogleUseApplicationDefaultCredentials, TargetPrincipal: l.GoogleTargetPrincipal, UseOrganizationID: l.GoogleUseOrganizationID, AdminAPIUserScope: l.GoogleAdminAPIUserScope, @@ -780,7 +781,7 @@ func (l *LegacyProvider) convert() (Providers, error) { case "entra-id": provider.MicrosoftEntraIDConfig = MicrosoftEntraIDOptions{ AllowedTenants: l.EntraIDAllowedTenants, - FederatedTokenAuth: l.EntraIDFederatedTokenAuth, + FederatedTokenAuth: &l.EntraIDFederatedTokenAuth, } } diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 98a89601..4348021b 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -3,6 +3,7 @@ package options import ( "time" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -26,7 +27,6 @@ var _ = Describe("Legacy Options", func() { legacyOpts.LegacyProvider.ClientID = "oauth-proxy" legacyOpts.LegacyUpstreams.DisableKeepAlives = false - truth := true staticCode := 204 opts.UpstreamServers = UpstreamConfig{ Upstreams: []Upstream{ @@ -35,35 +35,35 @@ var _ = Describe("Legacy Options", func() { Path: "/baz", URI: "http://foo.bar/baz", FlushInterval: &flushInterval, - InsecureSkipTLSVerify: true, - PassHostHeader: &truth, - ProxyWebSockets: &truth, + InsecureSkipTLSVerify: ptr.Ptr(true), + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), Timeout: &timeout, - DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, + DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, { ID: "/bar", Path: "/bar", URI: "file:///var/lib/website", FlushInterval: &flushInterval, - InsecureSkipTLSVerify: true, - PassHostHeader: &truth, - ProxyWebSockets: &truth, + InsecureSkipTLSVerify: ptr.Ptr(true), + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), Timeout: &timeout, - DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, + DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, { ID: "static://204", Path: "/", URI: "", - Static: true, + Static: ptr.Ptr(true), StaticCode: &staticCode, FlushInterval: nil, - InsecureSkipTLSVerify: false, + InsecureSkipTLSVerify: ptr.Ptr(false), PassHostHeader: nil, ProxyWebSockets: nil, Timeout: nil, - DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, + DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, }, } @@ -71,7 +71,7 @@ var _ = Describe("Legacy Options", func() { opts.InjectRequestHeaders = []Header{ { Name: "X-Forwarded-Groups", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -82,7 +82,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-User", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -93,7 +93,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-Email", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -104,7 +104,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -123,7 +123,7 @@ var _ = Describe("Legacy Options", func() { opts.Providers[0].ClientID = "oauth-proxy" opts.Providers[0].ID = "google=oauth-proxy" - opts.Providers[0].OIDCConfig.InsecureSkipNonce = true + opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.Ptr(true) opts.Providers[0].OIDCConfig.AudienceClaims = []string{"aud"} opts.Providers[0].OIDCConfig.ExtraAudiences = []string{} opts.Providers[0].LoginURLParameters = []LoginURLParameter{ @@ -157,12 +157,12 @@ var _ = Describe("Legacy Options", func() { ID: "/baz", Path: "/baz", URI: validHTTP, - InsecureSkipTLSVerify: skipVerify, + InsecureSkipTLSVerify: &skipVerify, PassHostHeader: &passHostHeader, ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, - DisableKeepAlives: disableKeepAlives, + DisableKeepAlives: &disableKeepAlives, } // Test cases and expected outcomes @@ -171,12 +171,12 @@ var _ = Describe("Legacy Options", func() { ID: "/", Path: "/", URI: emptyPathHTTP, - InsecureSkipTLSVerify: skipVerify, + InsecureSkipTLSVerify: &skipVerify, PassHostHeader: &passHostHeader, ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, - DisableKeepAlives: disableKeepAlives, + DisableKeepAlives: &disableKeepAlives, } validFileWithFragment := "file:///var/lib/website#/bar" @@ -184,12 +184,12 @@ var _ = Describe("Legacy Options", func() { ID: "/bar", Path: "/bar", URI: "file:///var/lib/website", - InsecureSkipTLSVerify: skipVerify, + InsecureSkipTLSVerify: &skipVerify, PassHostHeader: &passHostHeader, ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, - DisableKeepAlives: disableKeepAlives, + DisableKeepAlives: &disableKeepAlives, } validStatic := "static://204" @@ -198,14 +198,14 @@ var _ = Describe("Legacy Options", func() { ID: validStatic, Path: "/", URI: "", - Static: true, + Static: ptr.Ptr(true), StaticCode: &validStaticCode, - InsecureSkipTLSVerify: false, + InsecureSkipTLSVerify: ptr.Ptr(false), PassHostHeader: nil, ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, - DisableKeepAlives: false, + DisableKeepAlives: ptr.Ptr(false), } invalidStatic := "static://abc" @@ -214,14 +214,14 @@ var _ = Describe("Legacy Options", func() { ID: invalidStatic, Path: "/", URI: "", - Static: true, + Static: ptr.Ptr(true), StaticCode: &invalidStaticCode, - InsecureSkipTLSVerify: false, + InsecureSkipTLSVerify: ptr.Ptr(false), PassHostHeader: nil, ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, - DisableKeepAlives: false, + DisableKeepAlives: ptr.Ptr(false), } invalidHTTP := ":foo" @@ -308,13 +308,13 @@ var _ = Describe("Legacy Options", func() { } withPreserveRequestValue := func(h Header, preserve bool) Header { - h.PreserveRequestValue = preserve + h.PreserveRequestValue = &preserve return h } xForwardedUser := Header{ Name: "X-Forwarded-User", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -326,7 +326,7 @@ var _ = Describe("Legacy Options", func() { xForwardedEmail := Header{ Name: "X-Forwarded-Email", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -338,7 +338,7 @@ var _ = Describe("Legacy Options", func() { xForwardedGroups := Header{ Name: "X-Forwarded-Groups", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -350,7 +350,7 @@ var _ = Describe("Legacy Options", func() { xForwardedPreferredUsername := Header{ Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -362,7 +362,7 @@ var _ = Describe("Legacy Options", func() { basicAuthHeader := Header{ Name: "Authorization", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -378,7 +378,7 @@ var _ = Describe("Legacy Options", func() { xForwardedUserWithEmail := Header{ Name: "X-Forwarded-User", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -390,7 +390,7 @@ var _ = Describe("Legacy Options", func() { xForwardedAccessToken := Header{ Name: "X-Forwarded-Access-Token", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -402,7 +402,7 @@ var _ = Describe("Legacy Options", func() { basicAuthHeaderWithEmail := Header{ Name: "Authorization", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -418,7 +418,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestUser := Header{ Name: "X-Auth-Request-User", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -430,7 +430,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestEmail := Header{ Name: "X-Auth-Request-Email", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -442,7 +442,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestGroups := Header{ Name: "X-Auth-Request-Groups", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -454,7 +454,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestPreferredUsername := Header{ Name: "X-Auth-Request-Preferred-Username", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -466,7 +466,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestAccessToken := Header{ Name: "X-Auth-Request-Access-Token", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -478,7 +478,7 @@ var _ = Describe("Legacy Options", func() { authorizationHeader := Header{ Name: "Authorization", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 9ddc2a84..027464de 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -1,5 +1,7 @@ package options +import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" + const ( // OIDCEmailClaim is the generic email claim used by the OIDC provider. OIDCEmailClaim = "email" @@ -67,7 +69,7 @@ type Provider struct { CAFiles []string `yaml:"caFiles,omitempty"` // UseSystemTrustStore determines if your custom CA files and the system trust store are used // If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. - UseSystemTrustStore bool `yaml:"useSystemTrustStore"` + UseSystemTrustStore *bool `yaml:"useSystemTrustStore,omitempty"` // LoginURL is the authentication endpoint LoginURL string `yaml:"loginURL,omitempty"` // LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL @@ -80,7 +82,7 @@ type Provider struct { ProfileURL string `yaml:"profileURL,omitempty"` // SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token // default set to 'false' - SkipClaimsFromProfileURL bool `yaml:"skipClaimsFromProfileURL"` + SkipClaimsFromProfileURL *bool `yaml:"skipClaimsFromProfileURL,omitempty"` // ProtectedResource is the resource that is protected (Azure AD and ADFS only) ProtectedResource string `yaml:"resource,omitempty"` // ValidateURL is the access token validation endpoint @@ -181,13 +183,13 @@ type MicrosoftEntraIDOptions struct { // FederatedTokenAuth enable oAuth2 client authentication with federated token projected // by Entra Workload Identity plugin, instead of client secret. - FederatedTokenAuth bool `yaml:"federatedTokenAuth"` + FederatedTokenAuth *bool `yaml:"federatedTokenAuth,omitempty"` } type ADFSOptions struct { // Skip adding the scope parameter in login request // Default value is 'false' - SkipScope bool `yaml:"skipScope"` + SkipScope *bool `yaml:"skipScope,omitempty"` } type BitbucketOptions struct { @@ -227,7 +229,7 @@ type GoogleOptions struct { // ServiceAccountJSON is the path to the service account json credentials ServiceAccountJSON string `yaml:"serviceAccountJson,omitempty"` // UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON - UseApplicationDefaultCredentials bool `yaml:"useApplicationDefaultCredentials"` + UseApplicationDefaultCredentials *bool `yaml:"useApplicationDefaultCredentials,omitempty"` // TargetPrincipal is the Google Service Account used for Application Default Credentials TargetPrincipal string `yaml:"targetPrincipal,omitempty"` // UseOrganizationId indicates whether to use the organization ID as the UserName claim @@ -242,19 +244,19 @@ type OIDCOptions struct { IssuerURL string `yaml:"issuerURL,omitempty"` // InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified // default set to 'false' - InsecureAllowUnverifiedEmail bool `yaml:"insecureAllowUnverifiedEmail"` + InsecureAllowUnverifiedEmail *bool `yaml:"insecureAllowUnverifiedEmail,omitempty"` // InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL // default set to 'false' - InsecureSkipIssuerVerification bool `yaml:"insecureSkipIssuerVerification"` + InsecureSkipIssuerVerification *bool `yaml:"insecureSkipIssuerVerification,omitempty"` // InsecureSkipNonce skips verifying the ID Token's nonce claim that must match // the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked // after the initial OAuth redeem & subsequent token refreshes. // default set to 'true' // Warning: In a future release, this will change to 'false' by default for enhanced security. - InsecureSkipNonce bool `yaml:"insecureSkipNonce"` + InsecureSkipNonce *bool `yaml:"insecureSkipNonce,omitempty"` // SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints // default set to 'false' - SkipDiscovery bool `yaml:"skipDiscovery"` + SkipDiscovery *bool `yaml:"skipDiscovery,omitempty"` // JwksURL is the OpenID Connect JWKS URL // eg: https://www.googleapis.com/oauth2/v3/certs JwksURL string `yaml:"jwksURL,omitempty"` @@ -295,9 +297,9 @@ func providerDefaults() Providers { Tenant: "common", }, OIDCConfig: OIDCOptions{ - InsecureAllowUnverifiedEmail: false, - InsecureSkipNonce: true, - SkipDiscovery: false, + InsecureAllowUnverifiedEmail: ptr.Ptr(false), + InsecureSkipNonce: ptr.Ptr(true), + SkipDiscovery: ptr.Ptr(false), UserIDClaim: OIDCEmailClaim, // Deprecated: Use OIDCEmailClaim EmailClaim: OIDCEmailClaim, GroupsClaim: OIDCGroupsClaim, diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index 2b90e632..f12a4bf3 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -14,7 +14,7 @@ const ( type UpstreamConfig struct { // ProxyRawPath will pass the raw url path to upstream allowing for urls // like: "/%2F/" which would otherwise be redirected to "/" - ProxyRawPath bool `yaml:"proxyRawPath"` + ProxyRawPath *bool `yaml:"proxyRawPath,omitempty"` // Upstreams represents the configuration for the upstream servers. // Requests will be proxied to this upstream if the path matches the request path. @@ -64,13 +64,13 @@ type Upstream struct { // This option is insecure and will allow potential Man-In-The-Middle attacks // between OAuth2 Proxy and the upstream server. // Defaults to false. - InsecureSkipTLSVerify bool `yaml:"insecureSkipTLSVerify"` + InsecureSkipTLSVerify *bool `yaml:"insecureSkipTLSVerify,omitempty"` // Static will make all requests to this upstream have a static response. // The response will have a body of "Authenticated" and a response code // matching StaticCode. // If StaticCode is not set, the response will return a 200 response. - Static bool `yaml:"static"` + Static *bool `yaml:"static,omitempty"` // StaticCode determines the response code for the Static response. // This option can only be used with Static enabled. @@ -84,11 +84,11 @@ type Upstream struct { // PassHostHeader determines whether the request host header should be proxied // to the upstream server. // Defaults to true. - PassHostHeader *bool `yaml:"passHostHeader"` + PassHostHeader *bool `yaml:"passHostHeader,omitempty"` // ProxyWebSockets enables proxying of websockets to upstream servers // Defaults to true. - ProxyWebSockets *bool `yaml:"proxyWebSockets"` + ProxyWebSockets *bool `yaml:"proxyWebSockets,omitempty"` // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. @@ -96,5 +96,5 @@ type Upstream struct { // DisableKeepAlives disables HTTP keep-alive connections to the upstream server. // Defaults to false. - DisableKeepAlives bool `yaml:"disableKeepAlives,omitempty"` + DisableKeepAlives *bool `yaml:"disableKeepAlives,omitempty"` } diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index 623d50e9..d9287505 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -27,7 +27,7 @@ func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, erro func newStripHeaders(headers []options.Header) alice.Constructor { headersToStrip := []options.Header{} for _, header := range headers { - if !header.PreserveRequestValue { + if !(*header.PreserveRequestValue) { headersToStrip = append(headersToStrip, header) } } diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 6a60ec01..89f65107 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -8,6 +8,7 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -115,7 +116,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: true, + PreserveRequestValue: ptr.Ptr(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -160,7 +161,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: true, + PreserveRequestValue: ptr.Ptr(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -385,7 +386,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: true, + PreserveRequestValue: ptr.Ptr(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -432,7 +433,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: true, + PreserveRequestValue: ptr.Ptr(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index f81f4ec0..38e0e7a9 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -54,7 +54,7 @@ func newHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *option // Set up a WebSocket proxy if required var wsProxy http.Handler if upstream.ProxyWebSockets == nil || *upstream.ProxyWebSockets { - wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify) + wsProxy = newWebSocketReverseProxy(u, *upstream.InsecureSkipTLSVerify) } var auth hmacauth.HmacAuth @@ -149,7 +149,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // InsecureSkipVerify is a configurable option we allow /* #nosec G402 */ - if upstream.InsecureSkipTLSVerify { + if *upstream.InsecureSkipTLSVerify { transport.TLSClientConfig.InsecureSkipVerify = true } @@ -168,7 +168,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Pass on DisableKeepAlives to the transport settings // to allow for disabling HTTP keep-alive connections - transport.DisableKeepAlives = upstream.DisableKeepAlives + transport.DisableKeepAlives = *upstream.DisableKeepAlives // Apply the customized transport to our proxy before returning it proxy.Transport = transport diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index df264c33..7c1831bf 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -15,6 +15,7 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "golang.org/x/net/websocket" @@ -23,8 +24,6 @@ import ( var _ = Describe("HTTP Upstream Suite", func() { defaultFlushInterval := options.DefaultUpstreamFlushInterval defaultTimeout := options.DefaultUpstreamTimeout - truth := true - falsum := false type httpUpstreamTableInput struct { id string @@ -64,8 +63,8 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: in.id, PassHostHeader: &in.passUpstreamHostHeader, - ProxyWebSockets: &falsum, - InsecureSkipTLSVerify: false, + ProxyWebSockets: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.Ptr(false), FlushInterval: &flush, Timeout: &timeout, } @@ -343,9 +342,9 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: "noPassHost", - PassHostHeader: &falsum, - ProxyWebSockets: &falsum, - InsecureSkipTLSVerify: false, + PassHostHeader: ptr.Ptr(false), + ProxyWebSockets: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.Ptr(false), FlushInterval: &defaultFlushInterval, Timeout: &defaultTimeout, } @@ -389,10 +388,10 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: "foo123", FlushInterval: &in.flushInterval, - InsecureSkipTLSVerify: in.skipVerify, + InsecureSkipTLSVerify: &in.skipVerify, ProxyWebSockets: &in.proxyWebSockets, Timeout: &in.timeout, - DisableKeepAlives: in.disableKeepAlives, + DisableKeepAlives: &in.disableKeepAlives, } handler := newHTTPUpstreamProxy(upstream, u, in.sigData, in.errorHandler) @@ -487,9 +486,9 @@ var _ = Describe("HTTP Upstream Suite", func() { timeout := options.DefaultUpstreamTimeout upstream := options.Upstream{ ID: "websocketProxy", - PassHostHeader: &truth, - ProxyWebSockets: &truth, - InsecureSkipTLSVerify: false, + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), + InsecureSkipTLSVerify: ptr.Ptr(false), FlushInterval: &flush, Timeout: &timeout, } diff --git a/pkg/upstream/proxy.go b/pkg/upstream/proxy.go index 74b0d02d..0d2286ea 100644 --- a/pkg/upstream/proxy.go +++ b/pkg/upstream/proxy.go @@ -27,12 +27,12 @@ func NewProxy(upstreams options.UpstreamConfig, sigData *options.SignatureData, serveMux: mux.NewRouter(), } - if upstreams.ProxyRawPath { + if *upstreams.ProxyRawPath { m.serveMux.UseEncodedPath() } for _, upstream := range sortByPathLongest(upstreams.Upstreams) { - if upstream.Static { + if *upstream.Static { if err := m.registerStaticResponseHandler(upstream, writer); err != nil { return nil, fmt.Errorf("could not register static upstream %q: %v", upstream.ID, err) } diff --git a/pkg/upstream/proxy_test.go b/pkg/upstream/proxy_test.go index 5252bd42..87aae7fa 100644 --- a/pkg/upstream/proxy_test.go +++ b/pkg/upstream/proxy_test.go @@ -10,6 +10,7 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/app/pagewriter" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -60,19 +61,19 @@ var _ = Describe("Proxy Suite", func() { { ID: "static-backend", Path: "/static/", - Static: true, + Static: ptr.Ptr(true), StaticCode: &ok, }, { ID: "static-backend-no-trailing-slash", Path: "/static", - Static: true, + Static: ptr.Ptr(true), StaticCode: &accepted, }, { ID: "static-backend-long", Path: "/static/long", - Static: true, + Static: ptr.Ptr(true), StaticCode: &accepted, }, { @@ -83,7 +84,7 @@ var _ = Describe("Proxy Suite", func() { { ID: "single-path-backend", Path: "/single-path", - Static: true, + Static: ptr.Ptr(true), StaticCode: &ok, }, { @@ -346,7 +347,7 @@ var _ = Describe("Proxy Suite", func() { upstream: "", }), Entry("containing an escaped '/' with ProxyRawPath", &proxyTableInput{ - upstreams: options.UpstreamConfig{ProxyRawPath: true}, + upstreams: options.UpstreamConfig{ProxyRawPath: ptr.Ptr(true)}, target: "http://example.localhost/%2F/test1/%2F/test2", response: testHTTPResponse{ code: 404, diff --git a/pkg/util/ptr/ptr.go b/pkg/util/ptr/ptr.go new file mode 100644 index 00000000..9242773c --- /dev/null +++ b/pkg/util/ptr/ptr.go @@ -0,0 +1,14 @@ +package ptr + +// Ptr generically returns a pointer to the given value. +func Ptr[T any](v T) *T { + return &v +} + +// Deref returns the value of the pointer or def(ault) if nil. +func Deref[T any](p *T, def T) T { + if p == nil { + return def + } + return *p +} diff --git a/pkg/util/ptr/ptr_test.go b/pkg/util/ptr/ptr_test.go new file mode 100644 index 00000000..c4817a6b --- /dev/null +++ b/pkg/util/ptr/ptr_test.go @@ -0,0 +1,38 @@ +package ptr + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestPtr(t *testing.T) { + p := Ptr(42) + assert.NotNil(t, p) + assert.Equal(t, 42, *p) + + s := Ptr("hello") + assert.NotNil(t, s) + assert.Equal(t, "hello", *s) + + b := Ptr(true) + assert.NotNil(t, b) + assert.True(t, *b) +} + +func TestDeref(t *testing.T) { + v := Deref(Ptr(99), 0) + assert.Equal(t, 99, v) + + v = Deref[int](nil, 123) + assert.Equal(t, 123, v) + + s := Deref[string](nil, "default") + assert.Equal(t, "default", s) + + b := Deref(Ptr(true), false) + assert.True(t, b) + + b = Deref[bool](nil, false) + assert.False(t, b) +} diff --git a/pkg/validation/options.go b/pkg/validation/options.go index 0f648d6c..d5aba4e4 100644 --- a/pkg/validation/options.go +++ b/pkg/validation/options.go @@ -34,7 +34,7 @@ func Validate(o *options.Options) error { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402 -- InsecureSkipVerify is a configurable option we allow } else if len(o.Providers[0].CAFiles) > 0 { - pool, err := util.GetCertPool(o.Providers[0].CAFiles, o.Providers[0].UseSystemTrustStore) + pool, err := util.GetCertPool(o.Providers[0].CAFiles, *o.Providers[0].UseSystemTrustStore) if err == nil { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{ diff --git a/pkg/validation/options_test.go b/pkg/validation/options_test.go index 5c283545..6657e847 100644 --- a/pkg/validation/options_test.go +++ b/pkg/validation/options_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/stretchr/testify/assert" ) @@ -68,7 +69,7 @@ func TestGoogleGroupOptionsWithoutServiceAccountJSON(t *testing.T) { func TestGoogleGroupOptionsWithoutAdminEmail(t *testing.T) { o := testOptions() - o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = true + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.Ptr(true) err := Validate(o) assert.NotEqual(t, nil, err) @@ -81,7 +82,7 @@ func TestGoogleGroupOptionsWithoutGroups(t *testing.T) { o := testOptions() // Set admin email and application default credentials but no groups - should still require them o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" - o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = true + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.Ptr(true) err := Validate(o) // Should pass validation since google-group is now optional assert.Equal(t, nil, err) diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index 4527b841..3abf69d4 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -5,6 +5,7 @@ import ( "os" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // validateProviders is the initial validation migration for multiple providrers @@ -64,7 +65,7 @@ func validateProvider(provider options.Provider, providerIDs map[string]struct{} // providerRequiresClientSecret checks if provider requires client secret to be set // or it can be omitted in favor of JWT token to authenticate oAuth client func providerRequiresClientSecret(provider options.Provider) bool { - if provider.Type == "entra-id" && provider.MicrosoftEntraIDConfig.FederatedTokenAuth { + if provider.Type == "entra-id" && *provider.MicrosoftEntraIDConfig.FederatedTokenAuth { return false } @@ -96,7 +97,7 @@ func validateGoogleConfig(provider options.Provider) []string { hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" - useADC := provider.GoogleConfig.UseApplicationDefaultCredentials + useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, false) if !hasAdminEmail && !hasSAJSON && !useADC { return msgs @@ -123,7 +124,7 @@ func validateGoogleConfig(provider options.Provider) []string { func validateEntraConfig(provider options.Provider) []string { msgs := []string{} - if provider.MicrosoftEntraIDConfig.FederatedTokenAuth { + if *provider.MicrosoftEntraIDConfig.FederatedTokenAuth { federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") if federatedTokenPath == "" { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 52facb4d..05d441e3 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -54,19 +54,19 @@ func validateUpstream(upstream options.Upstream, ids, paths map[string]struct{}) func validateStaticUpstream(upstream options.Upstream) []string { msgs := []string{} - if !upstream.Static && upstream.StaticCode != nil { + if !*upstream.Static && upstream.StaticCode != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has staticCode (%d), but is not a static upstream, set 'static' for a static response", upstream.ID, *upstream.StaticCode)) } // Checks after this only make sense when the upstream is static - if !upstream.Static { + if !*upstream.Static { return msgs } if upstream.URI != "" { msgs = append(msgs, fmt.Sprintf("upstream %q has uri, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.InsecureSkipTLSVerify { + if *upstream.InsecureSkipTLSVerify { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { @@ -85,13 +85,13 @@ func validateStaticUpstream(upstream options.Upstream) []string { func validateUpstreamURI(upstream options.Upstream) []string { msgs := []string{} - if !upstream.Static && upstream.URI == "" { + if !*upstream.Static && upstream.URI == "" { msgs = append(msgs, fmt.Sprintf("upstream %q has empty uri: uris are required for all non-static upstreams", upstream.ID)) return msgs } // Checks after this only make sense the upstream is not static - if upstream.Static { + if *upstream.Static { return msgs } diff --git a/pkg/validation/upstreams_test.go b/pkg/validation/upstreams_test.go index 67991b76..580e2f29 100644 --- a/pkg/validation/upstreams_test.go +++ b/pkg/validation/upstreams_test.go @@ -4,6 +4,7 @@ import ( "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -16,7 +17,6 @@ var _ = Describe("Upstreams", func() { flushInterval := 5 * time.Second staticCode200 := 200 - truth := true validHTTPUpstream := options.Upstream{ ID: "validHTTPUpstream", @@ -26,7 +26,7 @@ var _ = Describe("Upstreams", func() { validStaticUpstream := options.Upstream{ ID: "validStaticUpstream", Path: "/validStaticUpstream", - Static: true, + Static: ptr.Ptr(true), } validFileUpstream := options.Upstream{ ID: "validFileUpstream", @@ -145,11 +145,11 @@ var _ = Describe("Upstreams", func() { ID: "foo", Path: "/foo", URI: "ftp://foo", - Static: true, + Static: ptr.Ptr(true), FlushInterval: &flushInterval, - PassHostHeader: &truth, - ProxyWebSockets: &truth, - InsecureSkipTLSVerify: true, + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), + InsecureSkipTLSVerify: ptr.Ptr(true), }, }, }, diff --git a/providers/adfs.go b/providers/adfs.go index 0facfdcf..6615f38c 100644 --- a/providers/adfs.go +++ b/providers/adfs.go @@ -50,7 +50,7 @@ func NewADFSProvider(p *ProviderData, opts options.Provider) *ADFSProvider { return &ADFSProvider{ OIDCProvider: oidcProvider, - skipScope: opts.ADFSConfig.SkipScope, + skipScope: *opts.ADFSConfig.SkipScope, oidcEnrichFunc: oidcProvider.EnrichSession, oidcRefreshFunc: oidcProvider.RefreshSession, } diff --git a/providers/adfs_test.go b/providers/adfs_test.go index 0b730430..edcb9307 100755 --- a/providers/adfs_test.go +++ b/providers/adfs_test.go @@ -16,6 +16,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -172,7 +173,7 @@ var _ = Describe("ADFS Provider Tests", func() { ProtectedResource: resource, Scope: "", }, options.Provider{ - ADFSConfig: options.ADFSOptions{SkipScope: true}, + ADFSConfig: options.ADFSOptions{SkipScope: ptr.Ptr(true)}, }) result := p.GetLoginURL("https://example.com/adfs/oauth2/", "", "", url.Values{}) diff --git a/providers/google.go b/providers/google.go index a6a9d283..64102ebc 100644 --- a/providers/google.go +++ b/providers/google.go @@ -108,7 +108,8 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv }, } - if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { + if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || *opts.UseApplicationDefaultCredentials { + provider.configureGroups(opts) // reuse admin service to avoid multiple calls for token var adminService *admin.Service @@ -304,7 +305,7 @@ var possibleScopesList = [...]string{ } func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope string) oauth2.TokenSource { - if opts.UseApplicationDefaultCredentials { + if *opts.UseApplicationDefaultCredentials { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), Scopes: strings.Split(scope, " "), diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go index df1f38a4..752f9f44 100644 --- a/providers/ms_entra_id.go +++ b/providers/ms_entra_id.go @@ -51,7 +51,7 @@ func NewMicrosoftEntraIDProvider(p *ProviderData, opts options.Provider) *Micros OIDCProvider: NewOIDCProvider(p, opts.OIDCConfig), multiTenantAllowedTenants: opts.MicrosoftEntraIDConfig.AllowedTenants, - federatedTokenAuth: opts.MicrosoftEntraIDConfig.FederatedTokenAuth, + federatedTokenAuth: *opts.MicrosoftEntraIDConfig.FederatedTokenAuth, microsoftGraphURL: microsoftGraphURL, } } diff --git a/providers/ms_entra_id_test.go b/providers/ms_entra_id_test.go index dfd1ef99..7b720c91 100644 --- a/providers/ms_entra_id_test.go +++ b/providers/ms_entra_id_test.go @@ -13,6 +13,7 @@ import ( "github.com/coreos/go-oidc/v3/oidc" "github.com/golang-jwt/jwt/v5" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/stretchr/testify/assert" . "github.com/onsi/gomega" @@ -24,7 +25,7 @@ func TestAzureEntraOIDCProviderNewMultiTenant(t *testing.T) { provider := NewMicrosoftEntraIDProvider(&ProviderData{}, options.Provider{OIDCConfig: options.OIDCOptions{ IssuerURL: "https://login.microsoftonline.com/common/v2.0", - InsecureSkipIssuerVerification: true, + InsecureSkipIssuerVerification: ptr.Ptr(true), }}, ) g.Expect(provider.Data().ProviderName).To(Equal("Microsoft Entra ID")) @@ -90,8 +91,8 @@ func TestAzureEntraOIDCProviderValidateSessionAllowedTenants(t *testing.T) { options.Provider{ OIDCConfig: options.OIDCOptions{ IssuerURL: "https://login.microsoftonline.com/common/v2.0", - InsecureSkipIssuerVerification: true, - InsecureSkipNonce: true, + InsecureSkipIssuerVerification: ptr.Ptr(true), + InsecureSkipNonce: ptr.Ptr(true), }, MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ AllowedTenants: []string{"85d7d600-7804-4d92-8d43-9c33c21c130c"}, diff --git a/providers/oidc.go b/providers/oidc.go index eeac4073..fa65e839 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -50,7 +50,7 @@ func NewOIDCProvider(p *ProviderData, opts options.OIDCOptions) *OIDCProvider { return &OIDCProvider{ ProviderData: p, - SkipNonce: opts.InsecureSkipNonce, + SkipNonce: *opts.InsecureSkipNonce, } } diff --git a/providers/oidc_test.go b/providers/oidc_test.go index 81a70eb4..61f4762e 100644 --- a/providers/oidc_test.go +++ b/providers/oidc_test.go @@ -63,7 +63,7 @@ func newOIDCProvider(serverURL *url.URL, skipNonce bool) *OIDCProvider { } p := NewOIDCProvider(providerData, options.OIDCOptions{ - InsecureSkipNonce: skipNonce, + InsecureSkipNonce: &skipNonce, }) return p diff --git a/providers/providers.go b/providers/providers.go index ec00f412..84f5ec91 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -98,8 +98,8 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, IssuerURL: providerConfig.OIDCConfig.IssuerURL, JWKsURL: providerConfig.OIDCConfig.JwksURL, PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles, - SkipDiscovery: providerConfig.OIDCConfig.SkipDiscovery, - SkipIssuerVerification: providerConfig.OIDCConfig.InsecureSkipIssuerVerification, + SkipDiscovery: *providerConfig.OIDCConfig.SkipDiscovery, + SkipIssuerVerification: *providerConfig.OIDCConfig.InsecureSkipIssuerVerification, }) if err != nil { return nil, fmt.Errorf("error building OIDC ProviderVerifier: %v", err) @@ -143,10 +143,10 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, } // Make the OIDC options available to all providers that support it - p.AllowUnverifiedEmail = providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail + p.AllowUnverifiedEmail = *providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail p.EmailClaim = providerConfig.OIDCConfig.EmailClaim p.GroupsClaim = providerConfig.OIDCConfig.GroupsClaim - p.SkipClaimsFromProfileURL = providerConfig.SkipClaimsFromProfileURL + p.SkipClaimsFromProfileURL = *providerConfig.SkipClaimsFromProfileURL // Set PKCE enabled or disabled based on discovery and force options p.CodeChallengeMethod = parseCodeChallengeMethod(providerConfig) diff --git a/providers/providers_test.go b/providers/providers_test.go index 82961d84..9591dc65 100644 --- a/providers/providers_test.go +++ b/providers/providers_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/gomega" ) @@ -81,7 +82,7 @@ func TestSkipOIDCDiscovery(t *testing.T) { ClientSecretFile: clientSecret, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: true, + SkipDiscovery: ptr.Ptr(true), }, } @@ -108,7 +109,7 @@ func TestURLsCorrectlyParsed(t *testing.T) { RedeemURL: msTokenURL, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: true, + SkipDiscovery: ptr.Ptr(true), JwksURL: msKeysURL, }, } @@ -216,7 +217,7 @@ func TestScope(t *testing.T) { AllowedGroups: tc.allowedGroups, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: true, + SkipDiscovery: ptr.Ptr(true), JwksURL: msKeysURL, }, } @@ -297,7 +298,7 @@ func TestEmailClaimCorrectlySet(t *testing.T) { RedeemURL: msTokenURL, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: true, + SkipDiscovery: ptr.Ptr(true), JwksURL: msKeysURL, UserIDClaim: tc.userIDClaim, EmailClaim: tc.emailClaim, From 51b1fd0510973af134e128c65f5689dab0f10177 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 30 Oct 2025 08:36:13 +0100 Subject: [PATCH 123/130] chore(deps): replace with forked official yaml library Signed-off-by: Jan Larwig --- go.mod | 78 ++++++++-------- go.sum | 194 ++++++++++++++++++++++----------------- main.go | 2 +- pkg/apis/options/load.go | 2 +- 4 files changed, 151 insertions(+), 125 deletions(-) diff --git a/go.mod b/go.mod index be7de03b..99195a4e 100644 --- a/go.mod +++ b/go.mod @@ -3,56 +3,57 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 go 1.25.3 require ( - cloud.google.com/go/compute/metadata v0.7.0 + cloud.google.com/go/compute/metadata v0.9.0 github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb github.com/a8m/envsubst v1.4.3 github.com/alicebob/miniredis/v2 v2.35.0 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 - github.com/coreos/go-oidc/v3 v3.14.1 + github.com/coreos/go-oidc/v3 v3.16.0 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 github.com/go-jose/go-jose/v3 v3.0.4 github.com/go-viper/mapstructure/v2 v2.4.0 - github.com/golang-jwt/jwt/v5 v5.2.3 + github.com/golang-jwt/jwt/v5 v5.3.0 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.23.4 - github.com/onsi/gomega v1.38.0 + github.com/onsi/ginkgo/v2 v2.27.2 + github.com/onsi/gomega v1.38.2 github.com/pierrec/lz4/v4 v4.1.22 - github.com/prometheus/client_golang v1.22.0 - github.com/redis/go-redis/v9 v9.11.0 - github.com/spf13/cast v1.9.2 - github.com/spf13/pflag v1.0.7 - github.com/spf13/viper v1.20.1 + github.com/prometheus/client_golang v1.23.2 + github.com/redis/go-redis/v9 v9.16.0 + github.com/spf13/cast v1.10.0 + github.com/spf13/pflag v1.0.10 + github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 - golang.org/x/crypto v0.40.0 - golang.org/x/net v0.42.0 - golang.org/x/oauth2 v0.30.0 - golang.org/x/sync v0.16.0 - google.golang.org/api v0.243.0 + go.yaml.in/yaml/v3 v3.0.4 + golang.org/x/crypto v0.43.0 + golang.org/x/net v0.46.0 + golang.org/x/oauth2 v0.32.0 + golang.org/x/sync v0.17.0 + google.golang.org/api v0.254.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - gopkg.in/yaml.v3 v3.0.1 - k8s.io/apimachinery v0.33.3 + k8s.io/apimachinery v0.34.1 ) require ( - cloud.google.com/go/auth v0.16.3 // indirect + cloud.google.com/go/auth v0.17.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect + github.com/Masterminds/semver/v3 v3.4.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/go-jose/go-jose/v4 v4.1.1 // indirect + github.com/go-jose/go-jose/v4 v4.1.3 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 // indirect + github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect github.com/googleapis/gax-go/v2 v2.15.0 // indirect @@ -61,26 +62,25 @@ require ( github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.65.0 // indirect - github.com/prometheus/procfs v0.17.0 // indirect - github.com/rogpeppe/go-internal v1.14.1 // indirect - github.com/sagikazarmark/locafero v0.9.0 // indirect - github.com/sourcegraph/conc v0.3.0 // indirect - github.com/spf13/afero v1.14.0 // indirect + github.com/prometheus/common v0.67.2 // indirect + github.com/prometheus/procfs v0.19.1 // indirect + github.com/sagikazarmark/locafero v0.12.0 // indirect + github.com/spf13/afero v1.15.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 // indirect - go.opentelemetry.io/otel v1.37.0 // indirect - go.opentelemetry.io/otel/metric v1.37.0 // indirect - go.opentelemetry.io/otel/trace v1.37.0 // indirect - go.uber.org/automaxprocs v1.6.0 // indirect - go.uber.org/multierr v1.11.0 // indirect - golang.org/x/sys v0.34.0 // indirect - golang.org/x/text v0.27.0 // indirect - golang.org/x/tools v0.35.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074 // indirect - google.golang.org/grpc v1.74.2 // indirect - google.golang.org/protobuf v1.36.6 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect + go.opentelemetry.io/otel v1.38.0 // indirect + go.opentelemetry.io/otel/metric v1.38.0 // indirect + go.opentelemetry.io/otel/trace v1.38.0 // indirect + go.yaml.in/yaml/v2 v2.4.3 // indirect + golang.org/x/mod v0.29.0 // indirect + golang.org/x/sys v0.37.0 // indirect + golang.org/x/text v0.30.0 // indirect + golang.org/x/tools v0.38.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda // indirect + google.golang.org/grpc v1.76.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 09282969..8344be12 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,15 @@ -cloud.google.com/go/auth v0.16.3 h1:kabzoQ9/bobUmnseYnBO6qQG7q4a/CffFRlJSxv2wCc= -cloud.google.com/go/auth v0.16.3/go.mod h1:NucRGjaXfzP1ltpcQ7On/VTZ0H4kWB5Jy+Y9Dnm76fA= +cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4= +cloud.google.com/go/auth v0.17.0/go.mod h1:6wv/t5/6rOPAX4fJiRjKkJCvswLwdet7G8+UGXt7nCQ= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= -cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU= -cloud.google.com/go/compute/metadata v0.7.0/go.mod h1:j5MvL9PprKL39t166CoB1uVHfQMs4tFQZZcKwksXUjo= +cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb h1:ZVN4Iat3runWOFLaBCDVU5a9X/XikSRBosye++6gojw= github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb/go.mod h1:WsAABbY4HQBgd3mGuG4KMNTbHJCPvx9IVBHzysbknss= github.com/FZambia/sentinel v1.0.0 h1:KJ0ryjKTZk5WMp0dXvSdNqp3lFaW1fNFuEYfrkLOYIc= github.com/FZambia/sentinel v1.0.0/go.mod h1:ytL1Am/RLlAoAXG6Kj5LNuw/TRRQrv2rt2FT26vP5gI= +github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= +github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY= github.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU= github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= @@ -29,8 +31,8 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk= -github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= +github.com/coreos/go-oidc/v3 v3.16.0 h1:qRQUCFstKpXwmEjDQTIbyY/5jF00+asXzSkmkoa/mow= +github.com/coreos/go-oidc/v3 v3.16.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -44,10 +46,16 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs= +github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo= +github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M= +github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk= +github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE= +github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= -github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI= -github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA= +github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= +github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -57,8 +65,10 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= -github.com/golang-jwt/jwt/v5 v5.2.3 h1:kkGXqQOBSDDWRhWNXTFpqGSCMyh/PLnqUvMGJPDJDs0= -github.com/golang-jwt/jwt/v5 v5.2.3/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= +github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= +github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY= @@ -66,8 +76,8 @@ github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85q github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 h1:xhMrHhTJ6zxu3gA4enFM9MLn9AY7613teCdFnlUVbSQ= -github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5/go.mod h1:5hDyRhoBCxViHszMt12TnOpEI4VVi+U8Gm9iphldiMA= +github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d h1:KJIErDwbSHjnp/SGzE5ed8Aol7JsKiI5X7yWKAtzhM0= +github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -79,6 +89,8 @@ github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81 github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= +github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= +github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung= github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo= github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= @@ -89,16 +101,20 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/maruel/natural v1.1.1 h1:Hja7XhhmvEFhcByqDoHz9QZbkWey+COd9xWfCfn1ioo= +github.com/maruel/natural v1.1.1/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= +github.com/mfridman/tparse v0.18.0 h1:wh6dzOKaIwkUGyKgOntDW4liXSo37qg5AXbIhkMV3vE= +github.com/mfridman/tparse v0.18.0/go.mod h1:gEvqZTuCgEhPbYk/2lS3Kcxg1GmTxxU7kTC8DvP0i/A= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus= -github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8= -github.com/onsi/gomega v1.38.0 h1:c/WX+w8SLAinvuKKQFh77WEucCnPk4j2OTUr7lt7BeY= -github.com/onsi/gomega v1.38.0/go.mod h1:OcXcwId0b9QsE7Y49u+BTrL4IdKOBOKnD6VQNTJEB6o= +github.com/onsi/ginkgo/v2 v2.27.2 h1:LzwLj0b89qtIy6SSASkzlNvX6WktqurSHwkk2ipF/Ns= +github.com/onsi/ginkgo/v2 v2.27.2/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= +github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A= +github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= @@ -106,38 +122,42 @@ github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFu github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g= -github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= -github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= -github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= +github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= +github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE= -github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8= -github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0= -github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw= -github.com/redis/go-redis/v9 v9.11.0 h1:E3S08Gl/nJNn5vkxd2i78wZxWAPNZgUNTp8WIJUAiIs= -github.com/redis/go-redis/v9 v9.11.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= +github.com/prometheus/common v0.67.2 h1:PcBAckGFTIHt2+L3I33uNRTlKTplNzFctXcWhPyAEN8= +github.com/prometheus/common v0.67.2/go.mod h1:63W3KZb1JOKgcjlIr64WW/LvFGAqKPj0atm+knVGEko= +github.com/prometheus/procfs v0.19.1 h1:QVtROpTkphuXuNlnCv3m1ut3JytkXHtQ3xvck/YmzMM= +github.com/prometheus/procfs v0.19.1/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= +github.com/redis/go-redis/v9 v9.16.0 h1:OotgqgLSRCmzfqChbQyG1PHC3tLNR89DG4jdOERSEP4= +github.com/redis/go-redis/v9 v9.16.0/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k= -github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk= -github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= -github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA= -github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo= -github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= -github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= -github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M= -github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= -github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= +github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= +github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= +github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= +github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= @@ -147,47 +167,51 @@ github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBU github.com/yuin/gopher-lua v0.0.0-20191213034115-f46add6fdb5c/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ= github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 h1:Hf9xI/XLML9ElpiHVDNwvqI0hIFlzV8dgIr35kV1kRU= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0/go.mod h1:NfchwuyNoMcZ5MLHwPrODwUF1HWCXWrL31s8gSAdIKY= -go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ= -go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I= -go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE= -go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E= -go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI= -go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg= -go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc= -go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps= -go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4= -go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0= -go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= -go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= -go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= -go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= +go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= +go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= +go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= +go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= +go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= +go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= +go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= +go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= +go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= +go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= -golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= +golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= +golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= +golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= -golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= -golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= -golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= +golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= +golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= +golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= +golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= -golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -197,8 +221,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= -golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= +golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -210,29 +234,31 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= -golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= -golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= -golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= +golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= -golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= +golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= +golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.243.0 h1:sw+ESIJ4BVnlJcWu9S+p2Z6Qq1PjG77T8IJ1xtp4jZQ= -google.golang.org/api v0.243.0/go.mod h1:GE4QtYfaybx1KmeHMdBnNnyLzBZCVihGBXAmJu/uUr8= +gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= +gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= +google.golang.org/api v0.254.0 h1:jl3XrGj7lRjnlUvZAbAdhINTLbsg5dbjmR90+pTQvt4= +google.golang.org/api v0.254.0/go.mod h1:5BkSURm3D9kAqjGvBNgf0EcbX6Rnrf6UArKkwBzAyqQ= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= -google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822/go.mod h1:h3c4v36UTKzUiuaOKQ6gr3S+0hovBtUrXzTG/i3+XEc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074 h1:qJW29YvkiJmXOYMu5Tf8lyrTp3dOS+K4z6IixtLaCf8= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= -google.golang.org/grpc v1.74.2 h1:WoosgB65DlWVC9FqI82dGsZhWFNBSLjQ84bjROOpMu4= -google.golang.org/grpc v1.74.2/go.mod h1:CtQ+BGjaAIXHs/5YS3i473GqwBBa1zGQNevxdeBEXrM= -google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= -google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= +google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b h1:ULiyYQ0FdsJhwwZUwbaXpZF5yUE3h+RA+gxvBu37ucc= +google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:oDOGiMSXHL4sDTJvFvIB9nRQCGdLP1o/iVaqQK8zB+M= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda h1:i/Q+bfisr7gq6feoJnS/DlpdwEL4ihp41fvRiM3Ork0= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/grpc v1.76.0 h1:UnVkv1+uMLYXoIz6o7chp59WfQUYA2ex/BXQ9rHZu7A= +google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -241,5 +267,5 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/apimachinery v0.33.3 h1:4ZSrmNa0c/ZpZJhAgRdcsFcZOw1PQU1bALVQ0B3I5LA= -k8s.io/apimachinery v0.33.3/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= +k8s.io/apimachinery v0.34.1 h1:dTlxFls/eikpJxmAC7MVE8oOeP1zryV7iRyIjB0gky4= +k8s.io/apimachinery v0.34.1/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw= diff --git a/main.go b/main.go index 1525e94c..12ca2739 100644 --- a/main.go +++ b/main.go @@ -10,7 +10,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version" "github.com/spf13/pflag" - "gopkg.in/yaml.v3" + "go.yaml.in/yaml/v3" ) func main() { diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index fdd20c7a..20d04383 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -12,7 +12,7 @@ import ( "github.com/go-viper/mapstructure/v2" "github.com/spf13/pflag" "github.com/spf13/viper" - "gopkg.in/yaml.v3" + "go.yaml.in/yaml/v3" ) // Load reads in the config file at the path given, then merges in environment From 527c72f23f5aeceeb9cc4b3e7dd10fdaab8d67c2 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 30 Oct 2025 09:26:14 +0100 Subject: [PATCH 124/130] feat: add ensure defaults to all migrated structs Signed-off-by: Jan Larwig --- main.go | 6 ++- main_test.go | 9 +--- pkg/apis/middleware/session.go | 3 +- pkg/apis/options/alpha_options.go | 6 +-- pkg/apis/options/header.go | 27 ++++++++++ pkg/apis/options/legacy_options.go | 4 -- pkg/apis/options/legacy_options_test.go | 3 +- pkg/apis/options/options.go | 20 +++++++ pkg/apis/options/providers.go | 70 +++++++++++++++++++++++++ pkg/apis/options/secret_source.go | 5 ++ pkg/apis/options/upstreams.go | 41 ++++++++++++++- pkg/upstream/http.go | 11 ++-- pkg/validation/providers.go | 7 ++- pkg/validation/upstreams.go | 10 ++-- 14 files changed, 189 insertions(+), 33 deletions(-) diff --git a/main.go b/main.go index 12ca2739..7e18b95f 100644 --- a/main.go +++ b/main.go @@ -20,7 +20,7 @@ func main() { // Because we parse early to determine alpha vs legacy config, we have to // ignore any unknown flags for now - configFlagSet.ParseErrorsWhitelist.UnknownFlags = true + configFlagSet.ParseErrorsAllowlist.UnknownFlags = true config := configFlagSet.String("config", "", "path to config file") alphaConfig := configFlagSet.String("alpha-config", "", "path to alpha config file (use at your own risk - the structure in this config file may change between minor releases)") @@ -78,6 +78,8 @@ func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, arg return loadYamlOptions(yamlConfig, config, extraFlags, args) } + opts.EnsureDefaults() + return opts, nil } @@ -117,7 +119,7 @@ func loadYamlOptions(yamlConfig, config string, extraFlags *pflag.FlagSet, args return nil, fmt.Errorf("failed to load alpha options: %v", err) } - alphaOpts.MergeInto(opts) + alphaOpts.MergeOptionsWithDefaults(opts) return opts, nil } diff --git a/main_test.go b/main_test.go index b9ec39fb..0323c838 100644 --- a/main_test.go +++ b/main_test.go @@ -3,7 +3,6 @@ package main import ( "errors" "os" - "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil" @@ -114,10 +113,6 @@ cookie_secure="false" redirect_url="http://localhost:4180/oauth2/callback" ` - durationPtr := func(d time.Duration) *time.Duration { - return &d - } - testExpectedOptions := func() *options.Options { opts, err := options.NewLegacyOptions().ToOptions() Expect(err).ToNot(HaveOccurred()) @@ -133,10 +128,10 @@ redirect_url="http://localhost:4180/oauth2/callback" ID: "/", Path: "/", URI: "http://httpbin", - FlushInterval: durationPtr(options.DefaultUpstreamFlushInterval), + FlushInterval: ptr.Ptr(options.DefaultUpstreamFlushInterval), PassHostHeader: ptr.Ptr(true), ProxyWebSockets: ptr.Ptr(true), - Timeout: durationPtr(options.DefaultUpstreamTimeout), + Timeout: ptr.Ptr(options.DefaultUpstreamTimeout), InsecureSkipTLSVerify: ptr.Ptr(false), DisableKeepAlives: ptr.Ptr(false), }, diff --git a/pkg/apis/middleware/session.go b/pkg/apis/middleware/session.go index 9fcd974b..e17c0249 100644 --- a/pkg/apis/middleware/session.go +++ b/pkg/apis/middleware/session.go @@ -6,6 +6,7 @@ import ( "github.com/coreos/go-oidc/v3/oidc" sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // TokenToSessionFunc takes a raw ID Token and converts it into a SessionState. @@ -40,7 +41,7 @@ func CreateTokenToSessionFunc(verify VerifyFunc) TokenToSessionFunc { claims.Email = claims.Subject } - if claims.Verified != nil && !*claims.Verified { + if !ptr.Deref(claims.Verified, false) { return nil, fmt.Errorf("email in id_token (%s) isn't verified", claims.Email) } diff --git a/pkg/apis/options/alpha_options.go b/pkg/apis/options/alpha_options.go index 0c78359a..33daf17f 100644 --- a/pkg/apis/options/alpha_options.go +++ b/pkg/apis/options/alpha_options.go @@ -65,9 +65,9 @@ func (a *AlphaOptions) ExtractFrom(opts *Options) { a.Providers = opts.Providers } -// MergeInto replaces alpha options in the Options struct with the values -// from the AlphaOptions -func (a *AlphaOptions) MergeInto(opts *Options) { +// MergeOptionsWithDefaults replaces alpha options in the Options struct +// with the values from the AlphaOptions and ensures the defaults +func (a *AlphaOptions) MergeOptionsWithDefaults(opts *Options) { opts.UpstreamServers = a.UpstreamConfig opts.InjectRequestHeaders = a.InjectRequestHeaders opts.InjectResponseHeaders = a.InjectResponseHeaders diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 048b1974..a47e8a95 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -1,5 +1,7 @@ package options +import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" + // Header represents an individual header that will be added to a request or // response header. type Header struct { @@ -53,3 +55,28 @@ type ClaimSource struct { // basicAuthPassword will be used as the password value. BasicAuthPassword *SecretSource `yaml:"basicAuthPassword,omitempty"` } + +// EnsureDefaults sets any default values for Header fields. +func (h *Header) EnsureDefaults() { + if h.PreserveRequestValue == nil { + h.PreserveRequestValue = ptr.Ptr(false) + } + for i := range h.Values { + h.Values[i].EnsureDefaults() + } +} + +// EnsureDefaults sets any default values for HeaderValue fields. +func (hv *HeaderValue) EnsureDefaults() { + if hv.ClaimSource != nil { + hv.ClaimSource.EnsureDefaults() + } + if hv.SecretSource != nil { + hv.SecretSource.EnsureDefaults() + } +} + +// EnsureDefaults sets any default values for ClaimSource fields. +func (hc *ClaimSource) EnsureDefaults() { + // No defaults to set currently +} diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 672d6c63..ffd98bd1 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -177,10 +177,6 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { // Force defaults compatible with static responses upstream.URI = "" upstream.InsecureSkipTLSVerify = ptr.Ptr(false) - upstream.PassHostHeader = nil - upstream.ProxyWebSockets = nil - upstream.FlushInterval = nil - upstream.Timeout = nil upstream.DisableKeepAlives = ptr.Ptr(false) case "unix": upstream.Path = "/" diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 4348021b..cc2a76e5 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -3,6 +3,7 @@ package options import ( "time" + . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -132,7 +133,7 @@ var _ = Describe("Legacy Options", func() { converted, err := legacyOpts.ToOptions() Expect(err).ToNot(HaveOccurred()) - Expect(converted).To(Equal(opts)) + Expect(converted).To(EqualOpts(opts)) }) }) diff --git a/pkg/apis/options/options.go b/pkg/apis/options/options.go index 8fa72c7c..b57d5aed 100644 --- a/pkg/apis/options/options.go +++ b/pkg/apis/options/options.go @@ -168,3 +168,23 @@ func NewFlagSet() *pflag.FlagSet { return flagSet } + +// EnsureDefaults configures the defaults for all options +// to ensure no unexpected empty strings for enum types or nils for booleans +func (o *Options) EnsureDefaults() { + o.Providers.EnsureDefaults() + o.UpstreamServers.EnsureDefaults() + + for i := range o.InjectRequestHeaders { + o.InjectRequestHeaders[i].EnsureDefaults() + } + for i := range o.InjectResponseHeaders { + o.InjectResponseHeaders[i].EnsureDefaults() + } + + // TBD: Uncomment as we add EnsureDefaults methods + // o.Cookie.EnsureDefaults() + // o.Session.EnsureDefaults() + // o.Templates.EnsureDefaults() + // o.Logging.EnsureDefaults() +} diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 027464de..ed836656 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -289,6 +289,7 @@ type LoginGovOptions struct { PubJWKURL string `yaml:"pubjwkURL,omitempty"` } +// Legacy default providers configuration func providerDefaults() Providers { providers := Providers{ { @@ -310,3 +311,72 @@ func providerDefaults() Providers { } return providers } + +// EnsureDefaults sets any default values for Providers fields. +func (p Providers) EnsureDefaults() { + for i := range p { + p[i].EnsureDefaults() + } +} + +// EnsureDefaults sets any default values for Provider fields. +func (p *Provider) EnsureDefaults() { + if p.SkipClaimsFromProfileURL == nil { + p.SkipClaimsFromProfileURL = ptr.Ptr(false) + } + if p.UseSystemTrustStore == nil { + p.UseSystemTrustStore = ptr.Ptr(true) + } + + p.OIDCConfig.EnsureDefaults() + p.MicrosoftEntraIDConfig.EnsureDefaults() + p.ADFSConfig.EnsureDefaults() + p.GoogleConfig.EnsureDefaults() +} + +// EnsureDefaults sets any default values for OIDCOptions fields. +func (o *OIDCOptions) EnsureDefaults() { + // Ensure OIDC defaults + if o.InsecureAllowUnverifiedEmail == nil { + o.InsecureAllowUnverifiedEmail = ptr.Ptr(false) + } + if o.InsecureSkipNonce == nil { + o.InsecureSkipNonce = ptr.Ptr(true) + } + if o.SkipDiscovery == nil { + o.SkipDiscovery = ptr.Ptr(false) + } + if o.UserIDClaim == "" { + o.UserIDClaim = OIDCEmailClaim + } + if o.EmailClaim == "" { + o.EmailClaim = OIDCEmailClaim + } + if o.GroupsClaim == "" { + o.GroupsClaim = OIDCGroupsClaim + } + if len(o.AudienceClaims) == 0 { + o.AudienceClaims = OIDCAudienceClaims + } +} + +// EnsureDefaults sets any default values for MicrosoftEntraIDOptions fields. +func (me *MicrosoftEntraIDOptions) EnsureDefaults() { + if me.FederatedTokenAuth == nil { + me.FederatedTokenAuth = ptr.Ptr(false) + } +} + +// EnsureDefaults sets any default values for ADFSOptions fields. +func (a *ADFSOptions) EnsureDefaults() { + if a.SkipScope == nil { + a.SkipScope = ptr.Ptr(false) + } +} + +// EnsureDefaults sets any default values for GoogleOptions fields. +func (g *GoogleOptions) EnsureDefaults() { + if g.UseApplicationDefaultCredentials == nil { + g.UseApplicationDefaultCredentials = ptr.Ptr(false) + } +} diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go index 848f1635..8b783342 100644 --- a/pkg/apis/options/secret_source.go +++ b/pkg/apis/options/secret_source.go @@ -12,3 +12,8 @@ type SecretSource struct { // FromFile expects a path to a file containing the secret value. FromFile string `yaml:"fromFile,omitempty"` } + +// EnsureDefaults sets any default values for SecretSource fields. +func (ss *SecretSource) EnsureDefaults() { + // No defaults to set currently +} diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index f12a4bf3..05c12e03 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -1,6 +1,10 @@ package options -import "time" +import ( + "time" + + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" +) const ( // DefaultUpstreamFlushInterval is the default value for the Upstream FlushInterval. @@ -98,3 +102,38 @@ type Upstream struct { // Defaults to false. DisableKeepAlives *bool `yaml:"disableKeepAlives,omitempty"` } + +// EnsureDefaults sets any default values for UpstreamConfig fields. +func (uc *UpstreamConfig) EnsureDefaults() { + if uc.ProxyRawPath == nil { + uc.ProxyRawPath = ptr.Ptr(false) + } + for i := range uc.Upstreams { + uc.Upstreams[i].EnsureDefaults() + } +} + +// EnsureDefaults sets any default values for Upstream fields. +func (u *Upstream) EnsureDefaults() { + if u.InsecureSkipTLSVerify == nil { + u.InsecureSkipTLSVerify = ptr.Ptr(false) + } + if u.Static == nil { + u.Static = ptr.Ptr(false) + } + if u.FlushInterval == nil { + u.FlushInterval = ptr.Ptr(DefaultUpstreamFlushInterval) + } + if u.PassHostHeader == nil { + u.PassHostHeader = ptr.Ptr(true) + } + if u.ProxyWebSockets == nil { + u.ProxyWebSockets = ptr.Ptr(true) + } + if u.Timeout == nil { + u.Timeout = ptr.Ptr(DefaultUpstreamTimeout) + } + if u.DisableKeepAlives == nil { + u.DisableKeepAlives = ptr.Ptr(false) + } +} diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 38e0e7a9..59580ee3 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -11,6 +11,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) const ( @@ -53,8 +54,8 @@ func newHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *option // Set up a WebSocket proxy if required var wsProxy http.Handler - if upstream.ProxyWebSockets == nil || *upstream.ProxyWebSockets { - wsProxy = newWebSocketReverseProxy(u, *upstream.InsecureSkipTLSVerify) + if *upstream.ProxyWebSockets { + wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify) } var auth hmacauth.HmacAuth @@ -156,7 +157,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Ensure we always pass the original request path setProxyDirector(proxy) - if upstream.PassHostHeader != nil && !*upstream.PassHostHeader { + if upstream.PassHostHeader != nil && !(*upstream.PassHostHeader) { setProxyUpstreamHostHeader(proxy, target) } @@ -200,14 +201,14 @@ func setProxyDirector(proxy *httputil.ReverseProxy) { } // newWebSocketReverseProxy creates a new reverse proxy for proxying websocket connections. -func newWebSocketReverseProxy(u *url.URL, skipTLSVerify bool) http.Handler { +func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool) http.Handler { wsProxy := httputil.NewSingleHostReverseProxy(u) // Inherit default transport options from Go's stdlib transport := http.DefaultTransport.(*http.Transport).Clone() /* #nosec G402 */ - if skipTLSVerify { + if ptr.Deref(skipTLSVerify, false) { transport.TLSClientConfig.InsecureSkipVerify = true } diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index 3abf69d4..345274d8 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -5,7 +5,6 @@ import ( "os" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // validateProviders is the initial validation migration for multiple providrers @@ -97,9 +96,9 @@ func validateGoogleConfig(provider options.Provider) []string { hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" - useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, false) + useADC := provider.GoogleConfig.UseApplicationDefaultCredentials - if !hasAdminEmail && !hasSAJSON && !useADC { + if !hasAdminEmail && !hasSAJSON && !(*useADC) { return msgs } @@ -108,7 +107,7 @@ func validateGoogleConfig(provider options.Provider) []string { } _, err := os.Stat(provider.GoogleConfig.ServiceAccountJSON) - if !useADC { + if !(*useADC) { if !hasSAJSON { msgs = append(msgs, "missing setting: google-service-account-json or google-use-application-default-credentials") } else if err != nil { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 05d441e3..2750e22c 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -54,12 +54,12 @@ func validateUpstream(upstream options.Upstream, ids, paths map[string]struct{}) func validateStaticUpstream(upstream options.Upstream) []string { msgs := []string{} - if !*upstream.Static && upstream.StaticCode != nil { + if !(*upstream.Static) && upstream.StaticCode != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has staticCode (%d), but is not a static upstream, set 'static' for a static response", upstream.ID, *upstream.StaticCode)) } // Checks after this only make sense when the upstream is static - if !*upstream.Static { + if !(*upstream.Static) { return msgs } @@ -72,10 +72,10 @@ func validateStaticUpstream(upstream options.Upstream) []string { if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.PassHostHeader != nil { + if *upstream.PassHostHeader { msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.ProxyWebSockets != nil { + if *upstream.ProxyWebSockets { msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID)) } @@ -85,7 +85,7 @@ func validateStaticUpstream(upstream options.Upstream) []string { func validateUpstreamURI(upstream options.Upstream) []string { msgs := []string{} - if !*upstream.Static && upstream.URI == "" { + if !(*upstream.Static) && upstream.URI == "" { msgs = append(msgs, fmt.Sprintf("upstream %q has empty uri: uris are required for all non-static upstreams", upstream.ID)) return msgs } From ceb9a387b12b06230e4e03fef67edbb4931bc1a1 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 31 Oct 2025 16:11:54 +0100 Subject: [PATCH 125/130] deref everything... but why? Signed-off-by: Jan Larwig --- main.go | 7 +++++-- main_test.go | 17 ++++++++++++----- pkg/middleware/headers.go | 3 ++- pkg/upstream/http.go | 8 ++++---- pkg/upstream/proxy.go | 7 ++++--- pkg/upstream/static.go | 13 ++----------- pkg/validation/options.go | 3 ++- pkg/validation/providers.go | 11 ++++++----- pkg/validation/upstreams.go | 17 +++++++++-------- providers/adfs.go | 3 ++- providers/google.go | 9 ++++----- providers/ms_entra_id.go | 3 ++- providers/oidc.go | 3 ++- providers/providers.go | 9 +++++---- 14 files changed, 61 insertions(+), 52 deletions(-) diff --git a/main.go b/main.go index 7e18b95f..42e8bab0 100644 --- a/main.go +++ b/main.go @@ -75,11 +75,14 @@ func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, arg if yamlConfig != "" { logger.Printf("WARNING: You are using alpha configuration. The structure in this configuration file may change without notice. You MUST remove conflicting options from your existing configuration.") - return loadYamlOptions(yamlConfig, config, extraFlags, args) + opts, err = loadYamlOptions(yamlConfig, config, extraFlags, args) + if err != nil { + return nil, fmt.Errorf("failed to load yaml options: %w", err) + } } + // Ensure defaults after loading configuration opts.EnsureDefaults() - return opts, nil } diff --git a/main_test.go b/main_test.go index 0323c838..1d9102d7 100644 --- a/main_test.go +++ b/main_test.go @@ -123,6 +123,7 @@ redirect_url="http://localhost:4180/oauth2/callback" opts.RawRedirectURL = "http://localhost:4180/oauth2/callback" opts.UpstreamServers = options.UpstreamConfig{ + ProxyRawPath: ptr.Ptr(false), Upstreams: []options.Upstream{ { ID: "/", @@ -132,6 +133,7 @@ redirect_url="http://localhost:4180/oauth2/callback" PassHostHeader: ptr.Ptr(true), ProxyWebSockets: ptr.Ptr(true), Timeout: ptr.Ptr(options.DefaultUpstreamTimeout), + Static: ptr.Ptr(false), InsecureSkipTLSVerify: ptr.Ptr(false), DisableKeepAlives: ptr.Ptr(false), }, @@ -139,7 +141,8 @@ redirect_url="http://localhost:4180/oauth2/callback" } authHeader := options.Header{ - Name: "Authorization", + Name: "Authorization", + PreserveRequestValue: ptr.Ptr(false), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -153,10 +156,7 @@ redirect_url="http://localhost:4180/oauth2/callback" }, } - authHeader.PreserveRequestValue = ptr.Ptr(false) opts.InjectRequestHeaders = append([]options.Header{authHeader}, opts.InjectRequestHeaders...) - - authHeader.PreserveRequestValue = nil opts.InjectResponseHeaders = append(opts.InjectResponseHeaders, authHeader) opts.Providers = options.Providers{ @@ -186,6 +186,12 @@ redirect_url="http://localhost:4180/oauth2/callback" InsecureSkipIssuerVerification: ptr.Ptr(false), SkipDiscovery: ptr.Ptr(false), }, + MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ + FederatedTokenAuth: ptr.Ptr(false), + }, + ADFSConfig: options.ADFSOptions{ + SkipScope: ptr.Ptr(false), + }, LoginURLParameters: []options.LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, }, @@ -254,7 +260,8 @@ redirect_url="http://localhost:4180/oauth2/callback" Expect(err).ToNot(HaveOccurred()) } Expect(in.expectedOptions).ToNot(BeNil()) - Expect(opts).To(EqualOpts(in.expectedOptions())) + expectedOpts := in.expectedOptions() + Expect(opts).To(EqualOpts(expectedOpts)) }, Entry("with legacy configuration", loadConfigurationTableInput{ configContent: testCoreConfig + testLegacyConfig, diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index d9287505..ed82a30b 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -9,6 +9,7 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/header" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, error) { @@ -27,7 +28,7 @@ func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, erro func newStripHeaders(headers []options.Header) alice.Constructor { headersToStrip := []options.Header{} for _, header := range headers { - if !(*header.PreserveRequestValue) { + if !ptr.Deref(header.PreserveRequestValue, false) { headersToStrip = append(headersToStrip, header) } } diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 59580ee3..9c33f96c 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -54,7 +54,7 @@ func newHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *option // Set up a WebSocket proxy if required var wsProxy http.Handler - if *upstream.ProxyWebSockets { + if ptr.Deref(upstream.ProxyWebSockets, false) { wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify) } @@ -150,14 +150,14 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // InsecureSkipVerify is a configurable option we allow /* #nosec G402 */ - if *upstream.InsecureSkipTLSVerify { + if ptr.Deref(upstream.InsecureSkipTLSVerify, false) { transport.TLSClientConfig.InsecureSkipVerify = true } // Ensure we always pass the original request path setProxyDirector(proxy) - if upstream.PassHostHeader != nil && !(*upstream.PassHostHeader) { + if !ptr.Deref(upstream.PassHostHeader, false) { setProxyUpstreamHostHeader(proxy, target) } @@ -169,7 +169,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Pass on DisableKeepAlives to the transport settings // to allow for disabling HTTP keep-alive connections - transport.DisableKeepAlives = *upstream.DisableKeepAlives + transport.DisableKeepAlives = ptr.Deref(upstream.DisableKeepAlives, false) // Apply the customized transport to our proxy before returning it proxy.Transport = transport diff --git a/pkg/upstream/proxy.go b/pkg/upstream/proxy.go index 0d2286ea..acf24d1a 100644 --- a/pkg/upstream/proxy.go +++ b/pkg/upstream/proxy.go @@ -14,6 +14,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/app/pagewriter" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // ProxyErrorHandler is a function that will be used to render error pages when @@ -27,12 +28,12 @@ func NewProxy(upstreams options.UpstreamConfig, sigData *options.SignatureData, serveMux: mux.NewRouter(), } - if *upstreams.ProxyRawPath { + if ptr.Deref(upstreams.ProxyRawPath, false) { m.serveMux.UseEncodedPath() } for _, upstream := range sortByPathLongest(upstreams.Upstreams) { - if *upstream.Static { + if ptr.Deref(upstream.Static, false) { if err := m.registerStaticResponseHandler(upstream, writer); err != nil { return nil, fmt.Errorf("could not register static upstream %q: %v", upstream.ID, err) } @@ -74,7 +75,7 @@ func (m *multiUpstreamProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request // registerStaticResponseHandler registers a static response handler with at the given path. func (m *multiUpstreamProxy) registerStaticResponseHandler(upstream options.Upstream, writer pagewriter.Writer) error { - logger.Printf("mapping path %q => static response %d", upstream.Path, derefStaticCode(upstream.StaticCode)) + logger.Printf("mapping path %q => static response %d", upstream.Path, ptr.Deref(upstream.StaticCode, 200)) return m.registerHandler(upstream, newStaticResponseHandler(upstream.ID, upstream.StaticCode), writer) } diff --git a/pkg/upstream/static.go b/pkg/upstream/static.go index 027f3e74..d7d037bf 100644 --- a/pkg/upstream/static.go +++ b/pkg/upstream/static.go @@ -6,15 +6,14 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) -const defaultStaticResponseCode = 200 - // newStaticResponseHandler creates a new staticResponseHandler that serves a // a static response code. func newStaticResponseHandler(upstream string, code *int) http.Handler { return &staticResponseHandler{ - code: derefStaticCode(code), + code: ptr.Deref(code, 200), upstream: upstream, } } @@ -38,11 +37,3 @@ func (s *staticResponseHandler) ServeHTTP(rw http.ResponseWriter, req *http.Requ logger.Errorf("Error writing static response: %v", err) } } - -// derefStaticCode returns the derefenced value, or the default if the value is nil -func derefStaticCode(code *int) int { - if code != nil { - return *code - } - return defaultStaticResponseCode -} diff --git a/pkg/validation/options.go b/pkg/validation/options.go index d5aba4e4..ffb0accc 100644 --- a/pkg/validation/options.go +++ b/pkg/validation/options.go @@ -15,6 +15,7 @@ import ( internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // Validate checks that required options are set and validates those that they @@ -34,7 +35,7 @@ func Validate(o *options.Options) error { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402 -- InsecureSkipVerify is a configurable option we allow } else if len(o.Providers[0].CAFiles) > 0 { - pool, err := util.GetCertPool(o.Providers[0].CAFiles, *o.Providers[0].UseSystemTrustStore) + pool, err := util.GetCertPool(o.Providers[0].CAFiles, ptr.Deref(o.Providers[0].UseSystemTrustStore, false)) if err == nil { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{ diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index 345274d8..1acdee65 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -5,6 +5,7 @@ import ( "os" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // validateProviders is the initial validation migration for multiple providrers @@ -64,7 +65,7 @@ func validateProvider(provider options.Provider, providerIDs map[string]struct{} // providerRequiresClientSecret checks if provider requires client secret to be set // or it can be omitted in favor of JWT token to authenticate oAuth client func providerRequiresClientSecret(provider options.Provider) bool { - if provider.Type == "entra-id" && *provider.MicrosoftEntraIDConfig.FederatedTokenAuth { + if provider.Type == "entra-id" && ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, false) { return false } @@ -96,9 +97,9 @@ func validateGoogleConfig(provider options.Provider) []string { hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" - useADC := provider.GoogleConfig.UseApplicationDefaultCredentials + useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, false) - if !hasAdminEmail && !hasSAJSON && !(*useADC) { + if !hasAdminEmail && !hasSAJSON && !useADC { return msgs } @@ -107,7 +108,7 @@ func validateGoogleConfig(provider options.Provider) []string { } _, err := os.Stat(provider.GoogleConfig.ServiceAccountJSON) - if !(*useADC) { + if !useADC { if !hasSAJSON { msgs = append(msgs, "missing setting: google-service-account-json or google-use-application-default-credentials") } else if err != nil { @@ -123,7 +124,7 @@ func validateGoogleConfig(provider options.Provider) []string { func validateEntraConfig(provider options.Provider) []string { msgs := []string{} - if *provider.MicrosoftEntraIDConfig.FederatedTokenAuth { + if ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, false) { federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") if federatedTokenPath == "" { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 2750e22c..4c537678 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -5,6 +5,7 @@ import ( "net/url" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) func validateUpstreams(upstreams options.UpstreamConfig) []string { @@ -54,28 +55,28 @@ func validateUpstream(upstream options.Upstream, ids, paths map[string]struct{}) func validateStaticUpstream(upstream options.Upstream) []string { msgs := []string{} - if !(*upstream.Static) && upstream.StaticCode != nil { + if !ptr.Deref(upstream.Static, false) && upstream.StaticCode != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has staticCode (%d), but is not a static upstream, set 'static' for a static response", upstream.ID, *upstream.StaticCode)) } // Checks after this only make sense when the upstream is static - if !(*upstream.Static) { + if !ptr.Deref(upstream.Static, false) { return msgs } if upstream.URI != "" { msgs = append(msgs, fmt.Sprintf("upstream %q has uri, but is a static upstream, this will have no effect.", upstream.ID)) } - if *upstream.InsecureSkipTLSVerify { + if ptr.Deref(upstream.InsecureSkipTLSVerify, false) { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { + if ptr.Deref(upstream.FlushInterval, options.DefaultUpstreamFlushInterval) != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } - if *upstream.PassHostHeader { + if ptr.Deref(upstream.PassHostHeader, false) { msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID)) } - if *upstream.ProxyWebSockets { + if ptr.Deref(upstream.ProxyWebSockets, false) { msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID)) } @@ -85,13 +86,13 @@ func validateStaticUpstream(upstream options.Upstream) []string { func validateUpstreamURI(upstream options.Upstream) []string { msgs := []string{} - if !(*upstream.Static) && upstream.URI == "" { + if !ptr.Deref(upstream.Static, false) && upstream.URI == "" { msgs = append(msgs, fmt.Sprintf("upstream %q has empty uri: uris are required for all non-static upstreams", upstream.ID)) return msgs } // Checks after this only make sense the upstream is not static - if *upstream.Static { + if !ptr.Deref(upstream.Static, false) { return msgs } diff --git a/providers/adfs.go b/providers/adfs.go index 6615f38c..ebf91f71 100644 --- a/providers/adfs.go +++ b/providers/adfs.go @@ -8,6 +8,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // ADFSProvider represents an ADFS based Identity Provider @@ -50,7 +51,7 @@ func NewADFSProvider(p *ProviderData, opts options.Provider) *ADFSProvider { return &ADFSProvider{ OIDCProvider: oidcProvider, - skipScope: *opts.ADFSConfig.SkipScope, + skipScope: ptr.Deref(opts.ADFSConfig.SkipScope, false), oidcEnrichFunc: oidcProvider.EnrichSession, oidcRefreshFunc: oidcProvider.RefreshSession, } diff --git a/providers/google.go b/providers/google.go index 64102ebc..ac38980f 100644 --- a/providers/google.go +++ b/providers/google.go @@ -19,6 +19,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "golang.org/x/oauth2" "golang.org/x/oauth2/google" admin "google.golang.org/api/admin/directory/v1" @@ -108,9 +109,7 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv }, } - if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || *opts.UseApplicationDefaultCredentials { - provider.configureGroups(opts) - + if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, false) { // reuse admin service to avoid multiple calls for token var adminService *admin.Service @@ -133,7 +132,7 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv } } - if opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { + if opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, false) { if adminService == nil { adminService = getAdminService(opts) } @@ -305,7 +304,7 @@ var possibleScopesList = [...]string{ } func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope string) oauth2.TokenSource { - if *opts.UseApplicationDefaultCredentials { + if ptr.Deref(opts.UseApplicationDefaultCredentials, false) { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), Scopes: strings.Split(scope, " "), diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go index 752f9f44..57c4fae1 100644 --- a/providers/ms_entra_id.go +++ b/providers/ms_entra_id.go @@ -16,6 +16,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/spf13/cast" "golang.org/x/oauth2" ) @@ -51,7 +52,7 @@ func NewMicrosoftEntraIDProvider(p *ProviderData, opts options.Provider) *Micros OIDCProvider: NewOIDCProvider(p, opts.OIDCConfig), multiTenantAllowedTenants: opts.MicrosoftEntraIDConfig.AllowedTenants, - federatedTokenAuth: *opts.MicrosoftEntraIDConfig.FederatedTokenAuth, + federatedTokenAuth: ptr.Deref(opts.MicrosoftEntraIDConfig.FederatedTokenAuth, false), microsoftGraphURL: microsoftGraphURL, } } diff --git a/providers/oidc.go b/providers/oidc.go index fa65e839..5e28039d 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -12,6 +12,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "golang.org/x/oauth2" ) @@ -50,7 +51,7 @@ func NewOIDCProvider(p *ProviderData, opts options.OIDCOptions) *OIDCProvider { return &OIDCProvider{ ProviderData: p, - SkipNonce: *opts.InsecureSkipNonce, + SkipNonce: ptr.Deref(opts.InsecureSkipNonce, false), } } diff --git a/providers/providers.go b/providers/providers.go index 84f5ec91..1c7ac652 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -9,6 +9,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" k8serrors "k8s.io/apimachinery/pkg/util/errors" ) @@ -98,8 +99,8 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, IssuerURL: providerConfig.OIDCConfig.IssuerURL, JWKsURL: providerConfig.OIDCConfig.JwksURL, PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles, - SkipDiscovery: *providerConfig.OIDCConfig.SkipDiscovery, - SkipIssuerVerification: *providerConfig.OIDCConfig.InsecureSkipIssuerVerification, + SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, false), + SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, false), }) if err != nil { return nil, fmt.Errorf("error building OIDC ProviderVerifier: %v", err) @@ -143,10 +144,10 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, } // Make the OIDC options available to all providers that support it - p.AllowUnverifiedEmail = *providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail + p.AllowUnverifiedEmail = ptr.Deref(providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail, false) p.EmailClaim = providerConfig.OIDCConfig.EmailClaim p.GroupsClaim = providerConfig.OIDCConfig.GroupsClaim - p.SkipClaimsFromProfileURL = *providerConfig.SkipClaimsFromProfileURL + p.SkipClaimsFromProfileURL = ptr.Deref(providerConfig.SkipClaimsFromProfileURL, false) // Set PKCE enabled or disabled based on discovery and force options p.CodeChallengeMethod = parseCodeChallengeMethod(providerConfig) From 638fba417f25c4c9fd09fc0de6a4fa44b2555b95 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 7 Nov 2025 22:31:48 +0100 Subject: [PATCH 126/130] deref everything but now with default constants Signed-off-by: Jan Larwig --- pkg/apis/options/header.go | 7 +++- pkg/apis/options/providers.go | 62 +++++++++++++++++++++++++++-------- pkg/apis/options/upstreams.go | 38 ++++++++++++++++----- pkg/middleware/headers.go | 2 +- pkg/upstream/http.go | 8 ++--- pkg/upstream/proxy.go | 6 ++-- pkg/upstream/static.go | 3 +- pkg/validation/options.go | 2 +- pkg/validation/providers.go | 6 ++-- pkg/validation/upstreams.go | 14 ++++---- providers/adfs.go | 2 +- providers/adfs_test.go | 0 providers/google.go | 6 ++-- providers/ms_entra_id.go | 2 +- providers/oidc.go | 2 +- providers/providers.go | 8 ++--- 16 files changed, 116 insertions(+), 52 deletions(-) mode change 100755 => 100644 providers/adfs_test.go diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index a47e8a95..a3595508 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -2,6 +2,11 @@ package options import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" +const ( + // DefaultHeaderPreserveRequestValue is the default value for Header.PreserveRequestValue + DefaultHeaderPreserveRequestValue bool = false +) + // Header represents an individual header that will be added to a request or // response header. type Header struct { @@ -59,7 +64,7 @@ type ClaimSource struct { // EnsureDefaults sets any default values for Header fields. func (h *Header) EnsureDefaults() { if h.PreserveRequestValue == nil { - h.PreserveRequestValue = ptr.Ptr(false) + h.PreserveRequestValue = ptr.Ptr(DefaultHeaderPreserveRequestValue) } for i := range h.Values { h.Values[i].EnsureDefaults() diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index ed836656..e8c39226 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -4,10 +4,46 @@ import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" const ( // OIDCEmailClaim is the generic email claim used by the OIDC provider. - OIDCEmailClaim = "email" + OIDCEmailClaim string = "email" // OIDCGroupsClaim is the generic groups claim used by the OIDC provider. - OIDCGroupsClaim = "groups" + OIDCGroupsClaim string = "groups" + + // DefaultSkipDiscovery is the default value + // for OIDCOptions.SkipDiscovery + DefaultSkipDiscovery bool = false + + // DefaultInsecureSkipNonce is the default value + // for OIDCOptions.InsecureSkipNonce + DefaultInsecureSkipNonce bool = true + + // DefaultInsecureAllowUnverifiedEmail is the default value + // for OIDCOptions.InsecureAllowUnverifiedEmail + DefaultInsecureAllowUnverifiedEmail bool = false + + // DefaultInsecureSkipIssuerVerification is the default value + // for OIDCOptions.InsecureSkipIssuerVerification + DefaultInsecureSkipIssuerVerification bool = false + + // DefaultSkipClaimsFromProfileURL is the default value + // for Provider.SkipClaimsFromProfileURL + DefaultSkipClaimsFromProfileURL bool = false + + // DefaultADFSSkipScope is the default value + // for ADFSOptions.SkipScope + DefaultADFSSkipScope bool = false + + // DefaultMicrosoftEntraIDUseFederatedToken is the default value + // for MicrosoftEntraIDOptions.FederatedTokenAuth + DefaultMicrosoftEntraIDUseFederatedToken bool = false + + // DefaultGoogleUseApplicationDefaultCredentials is the default values + // for GoogleOptions.UseApplicationDefaultCredentials + DefaultUseApplicationDefaultCredentials bool = false + + // DefaultUseSystemTrustStore is the default value + // for Provider.UseSystemTrustStore + DefaultUseSystemTrustStore bool = true ) // OIDCAudienceClaims is the generic audience claim list used by the OIDC provider. @@ -298,9 +334,9 @@ func providerDefaults() Providers { Tenant: "common", }, OIDCConfig: OIDCOptions{ - InsecureAllowUnverifiedEmail: ptr.Ptr(false), - InsecureSkipNonce: ptr.Ptr(true), - SkipDiscovery: ptr.Ptr(false), + InsecureAllowUnverifiedEmail: ptr.Ptr(DefaultInsecureAllowUnverifiedEmail), + InsecureSkipNonce: ptr.Ptr(DefaultInsecureSkipNonce), + SkipDiscovery: ptr.Ptr(DefaultSkipDiscovery), UserIDClaim: OIDCEmailClaim, // Deprecated: Use OIDCEmailClaim EmailClaim: OIDCEmailClaim, GroupsClaim: OIDCGroupsClaim, @@ -322,10 +358,10 @@ func (p Providers) EnsureDefaults() { // EnsureDefaults sets any default values for Provider fields. func (p *Provider) EnsureDefaults() { if p.SkipClaimsFromProfileURL == nil { - p.SkipClaimsFromProfileURL = ptr.Ptr(false) + p.SkipClaimsFromProfileURL = ptr.Ptr(DefaultSkipClaimsFromProfileURL) } if p.UseSystemTrustStore == nil { - p.UseSystemTrustStore = ptr.Ptr(true) + p.UseSystemTrustStore = ptr.Ptr(DefaultUseSystemTrustStore) } p.OIDCConfig.EnsureDefaults() @@ -338,13 +374,13 @@ func (p *Provider) EnsureDefaults() { func (o *OIDCOptions) EnsureDefaults() { // Ensure OIDC defaults if o.InsecureAllowUnverifiedEmail == nil { - o.InsecureAllowUnverifiedEmail = ptr.Ptr(false) + o.InsecureAllowUnverifiedEmail = ptr.Ptr(DefaultInsecureAllowUnverifiedEmail) } if o.InsecureSkipNonce == nil { - o.InsecureSkipNonce = ptr.Ptr(true) + o.InsecureSkipNonce = ptr.Ptr(DefaultInsecureSkipNonce) } if o.SkipDiscovery == nil { - o.SkipDiscovery = ptr.Ptr(false) + o.SkipDiscovery = ptr.Ptr(DefaultSkipDiscovery) } if o.UserIDClaim == "" { o.UserIDClaim = OIDCEmailClaim @@ -363,20 +399,20 @@ func (o *OIDCOptions) EnsureDefaults() { // EnsureDefaults sets any default values for MicrosoftEntraIDOptions fields. func (me *MicrosoftEntraIDOptions) EnsureDefaults() { if me.FederatedTokenAuth == nil { - me.FederatedTokenAuth = ptr.Ptr(false) + me.FederatedTokenAuth = ptr.Ptr(DefaultMicrosoftEntraIDUseFederatedToken) } } // EnsureDefaults sets any default values for ADFSOptions fields. func (a *ADFSOptions) EnsureDefaults() { if a.SkipScope == nil { - a.SkipScope = ptr.Ptr(false) + a.SkipScope = ptr.Ptr(DefaultADFSSkipScope) } } // EnsureDefaults sets any default values for GoogleOptions fields. func (g *GoogleOptions) EnsureDefaults() { if g.UseApplicationDefaultCredentials == nil { - g.UseApplicationDefaultCredentials = ptr.Ptr(false) + g.UseApplicationDefaultCredentials = ptr.Ptr(DefaultUseApplicationDefaultCredentials) } } diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index 05c12e03..f69fec90 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -1,6 +1,7 @@ package options import ( + "net/http" "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" @@ -8,10 +9,31 @@ import ( const ( // DefaultUpstreamFlushInterval is the default value for the Upstream FlushInterval. - DefaultUpstreamFlushInterval = 1 * time.Second + DefaultUpstreamFlushInterval time.Duration = 1 * time.Second // DefaultUpstreamTimeout is the maximum duration a network dial to a upstream server for a response. - DefaultUpstreamTimeout = 30 * time.Second + DefaultUpstreamTimeout time.Duration = 30 * time.Second + + // DefaultUpstreamStatic determines if upstreams are static by default. + DefaultUpstreamStatic bool = false + + // DefaultUpstreamStaticCode is the default response code for static upstreams. + DefaultUpstreamStaticCode int = http.StatusOK // 200 + + // DefaultUpstreamProxyRawPath determines if upstreams will proxy the raw url path by default. + DefaultUpstreamProxyRawPath bool = false + + // DefaultUpstreamInsecureSkipTLSVerify determines if upstreams will skip TLS verification by default. + DefaultUpsteamInsecureSkipTLSVerify bool = false + + // DefaultUpstreamPassHostHeader determines if upstreams will pass the host header by default. + DefaultUpstreamPassHostHeader bool = true + + // DefaultUpstreamProxyWebSockets determines if upstreams will proxy websockets by default. + DefaultUpstreamProxyWebSockets bool = true + + // DefaultUpstreamDisableKeepAlives determines if upstreams will disable keep-alives by default. + DefaultUpstreamDisableKeepAlives bool = false ) // UpstreamConfig is a collection of definitions for upstream servers. @@ -106,7 +128,7 @@ type Upstream struct { // EnsureDefaults sets any default values for UpstreamConfig fields. func (uc *UpstreamConfig) EnsureDefaults() { if uc.ProxyRawPath == nil { - uc.ProxyRawPath = ptr.Ptr(false) + uc.ProxyRawPath = ptr.Ptr(DefaultUpstreamProxyRawPath) } for i := range uc.Upstreams { uc.Upstreams[i].EnsureDefaults() @@ -116,24 +138,24 @@ func (uc *UpstreamConfig) EnsureDefaults() { // EnsureDefaults sets any default values for Upstream fields. func (u *Upstream) EnsureDefaults() { if u.InsecureSkipTLSVerify == nil { - u.InsecureSkipTLSVerify = ptr.Ptr(false) + u.InsecureSkipTLSVerify = ptr.Ptr(DefaultUpsteamInsecureSkipTLSVerify) } if u.Static == nil { - u.Static = ptr.Ptr(false) + u.Static = ptr.Ptr(DefaultUpstreamStatic) } if u.FlushInterval == nil { u.FlushInterval = ptr.Ptr(DefaultUpstreamFlushInterval) } if u.PassHostHeader == nil { - u.PassHostHeader = ptr.Ptr(true) + u.PassHostHeader = ptr.Ptr(DefaultUpstreamPassHostHeader) } if u.ProxyWebSockets == nil { - u.ProxyWebSockets = ptr.Ptr(true) + u.ProxyWebSockets = ptr.Ptr(DefaultUpstreamProxyWebSockets) } if u.Timeout == nil { u.Timeout = ptr.Ptr(DefaultUpstreamTimeout) } if u.DisableKeepAlives == nil { - u.DisableKeepAlives = ptr.Ptr(false) + u.DisableKeepAlives = ptr.Ptr(DefaultUpstreamDisableKeepAlives) } } diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index ed82a30b..b567f4f5 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -28,7 +28,7 @@ func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, erro func newStripHeaders(headers []options.Header) alice.Constructor { headersToStrip := []options.Header{} for _, header := range headers { - if !ptr.Deref(header.PreserveRequestValue, false) { + if !ptr.Deref(header.PreserveRequestValue, options.DefaultHeaderPreserveRequestValue) { headersToStrip = append(headersToStrip, header) } } diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 9c33f96c..e8283144 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -54,7 +54,7 @@ func newHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *option // Set up a WebSocket proxy if required var wsProxy http.Handler - if ptr.Deref(upstream.ProxyWebSockets, false) { + if ptr.Deref(upstream.ProxyWebSockets, options.DefaultUpstreamProxyWebSockets) { wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify) } @@ -150,14 +150,14 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // InsecureSkipVerify is a configurable option we allow /* #nosec G402 */ - if ptr.Deref(upstream.InsecureSkipTLSVerify, false) { + if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) { transport.TLSClientConfig.InsecureSkipVerify = true } // Ensure we always pass the original request path setProxyDirector(proxy) - if !ptr.Deref(upstream.PassHostHeader, false) { + if !ptr.Deref(upstream.PassHostHeader, options.DefaultUpstreamPassHostHeader) { setProxyUpstreamHostHeader(proxy, target) } @@ -169,7 +169,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Pass on DisableKeepAlives to the transport settings // to allow for disabling HTTP keep-alive connections - transport.DisableKeepAlives = ptr.Deref(upstream.DisableKeepAlives, false) + transport.DisableKeepAlives = ptr.Deref(upstream.DisableKeepAlives, options.DefaultUpstreamDisableKeepAlives) // Apply the customized transport to our proxy before returning it proxy.Transport = transport diff --git a/pkg/upstream/proxy.go b/pkg/upstream/proxy.go index acf24d1a..af4d2e84 100644 --- a/pkg/upstream/proxy.go +++ b/pkg/upstream/proxy.go @@ -28,12 +28,12 @@ func NewProxy(upstreams options.UpstreamConfig, sigData *options.SignatureData, serveMux: mux.NewRouter(), } - if ptr.Deref(upstreams.ProxyRawPath, false) { + if ptr.Deref(upstreams.ProxyRawPath, options.DefaultUpstreamProxyRawPath) { m.serveMux.UseEncodedPath() } for _, upstream := range sortByPathLongest(upstreams.Upstreams) { - if ptr.Deref(upstream.Static, false) { + if ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { if err := m.registerStaticResponseHandler(upstream, writer); err != nil { return nil, fmt.Errorf("could not register static upstream %q: %v", upstream.ID, err) } @@ -75,7 +75,7 @@ func (m *multiUpstreamProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request // registerStaticResponseHandler registers a static response handler with at the given path. func (m *multiUpstreamProxy) registerStaticResponseHandler(upstream options.Upstream, writer pagewriter.Writer) error { - logger.Printf("mapping path %q => static response %d", upstream.Path, ptr.Deref(upstream.StaticCode, 200)) + logger.Printf("mapping path %q => static response %d", upstream.Path, ptr.Deref(upstream.StaticCode, options.DefaultUpstreamStaticCode)) return m.registerHandler(upstream, newStaticResponseHandler(upstream.ID, upstream.StaticCode), writer) } diff --git a/pkg/upstream/static.go b/pkg/upstream/static.go index d7d037bf..6f002b8f 100644 --- a/pkg/upstream/static.go +++ b/pkg/upstream/static.go @@ -5,6 +5,7 @@ import ( "net/http" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) @@ -13,7 +14,7 @@ import ( // a static response code. func newStaticResponseHandler(upstream string, code *int) http.Handler { return &staticResponseHandler{ - code: ptr.Deref(code, 200), + code: ptr.Deref(code, options.DefaultUpstreamStaticCode), upstream: upstream, } } diff --git a/pkg/validation/options.go b/pkg/validation/options.go index ffb0accc..13ce2e0b 100644 --- a/pkg/validation/options.go +++ b/pkg/validation/options.go @@ -35,7 +35,7 @@ func Validate(o *options.Options) error { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402 -- InsecureSkipVerify is a configurable option we allow } else if len(o.Providers[0].CAFiles) > 0 { - pool, err := util.GetCertPool(o.Providers[0].CAFiles, ptr.Deref(o.Providers[0].UseSystemTrustStore, false)) + pool, err := util.GetCertPool(o.Providers[0].CAFiles, ptr.Deref(o.Providers[0].UseSystemTrustStore, options.DefaultUseSystemTrustStore)) if err == nil { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{ diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index 1acdee65..9e62e98a 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -65,7 +65,7 @@ func validateProvider(provider options.Provider, providerIDs map[string]struct{} // providerRequiresClientSecret checks if provider requires client secret to be set // or it can be omitted in favor of JWT token to authenticate oAuth client func providerRequiresClientSecret(provider options.Provider) bool { - if provider.Type == "entra-id" && ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, false) { + if provider.Type == "entra-id" && ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, options.DefaultMicrosoftEntraIDUseFederatedToken) { return false } @@ -97,7 +97,7 @@ func validateGoogleConfig(provider options.Provider) []string { hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" - useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, false) + useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) if !hasAdminEmail && !hasSAJSON && !useADC { return msgs @@ -124,7 +124,7 @@ func validateGoogleConfig(provider options.Provider) []string { func validateEntraConfig(provider options.Provider) []string { msgs := []string{} - if ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, false) { + if ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, options.DefaultMicrosoftEntraIDUseFederatedToken) { federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") if federatedTokenPath == "" { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 4c537678..4c566659 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -55,28 +55,28 @@ func validateUpstream(upstream options.Upstream, ids, paths map[string]struct{}) func validateStaticUpstream(upstream options.Upstream) []string { msgs := []string{} - if !ptr.Deref(upstream.Static, false) && upstream.StaticCode != nil { + if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) && upstream.StaticCode != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has staticCode (%d), but is not a static upstream, set 'static' for a static response", upstream.ID, *upstream.StaticCode)) } // Checks after this only make sense when the upstream is static - if !ptr.Deref(upstream.Static, false) { + if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { return msgs } if upstream.URI != "" { msgs = append(msgs, fmt.Sprintf("upstream %q has uri, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.InsecureSkipTLSVerify, false) { + if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } if ptr.Deref(upstream.FlushInterval, options.DefaultUpstreamFlushInterval) != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.PassHostHeader, false) { + if ptr.Deref(upstream.PassHostHeader, options.DefaultUpstreamPassHostHeader) { msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.ProxyWebSockets, false) { + if ptr.Deref(upstream.ProxyWebSockets, options.DefaultUpstreamProxyWebSockets) { msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID)) } @@ -86,13 +86,13 @@ func validateStaticUpstream(upstream options.Upstream) []string { func validateUpstreamURI(upstream options.Upstream) []string { msgs := []string{} - if !ptr.Deref(upstream.Static, false) && upstream.URI == "" { + if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) && upstream.URI == "" { msgs = append(msgs, fmt.Sprintf("upstream %q has empty uri: uris are required for all non-static upstreams", upstream.ID)) return msgs } // Checks after this only make sense the upstream is not static - if !ptr.Deref(upstream.Static, false) { + if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { return msgs } diff --git a/providers/adfs.go b/providers/adfs.go index ebf91f71..bc583df0 100644 --- a/providers/adfs.go +++ b/providers/adfs.go @@ -51,7 +51,7 @@ func NewADFSProvider(p *ProviderData, opts options.Provider) *ADFSProvider { return &ADFSProvider{ OIDCProvider: oidcProvider, - skipScope: ptr.Deref(opts.ADFSConfig.SkipScope, false), + skipScope: ptr.Deref(opts.ADFSConfig.SkipScope, options.DefaultADFSSkipScope), oidcEnrichFunc: oidcProvider.EnrichSession, oidcRefreshFunc: oidcProvider.RefreshSession, } diff --git a/providers/adfs_test.go b/providers/adfs_test.go old mode 100755 new mode 100644 diff --git a/providers/google.go b/providers/google.go index ac38980f..92d78224 100644 --- a/providers/google.go +++ b/providers/google.go @@ -109,7 +109,7 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv }, } - if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, false) { + if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { // reuse admin service to avoid multiple calls for token var adminService *admin.Service @@ -132,7 +132,7 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv } } - if opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, false) { + if opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { if adminService == nil { adminService = getAdminService(opts) } @@ -304,7 +304,7 @@ var possibleScopesList = [...]string{ } func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope string) oauth2.TokenSource { - if ptr.Deref(opts.UseApplicationDefaultCredentials, false) { + if ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), Scopes: strings.Split(scope, " "), diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go index 57c4fae1..f9445d69 100644 --- a/providers/ms_entra_id.go +++ b/providers/ms_entra_id.go @@ -52,7 +52,7 @@ func NewMicrosoftEntraIDProvider(p *ProviderData, opts options.Provider) *Micros OIDCProvider: NewOIDCProvider(p, opts.OIDCConfig), multiTenantAllowedTenants: opts.MicrosoftEntraIDConfig.AllowedTenants, - federatedTokenAuth: ptr.Deref(opts.MicrosoftEntraIDConfig.FederatedTokenAuth, false), + federatedTokenAuth: ptr.Deref(opts.MicrosoftEntraIDConfig.FederatedTokenAuth, options.DefaultMicrosoftEntraIDUseFederatedToken), microsoftGraphURL: microsoftGraphURL, } } diff --git a/providers/oidc.go b/providers/oidc.go index 5e28039d..b0be63bc 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -51,7 +51,7 @@ func NewOIDCProvider(p *ProviderData, opts options.OIDCOptions) *OIDCProvider { return &OIDCProvider{ ProviderData: p, - SkipNonce: ptr.Deref(opts.InsecureSkipNonce, false), + SkipNonce: ptr.Deref(opts.InsecureSkipNonce, options.DefaultInsecureSkipNonce), } } diff --git a/providers/providers.go b/providers/providers.go index 1c7ac652..6af51ecf 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -99,8 +99,8 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, IssuerURL: providerConfig.OIDCConfig.IssuerURL, JWKsURL: providerConfig.OIDCConfig.JwksURL, PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles, - SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, false), - SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, false), + SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, options.DefaultSkipDiscovery), + SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, options.DefaultInsecureSkipIssuerVerification), }) if err != nil { return nil, fmt.Errorf("error building OIDC ProviderVerifier: %v", err) @@ -144,10 +144,10 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, } // Make the OIDC options available to all providers that support it - p.AllowUnverifiedEmail = ptr.Deref(providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail, false) + p.AllowUnverifiedEmail = ptr.Deref(providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail, options.DefaultInsecureAllowUnverifiedEmail) p.EmailClaim = providerConfig.OIDCConfig.EmailClaim p.GroupsClaim = providerConfig.OIDCConfig.GroupsClaim - p.SkipClaimsFromProfileURL = ptr.Deref(providerConfig.SkipClaimsFromProfileURL, false) + p.SkipClaimsFromProfileURL = ptr.Deref(providerConfig.SkipClaimsFromProfileURL, options.DefaultSkipClaimsFromProfileURL) // Set PKCE enabled or disabled based on discovery and force options p.CodeChallengeMethod = parseCodeChallengeMethod(providerConfig) From 137decb1ec59efc2eaa44df49372567272ca6dcc Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 7 Nov 2025 23:26:00 +0100 Subject: [PATCH 127/130] adapting unit tests and fixing minor issues introduced with the derefing Signed-off-by: Jan Larwig --- pkg/apis/middleware/session.go | 5 +- pkg/apis/options/legacy_options.go | 44 +++++++++---- pkg/apis/options/legacy_options_test.go | 86 +++++++++++++++++-------- pkg/apis/options/providers.go | 2 +- pkg/middleware/jwt_session_test.go | 4 +- pkg/validation/sessions_test.go | 4 +- pkg/validation/upstreams.go | 8 +-- 7 files changed, 103 insertions(+), 50 deletions(-) diff --git a/pkg/apis/middleware/session.go b/pkg/apis/middleware/session.go index e17c0249..afa56e9d 100644 --- a/pkg/apis/middleware/session.go +++ b/pkg/apis/middleware/session.go @@ -41,7 +41,10 @@ func CreateTokenToSessionFunc(verify VerifyFunc) TokenToSessionFunc { claims.Email = claims.Subject } - if !ptr.Deref(claims.Verified, false) { + // Ensure email is verified + // If the email is not verified, return an error + // If the email_verified claim is missing, assume it is verified + if !ptr.Deref(claims.Verified, true) { return nil, fmt.Errorf("email in id_token (%s) isn't verified", claims.Email) } diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index ffd98bd1..5f4efe57 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -96,6 +96,7 @@ func (l *LegacyOptions) ToOptions() (*Options, error) { return nil, fmt.Errorf("error converting provider: %v", err) } l.Options.Providers = providers + l.Options.EnsureDefaults() return &l.Options, nil } @@ -178,6 +179,10 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { upstream.URI = "" upstream.InsecureSkipTLSVerify = ptr.Ptr(false) upstream.DisableKeepAlives = ptr.Ptr(false) + upstream.PassHostHeader = nil + upstream.ProxyWebSockets = nil + upstream.FlushInterval = nil + upstream.Timeout = nil case "unix": upstream.Path = "/" } @@ -284,7 +289,8 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header } return Header{ - Name: "Authorization", + Name: "Authorization", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -302,7 +308,8 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header func getPassUserHeaders(preferEmailToUser bool) []Header { headers := []Header{ { - Name: "X-Forwarded-Groups", + Name: "X-Forwarded-Groups", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -316,7 +323,8 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { if preferEmailToUser { return append(headers, Header{ - Name: "X-Forwarded-User", + Name: "X-Forwarded-User", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -330,7 +338,8 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { return append(headers, Header{ - Name: "X-Forwarded-User", + Name: "X-Forwarded-User", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -340,7 +349,8 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { }, }, Header{ - Name: "X-Forwarded-Email", + Name: "X-Forwarded-Email", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -354,7 +364,8 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { func getPassAccessTokenHeader() Header { return Header{ - Name: "X-Forwarded-Access-Token", + Name: "X-Forwarded-Access-Token", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -367,7 +378,8 @@ func getPassAccessTokenHeader() Header { func getAuthorizationHeader() Header { return Header{ - Name: "Authorization", + Name: "Authorization", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -381,7 +393,8 @@ func getAuthorizationHeader() Header { func getPreferredUsernameHeader() Header { return Header{ - Name: "X-Forwarded-Preferred-Username", + Name: "X-Forwarded-Preferred-Username", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -395,7 +408,8 @@ func getPreferredUsernameHeader() Header { func getXAuthRequestHeaders() []Header { headers := []Header{ { - Name: "X-Auth-Request-User", + Name: "X-Auth-Request-User", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -405,7 +419,8 @@ func getXAuthRequestHeaders() []Header { }, }, { - Name: "X-Auth-Request-Email", + Name: "X-Auth-Request-Email", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -415,7 +430,8 @@ func getXAuthRequestHeaders() []Header { }, }, { - Name: "X-Auth-Request-Preferred-Username", + Name: "X-Auth-Request-Preferred-Username", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -425,7 +441,8 @@ func getXAuthRequestHeaders() []Header { }, }, { - Name: "X-Auth-Request-Groups", + Name: "X-Auth-Request-Groups", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -441,7 +458,8 @@ func getXAuthRequestHeaders() []Header { func getXAuthRequestAccessTokenHeader() Header { return Header{ - Name: "X-Auth-Request-Access-Token", + Name: "X-Auth-Request-Access-Token", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index cc2a76e5..65813c80 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -122,16 +122,19 @@ var _ = Describe("Legacy Options", func() { BindAddress: "127.0.0.1:4180", } - opts.Providers[0].ClientID = "oauth-proxy" opts.Providers[0].ID = "google=oauth-proxy" - opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.Ptr(true) + opts.Providers[0].ClientID = "oauth-proxy" opts.Providers[0].OIDCConfig.AudienceClaims = []string{"aud"} opts.Providers[0].OIDCConfig.ExtraAudiences = []string{} + opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.Ptr(true) + opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.Ptr(false) opts.Providers[0].LoginURLParameters = []LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, } converted, err := legacyOpts.ToOptions() + opts.EnsureDefaults() + Expect(err).ToNot(HaveOccurred()) Expect(converted).To(EqualOpts(opts)) }) @@ -944,37 +947,50 @@ var _ = Describe("Legacy Options", func() { {Name: "approval_prompt", Default: []string{"force"}}, } - defaultProvider := Provider{ - ID: "google=" + clientID, - ClientID: clientID, - Type: "google", - LoginURLParameters: defaultURLParams, + defaultOIDCOptions := OIDCOptions{ + SkipDiscovery: ptr.Ptr(false), + InsecureSkipNonce: ptr.Ptr(false), + InsecureAllowUnverifiedEmail: ptr.Ptr(false), + InsecureSkipIssuerVerification: ptr.Ptr(false), } + + defaultGoogleOptions := GoogleOptions{ + UseApplicationDefaultCredentials: ptr.Ptr(false), + } + defaultLegacyProvider := LegacyProvider{ ClientID: clientID, ProviderType: "google", } - defaultProviderWithPrompt := Provider{ - ID: "google=" + clientID, - ClientID: clientID, - Type: "google", - LoginURLParameters: []LoginURLParameter{ - {Name: "prompt", Default: []string{"switch_user"}}, - }, + defaultProvider := Provider{ + ID: "google=" + clientID, + ClientID: clientID, + Type: "google", + OIDCConfig: defaultOIDCOptions, + GoogleConfig: defaultGoogleOptions, + LoginURLParameters: defaultURLParams, + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), } + defaultLegacyProviderWithPrompt := LegacyProvider{ ClientID: clientID, ProviderType: "google", Prompt: "switch_user", } - displayNameProvider := Provider{ - ID: "displayName", - Name: "displayName", - ClientID: clientID, - Type: "google", - LoginURLParameters: defaultURLParams, + defaultProviderWithPrompt := Provider{ + ID: "google=" + clientID, + ClientID: clientID, + Type: "google", + OIDCConfig: defaultOIDCOptions, + GoogleConfig: defaultGoogleOptions, + LoginURLParameters: []LoginURLParameter{ + {Name: "prompt", Default: []string{"switch_user"}}, + }, + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), } displayNameLegacyProvider := LegacyProvider{ @@ -983,16 +999,32 @@ var _ = Describe("Legacy Options", func() { ProviderType: "google", } + displayNameProvider := Provider{ + ID: "displayName", + Name: "displayName", + ClientID: clientID, + Type: "google", + OIDCConfig: defaultOIDCOptions, + GoogleConfig: defaultGoogleOptions, + LoginURLParameters: defaultURLParams, + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), + } + internalConfigProvider := Provider{ - ID: "google=" + clientID, - ClientID: clientID, - Type: "google", + ID: "google=" + clientID, + ClientID: clientID, + Type: "google", + OIDCConfig: defaultOIDCOptions, GoogleConfig: GoogleOptions{ - AdminEmail: "email@email.com", - ServiceAccountJSON: "test.json", - Groups: []string{"1", "2"}, + AdminEmail: "email@email.com", + ServiceAccountJSON: "test.json", + Groups: []string{"1", "2"}, + UseApplicationDefaultCredentials: ptr.Ptr(false), }, - LoginURLParameters: defaultURLParams, + LoginURLParameters: defaultURLParams, + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), } internalConfigLegacyProvider := LegacyProvider{ diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index e8c39226..b93fb7ad 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -43,7 +43,7 @@ const ( // DefaultUseSystemTrustStore is the default value // for Provider.UseSystemTrustStore - DefaultUseSystemTrustStore bool = true + DefaultUseSystemTrustStore bool = false ) // OIDCAudienceClaims is the generic audience claim list used by the OIDC provider. diff --git a/pkg/middleware/jwt_session_test.go b/pkg/middleware/jwt_session_test.go index 12f30f5c..7b724280 100644 --- a/pkg/middleware/jwt_session_test.go +++ b/pkg/middleware/jwt_session_test.go @@ -304,7 +304,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=` authorizationHeader: fmt.Sprintf("Bearer %s", nonVerifiedToken), expectedErr: k8serrors.NewAggregate([]error{ errors.New("unable to verify bearer token"), - errors.New("oidc: malformed jwt: oidc: malformed jwt payload: illegal base64 data at input byte 8"), + errors.New("oidc: malformed jwt: illegal base64 data at input byte 8"), }), expectedSession: nil, }), @@ -317,7 +317,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=` authorizationHeader: "Basic ZXlKZm9vYmFyLmV5SmZvb2Jhci4xMjM0NWFzZGY6", expectedErr: k8serrors.NewAggregate([]error{ errors.New("unable to verify bearer token"), - errors.New("oidc: malformed jwt: oidc: malformed jwt payload: illegal base64 data at input byte 8"), + errors.New("oidc: malformed jwt: illegal base64 data at input byte 8"), }), expectedSession: nil, }), diff --git a/pkg/validation/sessions_test.go b/pkg/validation/sessions_test.go index 6f590ac5..cb54c571 100644 --- a/pkg/validation/sessions_test.go +++ b/pkg/validation/sessions_test.go @@ -193,8 +193,8 @@ var _ = Describe("Sessions", func() { unreachableRedisDelMsg = "unable to delete the redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused" unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" unrechableSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" - refusedSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" - refusedSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" + refusedSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: context deadline exceeded" + refusedSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: context deadline exceeded" ) type redisStoreTableInput struct { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 4c566659..9a381918 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -70,13 +70,13 @@ func validateStaticUpstream(upstream options.Upstream) []string { if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.FlushInterval, options.DefaultUpstreamFlushInterval) != options.DefaultUpstreamFlushInterval { + if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.PassHostHeader, options.DefaultUpstreamPassHostHeader) { + if upstream.PassHostHeader != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.ProxyWebSockets, options.DefaultUpstreamProxyWebSockets) { + if upstream.ProxyWebSockets != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID)) } @@ -92,7 +92,7 @@ func validateUpstreamURI(upstream options.Upstream) []string { } // Checks after this only make sense the upstream is not static - if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { + if ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { return msgs } From 0eec65e230219c389e837bfd97b21e00410b1e95 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 16 Nov 2025 22:04:22 +0100 Subject: [PATCH 128/130] refactor: ptr.Ptr to ptr.To Signed-off-by: Jan Larwig --- main_test.go | 36 +++++----- oauthproxy_test.go | 4 +- pkg/apis/options/header.go | 2 +- pkg/apis/options/legacy_options.go | 34 ++++----- pkg/apis/options/legacy_options_test.go | 96 ++++++++++++------------- pkg/apis/options/providers.go | 22 +++--- pkg/apis/options/upstreams.go | 16 ++--- pkg/apis/sessions/session_state_test.go | 11 ++- pkg/middleware/headers_test.go | 8 +-- pkg/upstream/http_test.go | 16 ++--- pkg/upstream/proxy_test.go | 10 +-- pkg/util/ptr/ptr.go | 4 +- pkg/util/ptr/ptr_test.go | 12 ++-- pkg/validation/options_test.go | 4 +- pkg/validation/upstreams_test.go | 10 +-- providers/adfs_test.go | 2 +- providers/ms_entra_id_test.go | 6 +- providers/providers_test.go | 8 +-- 18 files changed, 149 insertions(+), 152 deletions(-) diff --git a/main_test.go b/main_test.go index 1d9102d7..dce11fcc 100644 --- a/main_test.go +++ b/main_test.go @@ -123,26 +123,26 @@ redirect_url="http://localhost:4180/oauth2/callback" opts.RawRedirectURL = "http://localhost:4180/oauth2/callback" opts.UpstreamServers = options.UpstreamConfig{ - ProxyRawPath: ptr.Ptr(false), + ProxyRawPath: ptr.To(false), Upstreams: []options.Upstream{ { ID: "/", Path: "/", URI: "http://httpbin", - FlushInterval: ptr.Ptr(options.DefaultUpstreamFlushInterval), - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), - Timeout: ptr.Ptr(options.DefaultUpstreamTimeout), - Static: ptr.Ptr(false), - InsecureSkipTLSVerify: ptr.Ptr(false), - DisableKeepAlives: ptr.Ptr(false), + FlushInterval: ptr.To(options.DefaultUpstreamFlushInterval), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), + Timeout: ptr.To(options.DefaultUpstreamTimeout), + Static: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(false), + DisableKeepAlives: ptr.To(false), }, }, } authHeader := options.Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -165,11 +165,11 @@ redirect_url="http://localhost:4180/oauth2/callback" Type: "google", ClientSecret: "b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK", ClientID: "oauth2-proxy", - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), GoogleConfig: options.GoogleOptions{ AdminEmail: "admin@example.com", - UseApplicationDefaultCredentials: ptr.Ptr(false), + UseApplicationDefaultCredentials: ptr.To(false), TargetPrincipal: "principal", }, AzureConfig: options.AzureOptions{ @@ -181,16 +181,16 @@ redirect_url="http://localhost:4180/oauth2/callback" UserIDClaim: "email", AudienceClaims: []string{"aud"}, ExtraAudiences: []string{}, - InsecureSkipNonce: ptr.Ptr(true), - InsecureAllowUnverifiedEmail: ptr.Ptr(false), - InsecureSkipIssuerVerification: ptr.Ptr(false), - SkipDiscovery: ptr.Ptr(false), + InsecureSkipNonce: ptr.To(true), + InsecureAllowUnverifiedEmail: ptr.To(false), + InsecureSkipIssuerVerification: ptr.To(false), + SkipDiscovery: ptr.To(false), }, MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ - FederatedTokenAuth: ptr.Ptr(false), + FederatedTokenAuth: ptr.To(false), }, ADFSConfig: options.ADFSOptions{ - SkipScope: ptr.Ptr(false), + SkipScope: ptr.To(false), }, LoginURLParameters: []options.LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 0463c9dd..ccabdbbd 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -507,7 +507,7 @@ func TestStaticProxyUpstream(t *testing.T) { ProxyUpstream: options.Upstream{ ID: "static-proxy", Path: "/static-proxy", - Static: ptr.Ptr(true), + Static: ptr.To(true), }, }) if err != nil { @@ -2224,7 +2224,7 @@ func TestTrustedIPs(t *testing.T) { { ID: "static", Path: "/", - Static: ptr.Ptr(true), + Static: ptr.To(true), }, }, } diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index a3595508..52552397 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -64,7 +64,7 @@ type ClaimSource struct { // EnsureDefaults sets any default values for Header fields. func (h *Header) EnsureDefaults() { if h.PreserveRequestValue == nil { - h.PreserveRequestValue = ptr.Ptr(DefaultHeaderPreserveRequestValue) + h.PreserveRequestValue = ptr.To(DefaultHeaderPreserveRequestValue) } for i := range h.Values { h.Values[i].EnsureDefaults() diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 5f4efe57..0f9f0829 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -166,7 +166,7 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { logger.Errorf("unable to convert %q to int, use default \"200\"", u.Host) responseCode = 200 } - upstream.Static = ptr.Ptr(true) + upstream.Static = ptr.To(true) upstream.StaticCode = &responseCode // This is not allowed to be empty and must be unique @@ -177,8 +177,8 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { // Force defaults compatible with static responses upstream.URI = "" - upstream.InsecureSkipTLSVerify = ptr.Ptr(false) - upstream.DisableKeepAlives = ptr.Ptr(false) + upstream.InsecureSkipTLSVerify = ptr.To(false) + upstream.DisableKeepAlives = ptr.To(false) upstream.PassHostHeader = nil upstream.ProxyWebSockets = nil upstream.FlushInterval = nil @@ -255,7 +255,7 @@ func (l *LegacyHeaders) getRequestHeaders() []Header { } for i := range requestHeaders { - requestHeaders[i].PreserveRequestValue = ptr.Ptr(!l.SkipAuthStripHeaders) + requestHeaders[i].PreserveRequestValue = ptr.To(!l.SkipAuthStripHeaders) } return requestHeaders @@ -290,7 +290,7 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header return Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -309,7 +309,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { headers := []Header{ { Name: "X-Forwarded-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -324,7 +324,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { return append(headers, Header{ Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -339,7 +339,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { return append(headers, Header{ Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -350,7 +350,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { }, Header{ Name: "X-Forwarded-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -365,7 +365,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { func getPassAccessTokenHeader() Header { return Header{ Name: "X-Forwarded-Access-Token", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -379,7 +379,7 @@ func getPassAccessTokenHeader() Header { func getAuthorizationHeader() Header { return Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -394,7 +394,7 @@ func getAuthorizationHeader() Header { func getPreferredUsernameHeader() Header { return Header{ Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -409,7 +409,7 @@ func getXAuthRequestHeaders() []Header { headers := []Header{ { Name: "X-Auth-Request-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -420,7 +420,7 @@ func getXAuthRequestHeaders() []Header { }, { Name: "X-Auth-Request-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -431,7 +431,7 @@ func getXAuthRequestHeaders() []Header { }, { Name: "X-Auth-Request-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -442,7 +442,7 @@ func getXAuthRequestHeaders() []Header { }, { Name: "X-Auth-Request-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -459,7 +459,7 @@ func getXAuthRequestHeaders() []Header { func getXAuthRequestAccessTokenHeader() Header { return Header{ Name: "X-Auth-Request-Access-Token", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 65813c80..3fe9c1e5 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -36,9 +36,9 @@ var _ = Describe("Legacy Options", func() { Path: "/baz", URI: "http://foo.bar/baz", FlushInterval: &flushInterval, - InsecureSkipTLSVerify: ptr.Ptr(true), - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), + InsecureSkipTLSVerify: ptr.To(true), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), Timeout: &timeout, DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, @@ -47,9 +47,9 @@ var _ = Describe("Legacy Options", func() { Path: "/bar", URI: "file:///var/lib/website", FlushInterval: &flushInterval, - InsecureSkipTLSVerify: ptr.Ptr(true), - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), + InsecureSkipTLSVerify: ptr.To(true), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), Timeout: &timeout, DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, @@ -57,10 +57,10 @@ var _ = Describe("Legacy Options", func() { ID: "static://204", Path: "/", URI: "", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &staticCode, FlushInterval: nil, - InsecureSkipTLSVerify: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.To(false), PassHostHeader: nil, ProxyWebSockets: nil, Timeout: nil, @@ -72,7 +72,7 @@ var _ = Describe("Legacy Options", func() { opts.InjectRequestHeaders = []Header{ { Name: "X-Forwarded-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -83,7 +83,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -94,7 +94,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -105,7 +105,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -126,8 +126,8 @@ var _ = Describe("Legacy Options", func() { opts.Providers[0].ClientID = "oauth-proxy" opts.Providers[0].OIDCConfig.AudienceClaims = []string{"aud"} opts.Providers[0].OIDCConfig.ExtraAudiences = []string{} - opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.Ptr(true) - opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.Ptr(false) + opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.To(true) + opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.To(false) opts.Providers[0].LoginURLParameters = []LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, } @@ -202,14 +202,14 @@ var _ = Describe("Legacy Options", func() { ID: validStatic, Path: "/", URI: "", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &validStaticCode, - InsecureSkipTLSVerify: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.To(false), PassHostHeader: nil, ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, - DisableKeepAlives: ptr.Ptr(false), + DisableKeepAlives: ptr.To(false), } invalidStatic := "static://abc" @@ -218,14 +218,14 @@ var _ = Describe("Legacy Options", func() { ID: invalidStatic, Path: "/", URI: "", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &invalidStaticCode, - InsecureSkipTLSVerify: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.To(false), PassHostHeader: nil, ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, - DisableKeepAlives: ptr.Ptr(false), + DisableKeepAlives: ptr.To(false), } invalidHTTP := ":foo" @@ -318,7 +318,7 @@ var _ = Describe("Legacy Options", func() { xForwardedUser := Header{ Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -330,7 +330,7 @@ var _ = Describe("Legacy Options", func() { xForwardedEmail := Header{ Name: "X-Forwarded-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -342,7 +342,7 @@ var _ = Describe("Legacy Options", func() { xForwardedGroups := Header{ Name: "X-Forwarded-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -354,7 +354,7 @@ var _ = Describe("Legacy Options", func() { xForwardedPreferredUsername := Header{ Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -366,7 +366,7 @@ var _ = Describe("Legacy Options", func() { basicAuthHeader := Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -382,7 +382,7 @@ var _ = Describe("Legacy Options", func() { xForwardedUserWithEmail := Header{ Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -394,7 +394,7 @@ var _ = Describe("Legacy Options", func() { xForwardedAccessToken := Header{ Name: "X-Forwarded-Access-Token", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -406,7 +406,7 @@ var _ = Describe("Legacy Options", func() { basicAuthHeaderWithEmail := Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -422,7 +422,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestUser := Header{ Name: "X-Auth-Request-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -434,7 +434,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestEmail := Header{ Name: "X-Auth-Request-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -446,7 +446,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestGroups := Header{ Name: "X-Auth-Request-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -458,7 +458,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestPreferredUsername := Header{ Name: "X-Auth-Request-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -470,7 +470,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestAccessToken := Header{ Name: "X-Auth-Request-Access-Token", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -482,7 +482,7 @@ var _ = Describe("Legacy Options", func() { authorizationHeader := Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -948,14 +948,14 @@ var _ = Describe("Legacy Options", func() { } defaultOIDCOptions := OIDCOptions{ - SkipDiscovery: ptr.Ptr(false), - InsecureSkipNonce: ptr.Ptr(false), - InsecureAllowUnverifiedEmail: ptr.Ptr(false), - InsecureSkipIssuerVerification: ptr.Ptr(false), + SkipDiscovery: ptr.To(false), + InsecureSkipNonce: ptr.To(false), + InsecureAllowUnverifiedEmail: ptr.To(false), + InsecureSkipIssuerVerification: ptr.To(false), } defaultGoogleOptions := GoogleOptions{ - UseApplicationDefaultCredentials: ptr.Ptr(false), + UseApplicationDefaultCredentials: ptr.To(false), } defaultLegacyProvider := LegacyProvider{ @@ -970,8 +970,8 @@ var _ = Describe("Legacy Options", func() { OIDCConfig: defaultOIDCOptions, GoogleConfig: defaultGoogleOptions, LoginURLParameters: defaultURLParams, - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), } defaultLegacyProviderWithPrompt := LegacyProvider{ @@ -989,8 +989,8 @@ var _ = Describe("Legacy Options", func() { LoginURLParameters: []LoginURLParameter{ {Name: "prompt", Default: []string{"switch_user"}}, }, - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), } displayNameLegacyProvider := LegacyProvider{ @@ -1007,8 +1007,8 @@ var _ = Describe("Legacy Options", func() { OIDCConfig: defaultOIDCOptions, GoogleConfig: defaultGoogleOptions, LoginURLParameters: defaultURLParams, - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), } internalConfigProvider := Provider{ @@ -1020,11 +1020,11 @@ var _ = Describe("Legacy Options", func() { AdminEmail: "email@email.com", ServiceAccountJSON: "test.json", Groups: []string{"1", "2"}, - UseApplicationDefaultCredentials: ptr.Ptr(false), + UseApplicationDefaultCredentials: ptr.To(false), }, LoginURLParameters: defaultURLParams, - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), } internalConfigLegacyProvider := LegacyProvider{ diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index b93fb7ad..2d89eb2c 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -334,9 +334,9 @@ func providerDefaults() Providers { Tenant: "common", }, OIDCConfig: OIDCOptions{ - InsecureAllowUnverifiedEmail: ptr.Ptr(DefaultInsecureAllowUnverifiedEmail), - InsecureSkipNonce: ptr.Ptr(DefaultInsecureSkipNonce), - SkipDiscovery: ptr.Ptr(DefaultSkipDiscovery), + InsecureAllowUnverifiedEmail: ptr.To(DefaultInsecureAllowUnverifiedEmail), + InsecureSkipNonce: ptr.To(DefaultInsecureSkipNonce), + SkipDiscovery: ptr.To(DefaultSkipDiscovery), UserIDClaim: OIDCEmailClaim, // Deprecated: Use OIDCEmailClaim EmailClaim: OIDCEmailClaim, GroupsClaim: OIDCGroupsClaim, @@ -358,10 +358,10 @@ func (p Providers) EnsureDefaults() { // EnsureDefaults sets any default values for Provider fields. func (p *Provider) EnsureDefaults() { if p.SkipClaimsFromProfileURL == nil { - p.SkipClaimsFromProfileURL = ptr.Ptr(DefaultSkipClaimsFromProfileURL) + p.SkipClaimsFromProfileURL = ptr.To(DefaultSkipClaimsFromProfileURL) } if p.UseSystemTrustStore == nil { - p.UseSystemTrustStore = ptr.Ptr(DefaultUseSystemTrustStore) + p.UseSystemTrustStore = ptr.To(DefaultUseSystemTrustStore) } p.OIDCConfig.EnsureDefaults() @@ -374,13 +374,13 @@ func (p *Provider) EnsureDefaults() { func (o *OIDCOptions) EnsureDefaults() { // Ensure OIDC defaults if o.InsecureAllowUnverifiedEmail == nil { - o.InsecureAllowUnverifiedEmail = ptr.Ptr(DefaultInsecureAllowUnverifiedEmail) + o.InsecureAllowUnverifiedEmail = ptr.To(DefaultInsecureAllowUnverifiedEmail) } if o.InsecureSkipNonce == nil { - o.InsecureSkipNonce = ptr.Ptr(DefaultInsecureSkipNonce) + o.InsecureSkipNonce = ptr.To(DefaultInsecureSkipNonce) } if o.SkipDiscovery == nil { - o.SkipDiscovery = ptr.Ptr(DefaultSkipDiscovery) + o.SkipDiscovery = ptr.To(DefaultSkipDiscovery) } if o.UserIDClaim == "" { o.UserIDClaim = OIDCEmailClaim @@ -399,20 +399,20 @@ func (o *OIDCOptions) EnsureDefaults() { // EnsureDefaults sets any default values for MicrosoftEntraIDOptions fields. func (me *MicrosoftEntraIDOptions) EnsureDefaults() { if me.FederatedTokenAuth == nil { - me.FederatedTokenAuth = ptr.Ptr(DefaultMicrosoftEntraIDUseFederatedToken) + me.FederatedTokenAuth = ptr.To(DefaultMicrosoftEntraIDUseFederatedToken) } } // EnsureDefaults sets any default values for ADFSOptions fields. func (a *ADFSOptions) EnsureDefaults() { if a.SkipScope == nil { - a.SkipScope = ptr.Ptr(DefaultADFSSkipScope) + a.SkipScope = ptr.To(DefaultADFSSkipScope) } } // EnsureDefaults sets any default values for GoogleOptions fields. func (g *GoogleOptions) EnsureDefaults() { if g.UseApplicationDefaultCredentials == nil { - g.UseApplicationDefaultCredentials = ptr.Ptr(DefaultUseApplicationDefaultCredentials) + g.UseApplicationDefaultCredentials = ptr.To(DefaultUseApplicationDefaultCredentials) } } diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index f69fec90..a56fca61 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -128,7 +128,7 @@ type Upstream struct { // EnsureDefaults sets any default values for UpstreamConfig fields. func (uc *UpstreamConfig) EnsureDefaults() { if uc.ProxyRawPath == nil { - uc.ProxyRawPath = ptr.Ptr(DefaultUpstreamProxyRawPath) + uc.ProxyRawPath = ptr.To(DefaultUpstreamProxyRawPath) } for i := range uc.Upstreams { uc.Upstreams[i].EnsureDefaults() @@ -138,24 +138,24 @@ func (uc *UpstreamConfig) EnsureDefaults() { // EnsureDefaults sets any default values for Upstream fields. func (u *Upstream) EnsureDefaults() { if u.InsecureSkipTLSVerify == nil { - u.InsecureSkipTLSVerify = ptr.Ptr(DefaultUpsteamInsecureSkipTLSVerify) + u.InsecureSkipTLSVerify = ptr.To(DefaultUpsteamInsecureSkipTLSVerify) } if u.Static == nil { - u.Static = ptr.Ptr(DefaultUpstreamStatic) + u.Static = ptr.To(DefaultUpstreamStatic) } if u.FlushInterval == nil { - u.FlushInterval = ptr.Ptr(DefaultUpstreamFlushInterval) + u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval) } if u.PassHostHeader == nil { - u.PassHostHeader = ptr.Ptr(DefaultUpstreamPassHostHeader) + u.PassHostHeader = ptr.To(DefaultUpstreamPassHostHeader) } if u.ProxyWebSockets == nil { - u.ProxyWebSockets = ptr.Ptr(DefaultUpstreamProxyWebSockets) + u.ProxyWebSockets = ptr.To(DefaultUpstreamProxyWebSockets) } if u.Timeout == nil { - u.Timeout = ptr.Ptr(DefaultUpstreamTimeout) + u.Timeout = ptr.To(DefaultUpstreamTimeout) } if u.DisableKeepAlives == nil { - u.DisableKeepAlives = ptr.Ptr(DefaultUpstreamDisableKeepAlives) + u.DisableKeepAlives = ptr.To(DefaultUpstreamDisableKeepAlives) } } diff --git a/pkg/apis/sessions/session_state_test.go b/pkg/apis/sessions/session_state_test.go index 442fcea8..87b97614 100644 --- a/pkg/apis/sessions/session_state_test.go +++ b/pkg/apis/sessions/session_state_test.go @@ -8,15 +8,12 @@ import ( "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/gomega" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func timePtr(t time.Time) *time.Time { - return &t -} - func TestCreatedAtNow(t *testing.T) { g := NewWithT(t) ss := &SessionState{} @@ -137,10 +134,10 @@ func TestString(t *testing.T) { } func TestIsExpired(t *testing.T) { - s := &SessionState{ExpiresOn: timePtr(time.Now().Add(time.Duration(-1) * time.Minute))} + s := &SessionState{ExpiresOn: ptr.To(time.Now().Add(time.Duration(-1) * time.Minute))} assert.Equal(t, true, s.IsExpired()) - s = &SessionState{ExpiresOn: timePtr(time.Now().Add(time.Duration(1) * time.Minute))} + s = &SessionState{ExpiresOn: ptr.To(time.Now().Add(time.Duration(1) * time.Minute))} assert.Equal(t, false, s.IsExpired()) s = &SessionState{} @@ -154,7 +151,7 @@ func TestAge(t *testing.T) { assert.Equal(t, time.Duration(0), ss.Age()) // Set CreatedAt to 1 hour ago - ss.CreatedAt = timePtr(time.Now().Add(-1 * time.Hour)) + ss.CreatedAt = ptr.To(time.Now().Add(-1 * time.Hour)) assert.Equal(t, time.Hour, ss.Age().Round(time.Minute)) } diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 89f65107..393ade9c 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -116,7 +116,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: ptr.Ptr(true), + PreserveRequestValue: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -161,7 +161,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: ptr.Ptr(true), + PreserveRequestValue: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -386,7 +386,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: ptr.Ptr(true), + PreserveRequestValue: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -433,7 +433,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: ptr.Ptr(true), + PreserveRequestValue: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index 7c1831bf..79dc0e4a 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -63,8 +63,8 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: in.id, PassHostHeader: &in.passUpstreamHostHeader, - ProxyWebSockets: ptr.Ptr(false), - InsecureSkipTLSVerify: ptr.Ptr(false), + ProxyWebSockets: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(false), FlushInterval: &flush, Timeout: &timeout, } @@ -342,9 +342,9 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: "noPassHost", - PassHostHeader: ptr.Ptr(false), - ProxyWebSockets: ptr.Ptr(false), - InsecureSkipTLSVerify: ptr.Ptr(false), + PassHostHeader: ptr.To(false), + ProxyWebSockets: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(false), FlushInterval: &defaultFlushInterval, Timeout: &defaultTimeout, } @@ -486,9 +486,9 @@ var _ = Describe("HTTP Upstream Suite", func() { timeout := options.DefaultUpstreamTimeout upstream := options.Upstream{ ID: "websocketProxy", - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), - InsecureSkipTLSVerify: ptr.Ptr(false), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), + InsecureSkipTLSVerify: ptr.To(false), FlushInterval: &flush, Timeout: &timeout, } diff --git a/pkg/upstream/proxy_test.go b/pkg/upstream/proxy_test.go index 87aae7fa..b9b8cf9c 100644 --- a/pkg/upstream/proxy_test.go +++ b/pkg/upstream/proxy_test.go @@ -61,19 +61,19 @@ var _ = Describe("Proxy Suite", func() { { ID: "static-backend", Path: "/static/", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &ok, }, { ID: "static-backend-no-trailing-slash", Path: "/static", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &accepted, }, { ID: "static-backend-long", Path: "/static/long", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &accepted, }, { @@ -84,7 +84,7 @@ var _ = Describe("Proxy Suite", func() { { ID: "single-path-backend", Path: "/single-path", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &ok, }, { @@ -347,7 +347,7 @@ var _ = Describe("Proxy Suite", func() { upstream: "", }), Entry("containing an escaped '/' with ProxyRawPath", &proxyTableInput{ - upstreams: options.UpstreamConfig{ProxyRawPath: ptr.Ptr(true)}, + upstreams: options.UpstreamConfig{ProxyRawPath: ptr.To(true)}, target: "http://example.localhost/%2F/test1/%2F/test2", response: testHTTPResponse{ code: 404, diff --git a/pkg/util/ptr/ptr.go b/pkg/util/ptr/ptr.go index 9242773c..d2b294a2 100644 --- a/pkg/util/ptr/ptr.go +++ b/pkg/util/ptr/ptr.go @@ -1,7 +1,7 @@ package ptr -// Ptr generically returns a pointer to the given value. -func Ptr[T any](v T) *T { +// To generically returns a pointer to the given value. +func To[T any](v T) *T { return &v } diff --git a/pkg/util/ptr/ptr_test.go b/pkg/util/ptr/ptr_test.go index c4817a6b..459e7cc9 100644 --- a/pkg/util/ptr/ptr_test.go +++ b/pkg/util/ptr/ptr_test.go @@ -6,22 +6,22 @@ import ( "github.com/stretchr/testify/assert" ) -func TestPtr(t *testing.T) { - p := Ptr(42) +func TestTo(t *testing.T) { + p := To(42) assert.NotNil(t, p) assert.Equal(t, 42, *p) - s := Ptr("hello") + s := To("hello") assert.NotNil(t, s) assert.Equal(t, "hello", *s) - b := Ptr(true) + b := To(true) assert.NotNil(t, b) assert.True(t, *b) } func TestDeref(t *testing.T) { - v := Deref(Ptr(99), 0) + v := Deref(To(99), 0) assert.Equal(t, 99, v) v = Deref[int](nil, 123) @@ -30,7 +30,7 @@ func TestDeref(t *testing.T) { s := Deref[string](nil, "default") assert.Equal(t, "default", s) - b := Deref(Ptr(true), false) + b := Deref(To(true), false) assert.True(t, b) b = Deref[bool](nil, false) diff --git a/pkg/validation/options_test.go b/pkg/validation/options_test.go index 6657e847..5ea748c1 100644 --- a/pkg/validation/options_test.go +++ b/pkg/validation/options_test.go @@ -69,7 +69,7 @@ func TestGoogleGroupOptionsWithoutServiceAccountJSON(t *testing.T) { func TestGoogleGroupOptionsWithoutAdminEmail(t *testing.T) { o := testOptions() - o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.Ptr(true) + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.To(true) err := Validate(o) assert.NotEqual(t, nil, err) @@ -82,7 +82,7 @@ func TestGoogleGroupOptionsWithoutGroups(t *testing.T) { o := testOptions() // Set admin email and application default credentials but no groups - should still require them o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" - o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.Ptr(true) + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.To(true) err := Validate(o) // Should pass validation since google-group is now optional assert.Equal(t, nil, err) diff --git a/pkg/validation/upstreams_test.go b/pkg/validation/upstreams_test.go index 580e2f29..79b29a22 100644 --- a/pkg/validation/upstreams_test.go +++ b/pkg/validation/upstreams_test.go @@ -26,7 +26,7 @@ var _ = Describe("Upstreams", func() { validStaticUpstream := options.Upstream{ ID: "validStaticUpstream", Path: "/validStaticUpstream", - Static: ptr.Ptr(true), + Static: ptr.To(true), } validFileUpstream := options.Upstream{ ID: "validFileUpstream", @@ -145,11 +145,11 @@ var _ = Describe("Upstreams", func() { ID: "foo", Path: "/foo", URI: "ftp://foo", - Static: ptr.Ptr(true), + Static: ptr.To(true), FlushInterval: &flushInterval, - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), - InsecureSkipTLSVerify: ptr.Ptr(true), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), + InsecureSkipTLSVerify: ptr.To(true), }, }, }, diff --git a/providers/adfs_test.go b/providers/adfs_test.go index edcb9307..75be7d0b 100644 --- a/providers/adfs_test.go +++ b/providers/adfs_test.go @@ -173,7 +173,7 @@ var _ = Describe("ADFS Provider Tests", func() { ProtectedResource: resource, Scope: "", }, options.Provider{ - ADFSConfig: options.ADFSOptions{SkipScope: ptr.Ptr(true)}, + ADFSConfig: options.ADFSOptions{SkipScope: ptr.To(true)}, }) result := p.GetLoginURL("https://example.com/adfs/oauth2/", "", "", url.Values{}) diff --git a/providers/ms_entra_id_test.go b/providers/ms_entra_id_test.go index 7b720c91..b153006e 100644 --- a/providers/ms_entra_id_test.go +++ b/providers/ms_entra_id_test.go @@ -25,7 +25,7 @@ func TestAzureEntraOIDCProviderNewMultiTenant(t *testing.T) { provider := NewMicrosoftEntraIDProvider(&ProviderData{}, options.Provider{OIDCConfig: options.OIDCOptions{ IssuerURL: "https://login.microsoftonline.com/common/v2.0", - InsecureSkipIssuerVerification: ptr.Ptr(true), + InsecureSkipIssuerVerification: ptr.To(true), }}, ) g.Expect(provider.Data().ProviderName).To(Equal("Microsoft Entra ID")) @@ -91,8 +91,8 @@ func TestAzureEntraOIDCProviderValidateSessionAllowedTenants(t *testing.T) { options.Provider{ OIDCConfig: options.OIDCOptions{ IssuerURL: "https://login.microsoftonline.com/common/v2.0", - InsecureSkipIssuerVerification: ptr.Ptr(true), - InsecureSkipNonce: ptr.Ptr(true), + InsecureSkipIssuerVerification: ptr.To(true), + InsecureSkipNonce: ptr.To(true), }, MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ AllowedTenants: []string{"85d7d600-7804-4d92-8d43-9c33c21c130c"}, diff --git a/providers/providers_test.go b/providers/providers_test.go index 9591dc65..8e3b8d77 100644 --- a/providers/providers_test.go +++ b/providers/providers_test.go @@ -82,7 +82,7 @@ func TestSkipOIDCDiscovery(t *testing.T) { ClientSecretFile: clientSecret, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: ptr.Ptr(true), + SkipDiscovery: ptr.To(true), }, } @@ -109,7 +109,7 @@ func TestURLsCorrectlyParsed(t *testing.T) { RedeemURL: msTokenURL, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: ptr.Ptr(true), + SkipDiscovery: ptr.To(true), JwksURL: msKeysURL, }, } @@ -217,7 +217,7 @@ func TestScope(t *testing.T) { AllowedGroups: tc.allowedGroups, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: ptr.Ptr(true), + SkipDiscovery: ptr.To(true), JwksURL: msKeysURL, }, } @@ -298,7 +298,7 @@ func TestEmailClaimCorrectlySet(t *testing.T) { RedeemURL: msTokenURL, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: ptr.Ptr(true), + SkipDiscovery: ptr.To(true), JwksURL: msKeysURL, UserIDClaim: tc.userIDClaim, EmailClaim: tc.emailClaim, From 15041dd116456b2d66440f4f96991aa226f8b4f1 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 16 Nov 2025 22:36:05 +0100 Subject: [PATCH 129/130] feat: migrate google used organization id and header normalization booleans to pointers Signed-off-by: Jan Larwig --- main_test.go | 3 ++- pkg/apis/options/header.go | 4 +++- pkg/apis/options/legacy_options.go | 2 +- pkg/apis/options/legacy_options_test.go | 2 ++ pkg/apis/options/providers.go | 8 +++++++- pkg/middleware/headers.go | 2 +- pkg/middleware/headers_test.go | 2 +- providers/google.go | 4 ++-- 8 files changed, 19 insertions(+), 8 deletions(-) diff --git a/main_test.go b/main_test.go index dce11fcc..cbe79683 100644 --- a/main_test.go +++ b/main_test.go @@ -169,8 +169,9 @@ redirect_url="http://localhost:4180/oauth2/callback" SkipClaimsFromProfileURL: ptr.To(false), GoogleConfig: options.GoogleOptions{ AdminEmail: "admin@example.com", - UseApplicationDefaultCredentials: ptr.To(false), TargetPrincipal: "principal", + UseOrganizationID: ptr.To(false), + UseApplicationDefaultCredentials: ptr.To(false), }, AzureConfig: options.AzureOptions{ Tenant: "common", diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 52552397..d9509de0 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -5,6 +5,8 @@ import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" const ( // DefaultHeaderPreserveRequestValue is the default value for Header.PreserveRequestValue DefaultHeaderPreserveRequestValue bool = false + // DefaultInsecureSkipHeaderNormalization is the default value for Header.InsecureSkipHeaderNormalization + DefaultInsecureSkipHeaderNormalization bool = false ) // Header represents an individual header that will be added to a request or @@ -28,7 +30,7 @@ type Header struct { // treated as the same header. Additionally underscores (_) in header names // will be converted to dashes (-) when normalizing. // Defaults to false (header names will be normalized). - InsecureSkipHeaderNormalization bool `json:"InsecureSkipHeaderNormalization,omitempty"` + InsecureSkipHeaderNormalization *bool `yaml:"InsecureSkipHeaderNormalization,omitempty"` // Values contains the desired values for this header Values []HeaderValue `yaml:"values,omitempty"` diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 0f9f0829..6ce730fd 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -789,7 +789,7 @@ func (l *LegacyProvider) convert() (Providers, error) { ServiceAccountJSON: l.GoogleServiceAccountJSON, UseApplicationDefaultCredentials: &l.GoogleUseApplicationDefaultCredentials, TargetPrincipal: l.GoogleTargetPrincipal, - UseOrganizationID: l.GoogleUseOrganizationID, + UseOrganizationID: &l.GoogleUseOrganizationID, AdminAPIUserScope: l.GoogleAdminAPIUserScope, } case "entra-id": diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 3fe9c1e5..ceba53af 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -955,6 +955,7 @@ var _ = Describe("Legacy Options", func() { } defaultGoogleOptions := GoogleOptions{ + UseOrganizationID: ptr.To(false), UseApplicationDefaultCredentials: ptr.To(false), } @@ -1020,6 +1021,7 @@ var _ = Describe("Legacy Options", func() { AdminEmail: "email@email.com", ServiceAccountJSON: "test.json", Groups: []string{"1", "2"}, + UseOrganizationID: ptr.To(false), UseApplicationDefaultCredentials: ptr.To(false), }, LoginURLParameters: defaultURLParams, diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 2d89eb2c..4dd206e2 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -37,6 +37,10 @@ const ( // for MicrosoftEntraIDOptions.FederatedTokenAuth DefaultMicrosoftEntraIDUseFederatedToken bool = false + // DefaultGoogleUseOrganizationID is the default value + // for GoogleOptions.UseOrganizationID + DefaultGoogleUseOrganizationID bool = false + // DefaultGoogleUseApplicationDefaultCredentials is the default values // for GoogleOptions.UseApplicationDefaultCredentials DefaultUseApplicationDefaultCredentials bool = false @@ -269,7 +273,7 @@ type GoogleOptions struct { // TargetPrincipal is the Google Service Account used for Application Default Credentials TargetPrincipal string `yaml:"targetPrincipal,omitempty"` // UseOrganizationId indicates whether to use the organization ID as the UserName claim - UseOrganizationID bool `yaml:"useOrganizationID,omitempty"` + UseOrganizationID *bool `yaml:"useOrganizationID,omitempty"` // admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly AdminAPIUserScope string `yaml:"adminAPIUserScope,omitempty"` } @@ -412,6 +416,8 @@ func (a *ADFSOptions) EnsureDefaults() { // EnsureDefaults sets any default values for GoogleOptions fields. func (g *GoogleOptions) EnsureDefaults() { + g.UseOrganizationID = ptr.To(DefaultGoogleUseOrganizationID) + if g.UseApplicationDefaultCredentials == nil { g.UseApplicationDefaultCredentials = ptr.To(DefaultUseApplicationDefaultCredentials) } diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index b567f4f5..39f8367a 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -54,7 +54,7 @@ func flattenHeaders(headers http.Header) { func stripHeaders(headers []options.Header, next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { for _, header := range headers { - if header.InsecureSkipHeaderNormalization { + if ptr.Deref(header.InsecureSkipHeaderNormalization, options.DefaultInsecureSkipHeaderNormalization) { req.Header.Del(header.Name) continue } diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 393ade9c..c3c402f0 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -231,7 +231,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "X-Auth-Request-User", - InsecureSkipHeaderNormalization: true, + InsecureSkipHeaderNormalization: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{Claim: "user"}, diff --git a/providers/google.go b/providers/google.go index 92d78224..d8e4dec8 100644 --- a/providers/google.go +++ b/providers/google.go @@ -109,11 +109,11 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv }, } - if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { + if ptr.Deref(opts.UseOrganizationID, options.DefaultGoogleUseOrganizationID) || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { // reuse admin service to avoid multiple calls for token var adminService *admin.Service - if opts.UseOrganizationID { + if ptr.Deref(opts.UseOrganizationID, options.DefaultGoogleUseOrganizationID) { // add user scopes to admin api userScope := getAdminAPIUserScope(opts.AdminAPIUserScope) for index, scope := range possibleScopesList { From aee540a27741090b28bad3952d752dee8f65ad20 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 28 Nov 2025 17:20:15 +0100 Subject: [PATCH 130/130] doc: fix mapstructure configuration comments Signed-off-by: Jan Larwig --- pkg/apis/options/load.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 20d04383..d0dd22df 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -95,10 +95,10 @@ func Decode(input interface{}, result interface{}) error { ), Metadata: nil, // Don't track any metadata Result: result, // Decode the result into the prefilled options - TagName: "yaml", // Parse all fields that use the json tag + TagName: "yaml", // Parse all fields that use the yaml tag ZeroFields: false, // Don't clean the default values from the result map (options) ErrorUnused: true, // Throw an error if keys have been used that aren't mapped to any struct fields - IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with json + IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with yaml }) if err != nil { return fmt.Errorf("error creating decoder for config: %w", err)