Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Restore lenient API key parsing and scope CSRF Bearer exemption (GHSA-xjr8-w967-4xjq)

Matt Robertscecef40c6e18
diff --git a/app/handlers/webhook_test.go b/app/handlers/webhook_test.go
new file mode 100644
index 000000000..8e8c3b058
--- /dev/null
+++ b/app/handlers/webhook_test.go
@@ -0,0 +1,44 @@
+package handlers_test
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "github.com/getfider/fider/app/handlers"
+ "github.com/getfider/fider/app/middlewares"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/mock"
+)
+
+// The test webhook route is a POST (it fires an outbound request), so it must work
+// when called the way the frontend's http.post does it: POST, JSON Content-Type,
+// no body, through the CSRF middleware.
+func TestTestWebhookHandler_POST(t *testing.T) {
+ RegisterT(t)
+
+ var triggeredID int
+ bus.AddHandler(func(ctx context.Context, c *cmd.TestWebhook) error {
+ triggeredID = c.ID
+ c.Result = &dto.WebhookTriggerResult{Success: true, StatusCode: http.StatusOK}
+ return nil
+ })
+
+ server := mock.NewServer()
+ server.Use(middlewares.CSRF())
+
+ code, query := server.
+ WithURL("http://demo.test.fider.io/_api/admin/webhook/test/42").
+ OnTenant(mock.DemoTenant).
+ AsUser(mock.JonSnow).
+ AddParam("id", 42).
+ ExecutePostAsJSON(handlers.TestWebhook(), "")
+
+ Expect(code).Equals(http.StatusOK)
+ Expect(triggeredID).Equals(42)
+ Expect(string(query.Raw("success"))).Equals("true")
+ Expect(query.Int32("status_code")).Equals(http.StatusOK)
+}
diff --git a/app/middlewares/security.go b/app/middlewares/security.go
index e30637adf..c85caeae7 100644
--- a/app/middlewares/security.go
+++ b/app/middlewares/security.go
@@ -40,7 +40,8 @@ func Secure() web.MiddlewareFunc {
// without first passing a CORS preflight (which Fider never grants):
//
// - a Content-Type whose media type is exactly "application/json"; or
-// - an "Authorization: Bearer ..." header (API key clients).
+// - an "Authorization: Bearer ..." header on an /api/ path, i.e. exactly the
+// requests that the User middleware authenticates with an API key.
//
// The Accept header is deliberately NOT considered: it is CORS-safelisted, so a
// cross-origin page can send "Accept: application/json" in a no-cors request.
@@ -56,9 +57,7 @@ func CSRF() web.MiddlewareFunc {
if strings.EqualFold(c.Request.GetHeader("Sec-Fetch-Site"), "cross-site") {
return c.Forbidden()
}
- // Only exempt exactly what the API key authentication path (User middleware) accepts
- _, hasBearerToken := web.ParseBearerToken(c.Request.GetHeader("Authorization"))
- if !web.IsJSONContentType(c.Request.GetHeader("Content-Type")) && !hasBearerToken {
+ if !web.IsJSONContentType(c.Request.GetHeader("Content-Type")) && !isAPIKeyRequest(c) {
return c.Forbidden()
}
}
@@ -75,3 +74,14 @@ func isWriteMethod(method string) bool {
return true
}
}
+
+// isAPIKeyRequest returns true if the request would be authenticated with an API key
+// by the User middleware: an /api/ path with a Bearer token. It is scoped this way so
+// the CSRF exemption matches exactly what the API key authentication path accepts.
+func isAPIKeyRequest(c *web.Context) bool {
+ if !c.Request.IsAPI() {
+ return false
+ }
+ _, ok := web.ParseBearerToken(c.Request.GetHeader("Authorization"))
+ return ok
+}
diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.go
index 6d07e7334..c7d8ca54e 100644
--- a/app/middlewares/security_test.go
+++ b/app/middlewares/security_test.go
@@ -79,8 +79,8 @@ func TestSecureWithCDN_SingleHost(t *testing.T) {
Expect(response.Header().Get("Referrer-Policy")).Equals("no-referrer-when-downgrade")
}
-func executeCSRF(method string, headers map[string]string) int {
- server := mock.NewServer()
+func executeCSRF(method, url string, headers map[string]string) int {
+ server := mock.NewServer().WithURL(url)
server.Use(func(next web.HandlerFunc) web.HandlerFunc {
return func(c *web.Context) error {
c.Request.Method = method
@@ -125,14 +125,18 @@ func TestCSRF(t *testing.T) {
{"POST with form content type", "POST", map[string]string{"Content-Type": "application/x-www-form-urlencoded"}, http.StatusForbidden},
{"POST with multipart content type", "POST", map[string]string{"Content-Type": "multipart/form-data; boundary=x"}, http.StatusForbidden},
{"POST with json-like content type", "POST", map[string]string{"Content-Type": "application/jsonx"}, http.StatusForbidden},
- {"POST with invalid content type", "POST", map[string]string{"Content-Type": "application/json;;;="}, http.StatusForbidden},
+ {"POST with JSON content type and malformed parameters", "POST", map[string]string{"Content-Type": "application/json;;;="}, http.StatusOK},
+ {"POST with text/plain and malformed parameters", "POST", map[string]string{"Content-Type": "text/plain; charset"}, http.StatusForbidden},
{"POST with Bearer Authorization", "POST", map[string]string{"Authorization": "Bearer some-api-key"}, http.StatusOK},
{"DELETE with Bearer Authorization", "DELETE", map[string]string{"Authorization": "Bearer some-api-key"}, http.StatusOK},
{"POST with Basic Authorization", "POST", map[string]string{"Authorization": "Basic dXNlcjpwYXNz"}, http.StatusForbidden},
{"POST with empty Bearer Authorization", "POST", map[string]string{"Authorization": "Bearer "}, http.StatusForbidden},
{"POST with lower-case bearer Authorization", "POST", map[string]string{"Authorization": "bearer some-api-key"}, http.StatusOK},
{"POST with Basic Bearer Authorization", "POST", map[string]string{"Authorization": "Basic Bearer some-api-key"}, http.StatusForbidden},
- {"POST with Bearer without space", "POST", map[string]string{"Authorization": "Bearersome-api-key"}, http.StatusForbidden},
+ {"POST with Bearer without space", "POST", map[string]string{"Authorization": "Bearersome-api-key"}, http.StatusOK},
+ {"POST with Bearer tab separator", "POST", map[string]string{"Authorization": "Bearer\tsome-api-key"}, http.StatusOK},
+ {"POST with Bearer and form content type", "POST", map[string]string{"Authorization": "Bearer some-api-key", "Content-Type": "application/x-www-form-urlencoded"}, http.StatusOK},
+ {"POST with JSON content type and invalid parameter", "POST", map[string]string{"Content-Type": "application/json; charset"}, http.StatusOK},
{"POST cross-site with JSON content type", "POST", map[string]string{"Content-Type": "application/json", "Sec-Fetch-Site": "cross-site"}, http.StatusForbidden},
{"POST cross-site with Bearer Authorization", "POST", map[string]string{"Authorization": "Bearer some-api-key", "Sec-Fetch-Site": "cross-site"}, http.StatusForbidden},
{"POST same-site with JSON content type", "POST", map[string]string{"Content-Type": "application/json", "Sec-Fetch-Site": "same-site"}, http.StatusOK},
@@ -144,7 +148,34 @@ func TestCSRF(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
RegisterT(t)
- status := executeCSRF(tc.method, tc.headers)
+ status := executeCSRF(tc.method, "http://demo.test.fider.io/api/v1/posts/1/votes", tc.headers)
+ Expect(status).Equals(tc.expected)
+ })
+ }
+}
+
+// The Bearer exemption only applies to /api/ paths, where the User middleware
+// authenticates with an API key. Elsewhere (e.g. /_api/) the cookie is used, so a
+// Bearer header must not bypass the CSRF check.
+func TestCSRF_BearerExemptionOnlyForAPIPaths(t *testing.T) {
+ testCases := []struct {
+ name string
+ url string
+ headers map[string]string
+ expected int
+ }{
+ {"/_api with only Bearer", "http://demo.test.fider.io/_api/user/settings", map[string]string{"Authorization": "Bearer x"}, http.StatusForbidden},
+ {"/_api with Bearer and text/plain", "http://demo.test.fider.io/_api/user/settings", map[string]string{"Authorization": "Bearer x", "Content-Type": "text/plain"}, http.StatusForbidden},
+ {"/_api with JSON content type", "http://demo.test.fider.io/_api/user/settings", map[string]string{"Content-Type": "application/json"}, http.StatusOK},
+ {"root path with only Bearer", "http://demo.test.fider.io/posts/1", map[string]string{"Authorization": "Bearer x"}, http.StatusForbidden},
+ {"/api with only Bearer", "http://demo.test.fider.io/api/v1/posts", map[string]string{"Authorization": "Bearer x"}, http.StatusOK},
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ RegisterT(t)
+
+ status := executeCSRF("POST", tc.url, tc.headers)
Expect(status).Equals(tc.expected)
})
}
diff --git a/app/middlewares/user_test.go b/app/middlewares/user_test.go
index af6805f87..5db5a5622 100644
--- a/app/middlewares/user_test.go
+++ b/app/middlewares/user_test.go
@@ -350,6 +350,59 @@ func TestUser_ValidAPIKey(t *testing.T) {
Expect(response.Body.String()).Equals("Jon Snow")
}
+func TestUser_ValidAPIKey_LenientBearerParsing(t *testing.T) {
+ for _, header := range []string{"bearer 1234567890", "BEARER 1234567890", "Bearer\t1234567890", "Bearer1234567890", "Bearer 1234567890 \r\n"} {
+ t.Run(header, func(t *testing.T) {
+ RegisterT(t)
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
+ if q.APIKey == "1234567890" {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
+
+ server.Use(middlewares.User())
+ status, response := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://example.com/api/v1").
+ AddHeader("Authorization", header).
+ Execute(func(c *web.Context) error {
+ return c.String(http.StatusOK, c.User().Name)
+ })
+
+ Expect(status).Equals(http.StatusOK)
+ Expect(response.Body.String()).Equals("Jon Snow")
+ })
+ }
+}
+
+func TestUser_OtherAuthorizationSchemes_AreIgnored(t *testing.T) {
+ RegisterT(t)
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
+ q.Result = mock.JonSnow
+ return nil
+ })
+
+ server := mock.NewServer()
+
+ server.Use(middlewares.User())
+ status, _ := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://example.com/api/v1").
+ AddHeader("Authorization", "Basic Bearer 1234567890").
+ Execute(func(c *web.Context) error {
+ Expect(c.User()).IsNil()
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).Equals(http.StatusOK)
+}
+
func TestUser_InvalidAPIKey(t *testing.T) {
RegisterT(t)
diff --git a/app/pkg/web/headers.go b/app/pkg/web/headers.go
index c2a4ba40d..865b90281 100644
--- a/app/pkg/web/headers.go
+++ b/app/pkg/web/headers.go
@@ -1,35 +1,45 @@
package web
import (
+ "errors"
"mime"
"strings"
)
// IsJSONContentType returns true if the media type of given Content-Type header
-// value is exactly application/json (case-insensitive, parameters such as charset
-// are allowed). Substring matching must not be used for this, as values such as
+// value is application/json (case-insensitive, parameters such as charset are
+// allowed). Substring matching must not be used for this, as values such as
// "text/plain; x=application/json" are CORS-safelisted and can be sent cross-origin.
+//
+// Malformed or duplicate parameters (e.g. "application/json; charset") are
+// tolerated for backwards compatibility, as long as the media type itself is
+// application/json. This is still CSRF-safe: a CORS simple request can never
+// have an application/json essence.
func IsJSONContentType(contentType string) bool {
if contentType == "" {
return false
}
mediaType, _, err := mime.ParseMediaType(contentType)
- if err != nil {
+ if err != nil && !errors.Is(err, mime.ErrInvalidMediaParameter) {
return false
}
return mediaType == JSONContentType
}
// ParseBearerToken extracts the token from an Authorization header value that uses
-// the Bearer scheme (e.g. "Bearer <token>"). The scheme is matched case-insensitively.
-// It returns false if the header does not use the Bearer scheme or the token is empty.
+// the Bearer scheme. The header must start with "Bearer" (case-insensitive); the
+// remainder, trimmed of any whitespace, is the token and must not be empty.
+//
+// This is deliberately lenient (e.g. "Bearer\t<key>" and "Bearer<key>" are
+// accepted) to stay compatible with how API keys were historically parsed.
+// Other schemes, including "Basic Bearer <key>", are rejected.
func ParseBearerToken(authorization string) (string, bool) {
+ const scheme = "Bearer"
authorization = strings.TrimSpace(authorization)
- scheme, token, found := strings.Cut(authorization, " ")
- if !found || !strings.EqualFold(scheme, "Bearer") {
+ if len(authorization) < len(scheme) || !strings.EqualFold(authorization[:len(scheme)], scheme) {
return "", false
}
- token = strings.TrimSpace(token)
+ token := strings.TrimSpace(authorization[len(scheme):])
if token == "" {
return "", false
}
diff --git a/app/pkg/web/headers_test.go b/app/pkg/web/headers_test.go
index 5c847a409..ef55595e7 100644
--- a/app/pkg/web/headers_test.go
+++ b/app/pkg/web/headers_test.go
@@ -22,7 +22,15 @@ func TestIsJSONContentType(t *testing.T) {
{"application/x-www-form-urlencoded", false},
{"multipart/form-data; boundary=x", false},
{"application/jsonx", false},
- {"application/json;;;=", false},
+ {"application/json;", true},
+ {"application/json; charset", true},
+ {"application/json; charset=utf-8; charset=utf-8", true},
+ {"application/json;;;=", true},
+ {"text/plain; charset", false},
+ {"text/plain; charset=utf-8; charset=utf-8", false},
+ {"text/plain;;;=", false},
+ {"application/json/x", false},
+ {"/json", false},
}
for _, tc := range testCases {
@@ -41,12 +49,17 @@ func TestParseBearerToken(t *testing.T) {
}{
{"Bearer MY-KEY", "MY-KEY", true},
{"Bearer MY-KEY ", "MY-KEY", true},
+ {"Bearer\tMY-KEY", "MY-KEY", true},
+ {"BearerMY-KEY", "MY-KEY", true},
{"bearer MY-KEY", "MY-KEY", true},
{"BEARER MY-KEY", "MY-KEY", true},
+ {"Bearer MY-KEY\r\n", "MY-KEY", true},
+ {"Bearer MY-KEY \t ", "MY-KEY", true},
{"", "", false},
+ {"Bear", "", false},
{"Bearer", "", false},
{"Bearer ", "", false},
- {"BearerMY-KEY", "", false},
+ {"Bearer \t\r\n", "", false},
{"Basic dXNlcjpwYXNz", "", false},
{"Basic Bearer MY-KEY", "", false},
{"Token Bearer", "", false},