Skip to content

Commit

Permalink
fix(cookie): Add default samesite (#276)
Browse files Browse the repository at this point in the history
Sets the SameSite cookie attribute to None in the Set-Cookie header. The SameSite=None value provides a reasonable balance between security and usability for websites. This also requires setting Secure=True by default.

Reference: 
https://owasp.org/www-community/SameSite

Related Tickets & Documents
- Related Issue # #256
- Closes #256
  • Loading branch information
bharat-rajani authored Jun 15, 2024
1 parent bdabf0a commit ef99c78
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
1 change: 1 addition & 0 deletions cookie_go111_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ func TestNewCookieFromOptionsSameSite(t *testing.T) {
{http.SameSiteDefaultMode},
{http.SameSiteLaxMode},
{http.SameSiteStrictMode},
{http.SameSiteNoneMode},
}
for i, v := range tests {
options := &Options{
Expand Down
9 changes: 9 additions & 0 deletions sessions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"encoding/gob"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

Expand Down Expand Up @@ -39,6 +40,10 @@ func TestFlashes(t *testing.T) {

store := NewCookieStore([]byte("secret-key"))

if store.Options.SameSite != http.SameSiteNoneMode {
t.Fatalf("cookie store error: default same site is not set to None")
}

// Round 1 ----------------------------------------------------------------

req, _ = http.NewRequest("GET", "http://localhost:8080/", nil)
Expand Down Expand Up @@ -67,6 +72,10 @@ func TestFlashes(t *testing.T) {
t.Fatal("No cookies. Header:", hdr)
}

if !strings.Contains(cookies[0], "SameSite=None") || !strings.Contains(cookies[0], "Secure") {
t.Fatal("Set-Cookie does not contains SameSite=None with Secure, cookie string:", cookies[0])
}

if _, err = store.Get(req, "session:key"); err.Error() != "sessions: invalid character in cookie name: session:key" {
t.Fatalf("Expected error due to invalid cookie name")
}
Expand Down
6 changes: 4 additions & 2 deletions store.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ func NewCookieStore(keyPairs ...[]byte) *CookieStore {
cs := &CookieStore{
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: &Options{
Path: "/",
MaxAge: 86400 * 30,
Path: "/",
MaxAge: 86400 * 30,
SameSite: http.SameSiteNoneMode,
Secure: true,
},
}

Expand Down

0 comments on commit ef99c78

Please sign in to comment.