Add cookie-csrf-samesite option

Most of the code is copied form pull request #1947

Signed-off-by: Joost <439100+jvnoije@users.noreply.github.com>
This commit is contained in:
Joost 2026-02-20 11:18:39 +01:00
parent 17896700ba
commit d0a07642ac
12 changed files with 295 additions and 8 deletions

View File

@ -2,13 +2,18 @@
## Release Highlights
- It is now possible to set a SameSite in CSRF cookie different from the one defined for the session cookie.
## Important Notes
- [#](https://github.com/oauth2-proxy/oauth2-proxy/pull/) New option "--cookie-csrf-samesite" added, to define the SameSite value of CSRF cookie. If option is not configured, then CSRF cookie SameSite is equal to the one configured for the session cookie.
## Breaking Changes
## Changes since v7.14.2
- [#3183](https://github.com/oauth2-proxy/oauth2-proxy/pull/3183) fix: allow URL parameters to configure username, password and max idle connection timeout if the matching configuration is empty.
- [#](https://github.com/oauth2-proxy/oauth2-proxy/pull/) Added new option to configure the SameSite value of CSRF cookie (e.g.: "--cookie-csrf-samesite").
# V7.14.2

View File

@ -83,7 +83,7 @@ Provider specific options can be found on their respective subpages.
| flag: `--approval-prompt`<br/>toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` |
| flag: `--backend-logout-url`<br/>toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | |
| flag: `--client-id`<br/>toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | |
| flag: `--client-secret-file`<br/>toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | |
| flag: `--client-secret-file`<br/>toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | |
| flag: `--client-secret`<br/>toml: `client_secret` | string | the OAuth Client Secret | |
| flag: `--code-challenge-method`<br/>toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | |
| flag: `--insecure-oidc-allow-unverified-email`<br/>toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false |
@ -102,7 +102,7 @@ Provider specific options can be found on their respective subpages.
| flag: `--oidc-public-key-file`<br/>toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list |
| flag: `--profile-url`<br/>toml: `profile_url` | string | Profile access endpoint | |
| flag: `--prompt`<br/>toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` |
| flag: `--provider-ca-file`<br/>toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. |
| flag: `--provider-ca-file`<br/>toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | |
| flag: `--provider-display-name`<br/>toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) |
| flag: `--provider`<br/>toml: `provider` | string | OAuth provider | google |
| flag: `--pubjwk-url`<br/>toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | |
@ -121,6 +121,7 @@ Provider specific options can be found on their respective subpages.
| flag: `--cookie-csrf-per-request`<br/>toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false |
| flag: `--cookie-csrf-per-request-limit`<br/>toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" |
| flag: `--cookie-domain`<br/>toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | |
| flag: `--cookie-csrf-samesite`<br/>toml: `cookie_csrf_samesite` | string | set SameSite CSRF cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). When using the default setting, the CSRF cookie samesite value is taken from the session cookie configuration. | `""` |
| flag: `--cookie-expire`<br/>toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s |
| flag: `--cookie-httponly`<br/>toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true |
| flag: `--cookie-name`<br/>toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` |
@ -128,7 +129,7 @@ Provider specific options can be found on their respective subpages.
| flag: `--cookie-refresh`<br/>toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers&nbsp;[^1] | |
| flag: `--cookie-samesite`<br/>toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` |
| flag: `--cookie-secret`<br/>toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | |
| flag: `--cookie-secret-file`<br/>toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | |
| flag: `--cookie-secret-file`<br/>toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | |
| flag: `--cookie-secure`<br/>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)
@ -174,7 +175,7 @@ Provider specific options can be found on their respective subpages.
| Flag / Config Field | Type | Description | Default |
| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- |
| flag: `--banner`<br/>toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | |
| flag: `--custom-sign-in-logo`<br/>toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. |
| flag: `--custom-sign-in-logo`<br/>toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | |
| flag: `--custom-templates-dir`<br/>toml: `custom_templates_dir` | string | path to custom html templates | |
| flag: `--display-htpasswd-form`<br/>toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true |
| flag: `--footer`<br/>toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | |

View File

@ -24,6 +24,7 @@ type Cookie struct {
CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"`
CSRFPerRequestLimit int `flag:"cookie-csrf-per-request-limit" cfg:"cookie_csrf_per_request_limit"`
CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"`
CSRFSameSite string `flag:"cookie-csrf-samesite" cfg:"cookie_csrf_samesite"`
}
func cookieFlagSet() *pflag.FlagSet {
@ -42,6 +43,7 @@ func cookieFlagSet() *pflag.FlagSet {
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")
flagSet.String("cookie-csrf-samesite", "", "set SameSite CSRF cookie attribute (ie: \"lax\", \"strict\", \"none\", or \"\"). When using the default setting, the CSRF cookie samesite value is taken from the session cookie configuration.")
return flagSet
}
@ -61,6 +63,7 @@ func cookieDefaults() Cookie {
CSRFPerRequest: false,
CSRFPerRequestLimit: 0,
CSRFExpire: time.Duration(15) * time.Minute,
CSRFSameSite: "",
}
}

View File

@ -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) *http.Cookie {
func MakeCookieFromOptions(req *http.Request, name string, value string, opts *options.Cookie, expiration time.Duration, sameSite string) *http.Cookie {
domain := GetCookieDomain(req, opts.Domains)
// If nothing matches, create the cookie with the shortest domain
if domain == "" && len(opts.Domains) > 0 {
@ -32,7 +32,7 @@ func MakeCookieFromOptions(req *http.Request, name string, value string, opts *o
Domain: domain,
HttpOnly: opts.HTTPOnly,
Secure: opts.Secure,
SameSite: ParseSameSite(opts.SameSite),
SameSite: ParseSameSite(sameSite),
}
if expiration > time.Duration(0) {

View File

@ -17,6 +17,10 @@ const (
cookieDomain = "o2p.cookies.test"
cookiePath = "/cookie-tests"
sameSiteLax = "lax"
sameSiteStrict = "strict"
sameSiteNone = "none"
nowEpoch = 1609366421
)

View File

@ -106,7 +106,7 @@ var _ = Describe("Cookie Tests", func() {
)
Expect(err).ToNot(HaveOccurred())
Expect(MakeCookieFromOptions(req, in.name, in.value, &in.opts, in.expiration).MaxAge).To(Equal(in.expectedOutput))
Expect(MakeCookieFromOptions(req, in.name, in.value, &in.opts, in.expiration, in.opts.SameSite).MaxAge).To(Equal(in.expectedOutput))
},
Entry("persistent cookie", makeCookieFromOptionsTableInput{
host: "www.cookies.test",

View File

@ -134,6 +134,15 @@ func (c *csrf) SetSessionNonce(s *sessions.SessionState) {
s.Nonce = c.OIDCNonce
}
// getCSRFSameSite get the CSRF same site
func getCSRFSameSite(opts *options.Cookie) string {
sameSite := opts.CSRFSameSite
if sameSite == "" {
sameSite = opts.SameSite
}
return sameSite
}
// SetCookie encodes the CSRF to a signed cookie and sets it on the ResponseWriter
func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cookie, error) {
encoded, err := c.encodeCookie()
@ -147,6 +156,7 @@ func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cooki
encoded,
c.cookieOpts,
c.cookieOpts.CSRFExpire,
getCSRFSameSite(c.cookieOpts),
)
http.SetCookie(rw, cookie)
@ -203,6 +213,7 @@ func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) {
"",
c.cookieOpts,
time.Hour*-1,
getCSRFSameSite(c.cookieOpts),
))
}

View File

@ -222,6 +222,7 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() {
encoded,
csrf.cookieOpts,
csrf.cookieOpts.CSRFExpire,
csrf.cookieOpts.CSRFSameSite,
)
cookies = append(cookies, fmt.Sprintf("%v=%v", cookie.Name, cookie.Value))
}

View File

@ -254,4 +254,263 @@ var _ = Describe("CSRF Cookie Tests", func() {
})
})
})
Context("Test Cookie SameSite", func() {
var req *http.Request
var cookieOpts *options.Cookie
testNow := time.Unix(nowEpoch, 0)
BeforeEach(func() {
// we need to reset the time to ensure the cookie is valid
privateCSRF.clock = time.Now
req = &http.Request{
Method: http.MethodGet,
Proto: "HTTP/1.1",
Host: cookieDomain,
URL: &url.URL{
Scheme: "https",
Host: cookieDomain,
Path: cookiePath,
},
}
cookieOpts = &options.Cookie{
Name: cookieName,
Secret: cookieSecret,
Domains: []string{cookieDomain},
Path: cookiePath,
Expire: time.Hour,
Secure: true,
HTTPOnly: true,
CSRFPerRequest: false,
CSRFExpire: time.Hour,
}
})
It("Call SetCookie when CSRF SameSite is not defined. Expected result: CSRF cookie SameSite is the same as session cookie.", func() {
// prepare
cookieOpts.SameSite = sameSiteLax
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
_, err := CSRF.SetCookie(rw, req)
// validate
Expect(err).ToNot(HaveOccurred())
Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
fmt.Sprintf(
"; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Lax",
cookiePath,
cookieDomain,
int(cookieOpts.CSRFExpire.Seconds()),
),
))
})
It("Call SetCookie when CSRF SameSite is an empty string. Expected result: CSRF cookie SameSite is the same as session cookie.", func() {
// prepare
cookieOpts.SameSite = sameSiteLax
cookieOpts.CSRFSameSite = ""
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
_, err := CSRF.SetCookie(rw, req)
// validate
Expect(err).ToNot(HaveOccurred())
Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
fmt.Sprintf(
"; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Lax",
cookiePath,
cookieDomain,
int(cookieOpts.CSRFExpire.Seconds()),
),
))
})
It("Call SetCookie when CSRF SameSite is 'none'. Expected result: CSRF cookie SameSite is None.", func() {
// prepare
cookieOpts.SameSite = sameSiteLax
cookieOpts.CSRFSameSite = sameSiteNone
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
_, err := CSRF.SetCookie(rw, req)
// validate
Expect(err).ToNot(HaveOccurred())
Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
fmt.Sprintf(
"; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=None",
cookiePath,
cookieDomain,
int(cookieOpts.CSRFExpire.Seconds()),
),
))
})
It("Call SetCookie when CSRF SameSite is 'strict'. Expected result: CSRF cookie SameSite is Strict.", func() {
// prepare
cookieOpts.SameSite = sameSiteLax
cookieOpts.CSRFSameSite = sameSiteStrict
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
_, err := CSRF.SetCookie(rw, req)
// validate
Expect(err).ToNot(HaveOccurred())
Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
fmt.Sprintf(
"; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Strict",
cookiePath,
cookieDomain,
int(cookieOpts.CSRFExpire.Seconds()),
),
))
})
It("Call SetCookie when CSRF SameSite is 'lax'. Expected result: CSRF cookie SameSite is Lax.", func() {
// prepare
cookieOpts.SameSite = sameSiteStrict
cookieOpts.CSRFSameSite = sameSiteLax
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
_, err := CSRF.SetCookie(rw, req)
// validate
Expect(err).ToNot(HaveOccurred())
Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
fmt.Sprintf(
"; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Lax",
cookiePath,
cookieDomain,
int(cookieOpts.CSRFExpire.Seconds()),
),
))
})
It("Call ClearCookie when CSRF SameSite is not defined. Expected result: CSRF cookie SameSite is the same as session cookie.", func() {
// prepare
cookieOpts.SameSite = sameSiteLax
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
CSRF.ClearCookie(rw, req)
// validate
Expect(rw.Header().Get("Set-Cookie")).To(Equal(
fmt.Sprintf(
"%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Lax",
CSRF.(*csrf).cookieName(),
cookiePath,
cookieDomain,
),
))
})
It("Call ClearCookie when CSRF SameSite is an empty string. Expected result: CSRF cookie SameSite is the same as session cookie.", func() {
// prepare
cookieOpts.SameSite = sameSiteLax
cookieOpts.CSRFSameSite = ""
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
CSRF.ClearCookie(rw, req)
// validate
Expect(rw.Header().Get("Set-Cookie")).To(Equal(
fmt.Sprintf(
"%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Lax",
CSRF.(*csrf).cookieName(),
cookiePath,
cookieDomain,
),
))
})
It("Call ClearCookie when CSRF SameSite is 'none'. Expected result: CSRF cookie SameSite is None.", func() {
// prepare
cookieOpts.SameSite = sameSiteLax
cookieOpts.CSRFSameSite = sameSiteNone
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
CSRF.ClearCookie(rw, req)
// validate
Expect(rw.Header().Get("Set-Cookie")).To(Equal(
fmt.Sprintf(
"%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=None",
CSRF.(*csrf).cookieName(),
cookiePath,
cookieDomain,
),
))
})
It("Call ClearCookie when CSRF SameSite is 'strict'. Expected result: CSRF cookie SameSite is Strict.", func() {
// prepare
cookieOpts.SameSite = sameSiteLax
cookieOpts.CSRFSameSite = sameSiteStrict
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
CSRF.ClearCookie(rw, req)
// validate
Expect(rw.Header().Get("Set-Cookie")).To(Equal(
fmt.Sprintf(
"%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Strict",
CSRF.(*csrf).cookieName(),
cookiePath,
cookieDomain,
),
))
})
It("Call ClearCookie when CSRF SameSite is 'lax'. Expected result: CSRF cookie SameSite is Lax.", func() {
// prepare
cookieOpts.SameSite = sameSiteStrict
cookieOpts.CSRFSameSite = sameSiteLax
CSRF, _ := NewCSRF(cookieOpts, "verifier")
rw := httptest.NewRecorder()
CSRF.(*csrf).clock = func() time.Time { return testNow }
// test
CSRF.ClearCookie(rw, req)
// validate
Expect(rw.Header().Get("Set-Cookie")).To(Equal(
fmt.Sprintf(
"%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Lax",
CSRF.(*csrf).cookieName(),
cookiePath,
cookieDomain,
),
))
})
})
})

View File

@ -146,6 +146,7 @@ func (s *SessionStore) makeCookie(req *http.Request, name string, value string,
value,
s.Cookie,
expiration,
s.Cookie.SameSite,
)
}

View File

@ -227,6 +227,7 @@ func (t *ticket) clearCookie(rw http.ResponseWriter, req *http.Request) {
"",
t.options,
time.Hour*-1,
t.options.SameSite,
))
}
@ -250,6 +251,7 @@ func (t *ticket) makeCookie(req *http.Request, value string, expires time.Durati
value,
t.options,
expires,
t.options.SameSite,
), nil
}

View File

@ -422,7 +422,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)
cookie := cookiesapi.MakeCookieFromOptions(in.request, in.cookieOpts.Name, value, in.cookieOpts, in.cookieOpts.Expire, in.cookieOpts.SameSite)
in.request.AddCookie(cookie)
err = in.ss().Save(in.response, in.request, in.session)