git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge pull request #339 from clubhouse/pgroudas/add-samesite-cookie-options

Add SameSite cookie configuration value for session cookie

commitec72ee8bf1b91a5ccd444ad4cf9bc5fab917fe0b authorJoel Speed <Joel.speed@hotmail.co.uk> dateMon 20 Jan 2020, 19:24 (7 years ago) parent038ee1617d9961
9 files changed+49−8
CHANGELOG.md+2 contrib/oauth2_proxy_autocomplete.sh+1−1 docs/configuration/configuration.md+1 main.go+1 oauthproxy.go+6−2 options.go+6 pkg/apis/options/cookie.go+1 pkg/cookies/cookies.go+21−3 pkg/sessions/session_store_test.go+10−2
CHANGELOG.md+2
@@ -5,6 +5,8 @@
55## Breaking Changes
66
77## Changes since v4.1.0
8+
9+- [#339](https://github.com/pusher/oauth2_proxy/pull/339) Add configuration for cookie 'SameSite' value. (@pgroudas)
810- [#347](https://github.com/pusher/oauth2_proxy/pull/347) Update keycloak provider configuration documentation
911- [#325](https://github.com/pusher/oauth2_proxy/pull/325) dist.sh: use sha256sum (@syscll)
1012- [#179](https://github.com/pusher/oauth2_proxy/pull/179) Add Nextcloud provider (@Ramblurr)
contrib/oauth2_proxy_autocomplete.sh+1−1
@@ -20,7 +20,7 @@ _oauth2_proxy() {
2020 COMPREPLY=( $(compgen -W "google azure facebook github keycloak gitlab linkedin login.gov digitalocean" -- ${cur}) )
2121 return 0
2222 ;;
23− -@(http-address|https-address|redirect-url|upstream|basic-auth-password|skip-auth-regex|flush-interval|extra-jwt-issuers|email-domain|whitelist-domain|keycloak-group|azure-tenant|bitbucket-team|bitbucket-repository|github-org|github-team|gitlab-group|google-group|google-admin-email|google-service-account-json|client-id|client_secret|banner|footer|proxy-prefix|ping-path|cookie-name|cookie-secret|cookie-domain|cookie-path|cookie-expire|cookie-refresh|redist-sentinel-master-name|redist-sentinel-connection-urls|logging-max-size|logging-max-age|logging-max-backups|standard-logging-format|request-logging-format|exclude-logging-paths|auth-logging-format|oidc-issuer-url|oidc-jwks-url|login-url|redeem-url|profile-url|resource|validate-url|scope|approval-prompt|signature-key|acr-values|jwt-key|pubjwk-url))
23+ -@(http-address|https-address|redirect-url|upstream|basic-auth-password|skip-auth-regex|flush-interval|extra-jwt-issuers|email-domain|whitelist-domain|keycloak-group|azure-tenant|bitbucket-team|bitbucket-repository|github-org|github-team|gitlab-group|google-group|google-admin-email|google-service-account-json|client-id|client_secret|banner|footer|proxy-prefix|ping-path|cookie-name|cookie-secret|cookie-domain|cookie-path|cookie-expire|cookie-refresh|cookie-samesite|redist-sentinel-master-name|redist-sentinel-connection-urls|logging-max-size|logging-max-age|logging-max-backups|standard-logging-format|request-logging-format|exclude-logging-paths|auth-logging-format|oidc-issuer-url|oidc-jwks-url|login-url|redeem-url|profile-url|resource|validate-url|scope|approval-prompt|signature-key|acr-values|jwt-key|pubjwk-url))
2424 return 0
2525 ;;
2626 esac
docs/configuration/configuration.md+1
@@ -38,6 +38,7 @@ An example [oauth2_proxy.cfg]({{ site.gitweb }}/contrib/oauth2_proxy.cfg.example
3838| `-cookie-refresh` | duration | refresh the cookie after this duration; `0` to disable | |
3939| `-cookie-secret` | string | the seed string for secure cookies (optionally base64 encoded) | |
4040| `-cookie-secure` | bool | set secure (HTTPS) cookie flag | true |
41+| `-cookie-samesite` | string | set SameSite cookie attribute (ie: `"lax"`, `"strict"`, `"none"`, or `""`). | `""` |
4142| `-custom-templates-dir` | string | path to custom html templates | |
4243| `-display-htpasswd-form` | bool | display username / password login form if an htpasswd file is provided | true |
4344| `-email-domain` | string | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | |
main.go+1
@@ -86,6 +86,7 @@ func main() {
8686 flagSet.Duration("cookie-refresh", time.Duration(0), "refresh the cookie after this duration; 0 to disable")
8787 flagSet.Bool("cookie-secure", true, "set secure (HTTPS) cookie flag")
8888 flagSet.Bool("cookie-httponly", true, "set HttpOnly cookie flag")
89+ flagSet.String("cookie-samesite", "", "set SameSite cookie attribute (ie: \"lax\", \"strict\", \"none\", or \"\"). ")
8990
9091 flagSet.String("session-store-type", "cookie", "the session storage provider to use")
9192 flagSet.String("redis-connection-url", "", "URL of redis server for redis session storage (eg: redis://HOST[:PORT])")
oauthproxy.go+6−2
@@ -20,6 +20,7 @@ import (
2020 "github.com/coreos/go-oidc"
2121 "github.com/mbland/hmacauth"
2222 sessionsapi "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
23+ "github.com/pusher/oauth2_proxy/pkg/cookies"
2324 "github.com/pusher/oauth2_proxy/pkg/encryption"
2425 "github.com/pusher/oauth2_proxy/pkg/logger"
2526 "github.com/pusher/oauth2_proxy/providers"
@@ -68,6 +69,7 @@ type OAuthProxy struct {
6869 CookieHTTPOnly bool
6970 CookieExpire time.Duration
7071 CookieRefresh time.Duration
72+ CookieSameSite string
7173 Validator func(string) bool
7274
7375 RobotsPath string
@@ -195,7 +197,7 @@ func NewWebSocketOrRestReverseProxy(u *url.URL, opts *Options, auth hmacauth.Hma
195197 }
196198}
197199
198−// NewOAuthProxy creates a new instance of OOuthProxy from the options provided
200+// NewOAuthProxy creates a new instance of OAuthProxy from the options provided
199201func NewOAuthProxy(opts *Options, validator func(string) bool) *OAuthProxy {
200202 serveMux := http.NewServeMux()
201203 var auth hmacauth.HmacAuth
@@ -260,7 +262,7 @@ func NewOAuthProxy(opts *Options, validator func(string) bool) *OAuthProxy {
260262 refresh = fmt.Sprintf("after %s", opts.CookieRefresh)
261263 }
262264
263− logger.Printf("Cookie settings: name:%s secure(https):%v httponly:%v expiry:%s domain:%s path:%s refresh:%s", opts.CookieName, opts.CookieSecure, opts.CookieHTTPOnly, opts.CookieExpire, opts.CookieDomain, opts.CookiePath, refresh)
265+ logger.Printf("Cookie settings: name:%s secure(https):%v httponly:%v expiry:%s domain:%s path:%s samesite:%s refresh:%s", opts.CookieName, opts.CookieSecure, opts.CookieHTTPOnly, opts.CookieExpire, opts.CookieDomain, opts.CookiePath, opts.CookieSameSite, refresh)
264266
265267 return &OAuthProxy{
266268 CookieName: opts.CookieName,
@@ -272,6 +274,7 @@ func NewOAuthProxy(opts *Options, validator func(string) bool) *OAuthProxy {
272274 CookieHTTPOnly: opts.CookieHTTPOnly,
273275 CookieExpire: opts.CookieExpire,
274276 CookieRefresh: opts.CookieRefresh,
277+ CookieSameSite: opts.CookieSameSite,
275278 Validator: validator,
276279
277280 RobotsPath: "/robots.txt",
@@ -380,6 +383,7 @@ func (p *OAuthProxy) makeCookie(req *http.Request, name string, value string, ex
380383 HttpOnly: p.CookieHTTPOnly,
381384 Secure: p.CookieSecure,
382385 Expires: now.Add(expiration),
386+ SameSite: cookies.ParseSameSite(p.CookieSameSite),
383387 }
384388}
385389
options.go+6
@@ -372,6 +372,12 @@ func (o *Options) Validate() error {
372372 }
373373 }
374374
375+ switch o.CookieSameSite {
376+ case "", "none", "lax", "strict":
377+ default:
378+ msgs = append(msgs, fmt.Sprintf("cookie_samesite (%s) must be one of ['', 'lax', 'strict', 'none']", o.CookieSameSite))
379+ }
380+
375381 msgs = parseSignatureKey(o, msgs)
376382 msgs = validateCookieName(o, msgs)
377383 msgs = setupLogger(o, msgs)
pkg/apis/options/cookie.go+1
@@ -12,4 +12,5 @@ type CookieOptions struct {
1212 CookieRefresh time.Duration `flag:"cookie-refresh" cfg:"cookie_refresh" env:"OAUTH2_PROXY_COOKIE_REFRESH"`
1313 CookieSecure bool `flag:"cookie-secure" cfg:"cookie_secure" env:"OAUTH2_PROXY_COOKIE_SECURE"`
1414 CookieHTTPOnly bool `flag:"cookie-httponly" cfg:"cookie_httponly" env:"OAUTH2_PROXY_COOKIE_HTTPONLY"`
15+ CookieSameSite string `flag:"cookie-samesite" cfg:"cookie_samesite" env:"OAUTH2_PROXY_COOKIE_SAMESITE"`
1516}
pkg/cookies/cookies.go+21−3
@@ -1,6 +1,7 @@
11package cookies
22
33import (
4+ "fmt"
45 "net"
56 "net/http"
67 "strings"
@@ -12,7 +13,7 @@ import (
1213
1314// MakeCookie constructs a cookie from the given parameters,
1415// discovering the domain from the request if not specified.
15−func MakeCookie(req *http.Request, name string, value string, path string, domain string, httpOnly bool, secure bool, expiration time.Duration, now time.Time) *http.Cookie {
16+func MakeCookie(req *http.Request, name string, value string, path string, domain string, httpOnly bool, secure bool, expiration time.Duration, now time.Time, sameSite http.SameSite) *http.Cookie {
1617 if domain != "" {
1718 host := req.Host
1819 if h, _, err := net.SplitHostPort(host); err == nil {
@@ -31,11 +32,28 @@ func MakeCookie(req *http.Request, name string, value string, path string, domai
3132 HttpOnly: httpOnly,
3233 Secure: secure,
3334 Expires: now.Add(expiration),
35+ SameSite: sameSite,
3436 }
3537}
3638
37−// MakeCookieFromOptions constructs a cookie based on the givemn *options.CookieOptions,
39+// MakeCookieFromOptions constructs a cookie based on the given *options.CookieOptions,
3840// value and creation time
3941func MakeCookieFromOptions(req *http.Request, name string, value string, opts *options.CookieOptions, expiration time.Duration, now time.Time) *http.Cookie {
40− return MakeCookie(req, name, value, opts.CookiePath, opts.CookieDomain, opts.CookieHTTPOnly, opts.CookieSecure, expiration, now)
42+ return MakeCookie(req, name, value, opts.CookiePath, opts.CookieDomain, opts.CookieHTTPOnly, opts.CookieSecure, expiration, now, ParseSameSite(opts.CookieSameSite))
43+}
44+
45+// Parse a valid http.SameSite value from a user supplied string for use of making cookies.
46+func ParseSameSite(v string) http.SameSite {
47+ switch v {
48+ case "lax":
49+ return http.SameSiteLaxMode
50+ case "strict":
51+ return http.SameSiteStrictMode
52+ case "none":
53+ return http.SameSiteNoneMode
54+ case "":
55+ return http.SameSiteDefaultMode
56+ default:
57+ panic(fmt.Sprintf("Invalid value for SameSite: %s", v))
58+ }
4159}
pkg/sessions/session_store_test.go+10−2
@@ -15,7 +15,7 @@ import (
1515 . "github.com/onsi/gomega"
1616 "github.com/pusher/oauth2_proxy/pkg/apis/options"
1717 sessionsapi "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
18− "github.com/pusher/oauth2_proxy/pkg/cookies"
18+ cookiesapi "github.com/pusher/oauth2_proxy/pkg/cookies"
1919 "github.com/pusher/oauth2_proxy/pkg/encryption"
2020 "github.com/pusher/oauth2_proxy/pkg/sessions"
2121 sessionscookie "github.com/pusher/oauth2_proxy/pkg/sessions/cookie"
@@ -79,6 +79,12 @@ var _ = Describe("NewSessionStore", func() {
7979 }
8080 })
8181
82+ It("have the correct SameSite set", func() {
83+ for _, cookie := range cookies {
84+ Expect(cookie.SameSite).To(Equal(cookiesapi.ParseSameSite(cookieOpts.CookieSameSite)))
85+ }
86+ })
87+
8288 It("have a signature timestamp matching session.CreatedAt", func() {
8389 for _, cookie := range cookies {
8490 if cookie.Value != "" {
@@ -159,7 +165,7 @@ var _ = Describe("NewSessionStore", func() {
159165 By("Using a valid cookie with a different providers session encoding")
160166 broken := "BrokenSessionFromADifferentSessionImplementation"
161167 value := encryption.SignedValue(cookieOpts.CookieSecret, cookieOpts.CookieName, broken, time.Now())
162− cookie := cookies.MakeCookieFromOptions(request, cookieOpts.CookieName, value, cookieOpts, cookieOpts.CookieExpire, time.Now())
168+ cookie := cookiesapi.MakeCookieFromOptions(request, cookieOpts.CookieName, value, cookieOpts, cookieOpts.CookieExpire, time.Now())
163169 request.AddCookie(cookie)
164170
165171 err := ss.Save(response, request, session)
@@ -338,6 +344,7 @@ var _ = Describe("NewSessionStore", func() {
338344 CookieSecure: false,
339345 CookieHTTPOnly: false,
340346 CookieDomain: "example.com",
347+ CookieSameSite: "strict",
341348 }
342349
343350 var err error
@@ -379,6 +386,7 @@ var _ = Describe("NewSessionStore", func() {
379386 CookieRefresh: time.Duration(1) * time.Hour,
380387 CookieSecure: true,
381388 CookieHTTPOnly: true,
389+ CookieSameSite: "",
382390 }
383391
384392 session = &sessionsapi.SessionState{