Skip to content

Commit

Permalink
Fix labstack#1523 by adding secure cookie if SameSite mode is None
Browse files Browse the repository at this point in the history
  • Loading branch information
pr0head committed Dec 3, 2020
1 parent cb15226 commit dc147d9
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
4 changes: 2 additions & 2 deletions middleware/csrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc {
if config.CookieMaxAge == 0 {
config.CookieMaxAge = DefaultCSRFConfig.CookieMaxAge
}
if config.CookieSameSite == 0 {
config.CookieSameSite = http.SameSiteDefaultMode
if config.CookieSameSite == http.SameSiteNoneMode {
config.CookieSecure = true
}

// Initialize
Expand Down
41 changes: 41 additions & 0 deletions middleware/csrf_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package middleware

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
Expand Down Expand Up @@ -117,3 +118,43 @@ func TestCSRFWithoutSameSiteMode(t *testing.T) {
assert.NoError(t, r)
assert.NotRegexp(t, "SameSite=", rec.Header()["Set-Cookie"])
}

func TestCSRFWithSameSiteDefaultMode(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

csrf := CSRFWithConfig(CSRFConfig{
CookieSameSite: http.SameSiteDefaultMode,
})

h := csrf(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})

r := h(c)
assert.NoError(t, r)
fmt.Println(rec.Header()["Set-Cookie"])
assert.NotRegexp(t, "SameSite=", rec.Header()["Set-Cookie"])
}

func TestCSRFWithSameSiteModeNone(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

csrf := CSRFWithConfig(CSRFConfig{
CookieSameSite: http.SameSiteNoneMode,
})

h := csrf(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})

r := h(c)
assert.NoError(t, r)
assert.Regexp(t, "SameSite=None", rec.Header()["Set-Cookie"])
assert.Regexp(t, "Secure", rec.Header()["Set-Cookie"])
}

0 comments on commit dc147d9

Please sign in to comment.