1
0
mirror of https://github.com/labstack/echo.git synced 2025-01-07 23:01:56 +02:00
echo/middleware/csrf_test.go
toimtoimtoim 6ef5f77bf2 WIP: logger examples
WIP: make default logger implemented custom writer for jsonlike logs
WIP: improve examples
WIP: defaultErrorHandler use errors.As to unwrap errors. Update readme
WIP: default logger logs json, restore e.Start method
WIP: clean router.Match a bit
WIP: func types/fields have echo.Context has first element
WIP: remove yaml tags as functions etc can not be serialized anyway
WIP: change BindPathParams,BindQueryParams,BindHeaders from methods to functions and reverse arguments to be like DefaultBinder.Bind is
WIP: improved comments, logger now extracts status from error
WIP: go mod tidy
WIP: rebase with 4.5.0
WIP:
* removed todos.
* removed StartAutoTLS and StartH2CServer methods from `StartConfig`
* KeyAuth middleware errorhandler can swallow the error and resume next middleware
WIP: add RouterConfig.UseEscapedPathForMatching to use escaped path for matching request against routes
WIP: FIXMEs
WIP: upgrade golang-jwt/jwt to `v4`
WIP: refactor http methods to return RouteInfo
WIP: refactor static not creating multiple routes
WIP: refactor route and middleware adding functions not to return error directly
WIP: Use 401 for problematic/missing headers for key auth and JWT middleware (#1552, #1402).
> In summary, a 401 Unauthorized response should be used for missing or bad authentication
WIP: replace `HTTPError.SetInternal` with `HTTPError.WithInternal` so we could not mutate global error variables
WIP: add RouteInfo and RouteMatchType into Context what we could know from in middleware what route was matched and/or type of that match (200/404/405)
WIP: make notFoundHandler and methodNotAllowedHandler private. encourage that all errors be handled in Echo.HTTPErrorHandler
WIP: server cleanup ideas
WIP: routable.ForGroup
WIP: note about logger middleware
WIP: bind should not default values on second try. use crypto rand for better randomness
WIP: router add route as interface and returns info as interface
WIP: improve flaky test (remains still flaky)
WIP: add notes about bind default values
WIP: every route can have their own path params names
WIP: routerCreator and different tests
WIP: different things
WIP: remove route implementation
WIP: support custom method types
WIP: extractor tests
WIP: v5.0.x proposal
over v4.4.0
2021-10-02 18:36:42 +03:00

177 lines
4.3 KiB
Go

package middleware
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestCSRF(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
csrf := CSRF()
h := csrf(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
// Generate CSRF token
h(c)
assert.Contains(t, rec.Header().Get(echo.HeaderSetCookie), "_csrf")
}
func TestMustCSRFWithConfig(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
csrf := CSRFWithConfig(CSRFConfig{
TokenLength: 16,
})
h := csrf(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
// Generate CSRF token
h(c)
assert.Contains(t, rec.Header().Get(echo.HeaderSetCookie), "_csrf")
// Without CSRF cookie
req = httptest.NewRequest(http.MethodPost, "/", nil)
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
assert.Error(t, h(c))
// Empty/invalid CSRF token
req = httptest.NewRequest(http.MethodPost, "/", nil)
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
req.Header.Set(echo.HeaderXCSRFToken, "")
assert.Error(t, h(c))
// Valid CSRF token
token := randomString(16)
req.Header.Set(echo.HeaderCookie, "_csrf="+token)
req.Header.Set(echo.HeaderXCSRFToken, token)
if assert.NoError(t, h(c)) {
assert.Equal(t, http.StatusOK, rec.Code)
}
}
func TestCSRFTokenFromForm(t *testing.T) {
f := make(url.Values)
f.Set("csrf", "token")
e := echo.New()
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(f.Encode()))
req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm)
c := e.NewContext(req, nil)
token, err := csrfTokenFromForm("csrf")(c)
if assert.NoError(t, err) {
assert.Equal(t, "token", token)
}
_, err = csrfTokenFromForm("invalid")(c)
assert.Error(t, err)
}
func TestCSRFTokenFromQuery(t *testing.T) {
q := make(url.Values)
q.Set("csrf", "token")
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm)
req.URL.RawQuery = q.Encode()
c := e.NewContext(req, nil)
token, err := csrfTokenFromQuery("csrf")(c)
if assert.NoError(t, err) {
assert.Equal(t, "token", token)
}
_, err = csrfTokenFromQuery("invalid")(c)
assert.Error(t, err)
csrfTokenFromQuery("csrf")
}
func TestCSRFSetSameSiteMode(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.SameSiteStrictMode,
})
h := csrf(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
r := h(c)
assert.NoError(t, r)
assert.Regexp(t, "SameSite=Strict", rec.Header()["Set-Cookie"])
}
func TestCSRFWithoutSameSiteMode(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
csrf := CSRFWithConfig(CSRFConfig{})
h := csrf(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})
r := h(c)
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, err := CSRFConfig{
CookieSameSite: http.SameSiteNoneMode,
}.ToMiddleware()
assert.NoError(t, err)
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"])
}