Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ErrorHandler and ErrorHandlerWithContext in CSRF middleware #2257

Merged
merged 5 commits into from
Sep 1, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions middleware/csrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,17 @@ type (
// Indicates SameSite mode of the CSRF cookie.
// Optional. Default value SameSiteDefaultMode.
CookieSameSite http.SameSite `yaml:"cookie_same_site"`

// ErrorHandler defines a function which is executed for returning custom errors.
ErrorHandler CSRFErrorHandler
aldas marked this conversation as resolved.
Show resolved Hide resolved

// ErrorHandlerWithContext is almost identical to ErrorHandler, but it's passed the current context.
ErrorHandlerWithContext CSRFErrorHandlerWithContext
}

CSRFErrorHandler func(err error) error

CSRFErrorHandlerWithContext func(err error, c echo.Context) error
)

// ErrCSRFInvalid is returned when CSRF check fails
Expand Down Expand Up @@ -154,8 +164,9 @@ func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc {
lastTokenErr = ErrCSRFInvalid
}
}
var finalErr error
if lastTokenErr != nil {
return lastTokenErr
finalErr = lastTokenErr
} else if lastExtractorErr != nil {
// ugly part to preserve backwards compatible errors. someone could rely on them
if lastExtractorErr == errQueryExtractorValueMissing {
Expand All @@ -167,7 +178,17 @@ func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc {
} else {
lastExtractorErr = echo.NewHTTPError(http.StatusBadRequest, lastExtractorErr.Error())
}
return lastExtractorErr
finalErr = lastExtractorErr
}

if finalErr != nil {
if config.ErrorHandler != nil {
return config.ErrorHandler(finalErr)
}
if config.ErrorHandlerWithContext != nil {
return config.ErrorHandlerWithContext(finalErr, c)
}
return finalErr
}
}

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

import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
Expand Down Expand Up @@ -358,3 +359,53 @@ func TestCSRFConfig_skipper(t *testing.T) {
})
}
}

func TestCSRFErrorHandling(t *testing.T) {
testCases := []struct {
name string
cfg CSRFConfig
expectedErr *echo.HTTPError
}{
{
name: "ok, ErrorHandler is executed",
cfg: CSRFConfig{
ErrorHandler: func(err error) error {
return echo.NewHTTPError(http.StatusTeapot, "error_handler_executed")
},
},
expectedErr: echo.NewHTTPError(http.StatusTeapot, "error_handler_executed"),
},
{
name: "ok, ErrorHandlerWithContext is executed",
cfg: CSRFConfig{
ErrorHandlerWithContext: func(err error, c echo.Context) error {
return echo.NewHTTPError(http.StatusTeapot, "error_handler_with_context_executed")
},
},
expectedErr: echo.NewHTTPError(http.StatusTeapot, "error_handler_with_context_executed"),
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
e := echo.New()
e.POST("/", func(c echo.Context) error {
return c.String(http.StatusNotImplemented, "should not end up here")
})

e.Use(CSRFWithConfig(tc.cfg))

req := httptest.NewRequest(http.MethodPost, "/", nil)
res := httptest.NewRecorder()
e.ServeHTTP(res, req)

var response struct {
Message string `json:"message"`
}

assert.NoError(t, json.Unmarshal(res.Body.Bytes(), &response))
assert.Equal(t, tc.expectedErr.Code, res.Code)
assert.Equal(t, tc.expectedErr.Message, response.Message)
})
}
}