Files
LocalAI/core/http/auth/csrf.go
T
Richard Palethorpe 66e3a06ce6 fix(auth): require validated header credentials for CSRF exemption (#12185)
Track successful header authentication before allowing cross-site requests
to bypass CSRF checks. Arbitrary headers on unauthenticated servers and
cookie-authenticated requests no longer grant an exemption.

Share the production CSRF middleware with multipart tests, add regression
coverage for credential sources, and document the exemption behavior.

Assisted-by: Codex:gpt-6 golangci-lint

Signed-off-by: Richard Palethorpe <io@richiejp.com>
2026-09-22 04:35:09 +01:00

26 lines
816 B
Go

// SPDX-License-Identifier: MIT
package auth
import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
// CSRFMiddleware must run after Middleware so only validated header credentials
// grant an exemption. Cookie authentication must still pass the browser checks.
func CSRFMiddleware() echo.MiddlewareFunc {
return middleware.CSRFWithConfig(middleware.CSRFConfig{
Skipper: func(c echo.Context) bool {
if authenticated, _ := c.Get(contextKeyHeaderAuthenticated).(bool); authenticated {
return true
}
// Preserve support for clients that do not send fetch metadata.
return c.Request().Header.Get("Sec-Fetch-Site") == ""
},
AllowSecFetchSiteFunc: func(c echo.Context) (bool, error) {
return c.Request().Header.Get("Sec-Fetch-Site") == "same-site", nil
},
})
}