Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Harden CSRF follow-ups from review (GHSA-xjr8-w967-4xjq)

Matt Robertsb6c8b17ea705
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index 10dc455df..0b34621a0 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -204,7 +204,7 @@ func routes(r *web.Engine) *web.Engine {
ui.Post("/_api/admin/webhook", handlers.CreateWebhook())
ui.Put("/_api/admin/webhook/:id", handlers.UpdateWebhook())
ui.Delete("/_api/admin/webhook/:id", handlers.DeleteWebhook())
- ui.Get("/_api/admin/webhook/test/:id", handlers.TestWebhook())
+ ui.Post("/_api/admin/webhook/test/:id", handlers.TestWebhook())
ui.Post("/_api/admin/webhook/preview", handlers.PreviewWebhook())
ui.Get("/_api/admin/webhook/props/:type", handlers.GetWebhookProps())
ui.Post("/_api/admin/settings/general", handlers.UpdateSettings())
diff --git a/app/middlewares/security.go b/app/middlewares/security.go
index e232e60a4..e30637adf 100644
--- a/app/middlewares/security.go
+++ b/app/middlewares/security.go
@@ -2,7 +2,6 @@ package middlewares
import (
"fmt"
- "mime"
"net/http"
"strings"
@@ -57,7 +56,9 @@ func CSRF() web.MiddlewareFunc {
if strings.EqualFold(c.Request.GetHeader("Sec-Fetch-Site"), "cross-site") {
return c.Forbidden()
}
- if !hasJSONContentType(c) && !hasBearerAuthorization(c) {
+ // 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 {
return c.Forbidden()
}
}
@@ -74,27 +75,3 @@ func isWriteMethod(method string) bool {
return true
}
}
-
-// hasJSONContentType returns true only if the Content-Type media type is exactly
-// application/json. Substring matching is unsafe, as "text/plain; x=application/json"
-// is a CORS-safelisted Content-Type.
-func hasJSONContentType(c *web.Context) bool {
- contentType := c.Request.GetHeader("Content-Type")
- if contentType == "" {
- return false
- }
- mediaType, _, err := mime.ParseMediaType(contentType)
- if err != nil {
- return false
- }
- return mediaType == web.JSONContentType
-}
-
-// hasBearerAuthorization returns true if the request has an Authorization header
-// using the Bearer scheme. Browsers never attach Bearer credentials automatically
-// (unlike cached Basic credentials), and cross-origin pages cannot set this header
-// without a CORS preflight.
-func hasBearerAuthorization(c *web.Context) bool {
- auth := strings.TrimSpace(c.Request.GetHeader("Authorization"))
- return len(auth) > len("Bearer ") && strings.EqualFold(auth[:len("Bearer ")], "Bearer ")
-}
diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.go
index 5d8af536c..6d07e7334 100644
--- a/app/middlewares/security_test.go
+++ b/app/middlewares/security_test.go
@@ -130,6 +130,9 @@ func TestCSRF(t *testing.T) {
{"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 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},
@@ -138,10 +141,12 @@ func TestCSRF(t *testing.T) {
}
for _, tc := range testCases {
- status := executeCSRF(tc.method, tc.headers)
- if status != tc.expected {
- t.Errorf("%s: expected status %d, got %d", tc.name, tc.expected, status)
- }
+ t.Run(tc.name, func(t *testing.T) {
+ RegisterT(t)
+
+ status := executeCSRF(tc.method, tc.headers)
+ Expect(status).Equals(tc.expected)
+ })
}
}
diff --git a/app/middlewares/user.go b/app/middlewares/user.go
index 1c2db3375..721e2c220 100644
--- a/app/middlewares/user.go
+++ b/app/middlewares/user.go
@@ -87,10 +87,7 @@ func User() web.MiddlewareFunc {
return c.Redirect("/signin")
}
} else if c.Request.IsAPI() {
- authHeader := c.Request.GetHeader("Authorization")
- parts := strings.Split(authHeader, "Bearer")
- if len(parts) == 2 {
- apiKey := strings.TrimSpace(parts[1])
+ if apiKey, ok := web.ParseBearerToken(c.Request.GetHeader("Authorization")); ok {
getUserByAPIKey := &query.GetUserByAPIKey{APIKey: apiKey}
err = bus.Dispatch(c, getUserByAPIKey)
if err != nil {
diff --git a/app/pkg/web/binder.go b/app/pkg/web/binder.go
index 281efbe04..f5eb6addc 100644
--- a/app/pkg/web/binder.go
+++ b/app/pkg/web/binder.go
@@ -32,8 +32,7 @@ func methodHasBody(method string) bool {
//Bind request data to object i
func (b *DefaultBinder) Bind(target any, c *Context) error {
if methodHasBody(c.Request.Method) && c.Request.ContentLength > 0 {
- contentType := strings.Split(c.Request.GetHeader("Content-Type"), ";")
- if len(contentType) == 0 || contentType[0] != JSONContentType {
+ if !IsJSONContentType(c.Request.GetHeader("Content-Type")) {
return ErrContentTypeNotAllowed
}
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index 172d2e9f5..a172c6826 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -205,7 +205,11 @@ func (c *Context) IsAuthenticated() bool {
return c.Value(app.UserCtxKey) != nil
}
-// IsAjax returns true if request is AJAX
+// IsAjax returns true if request is AJAX, i.e. the client asked for (Accept) or
+// sent (Content-Type) JSON. It is only meant to pick the response format (JSON vs
+// HTML page) and MUST NOT be used as a security or CSRF check: it matches on a
+// substring of CORS-safelisted headers that any cross-origin page can send.
+// See middlewares.CSRF() and GHSA-xjr8-w967-4xjq.
func (c *Context) IsAjax() bool {
accept := c.Request.GetHeader("Accept")
contentType := c.Request.GetHeader("Content-Type")
diff --git a/app/pkg/web/headers.go b/app/pkg/web/headers.go
new file mode 100644
index 000000000..c2a4ba40d
--- /dev/null
+++ b/app/pkg/web/headers.go
@@ -0,0 +1,37 @@
+package web
+
+import (
+ "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
+// "text/plain; x=application/json" are CORS-safelisted and can be sent cross-origin.
+func IsJSONContentType(contentType string) bool {
+ if contentType == "" {
+ return false
+ }
+ mediaType, _, err := mime.ParseMediaType(contentType)
+ if err != nil {
+ 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.
+func ParseBearerToken(authorization string) (string, bool) {
+ authorization = strings.TrimSpace(authorization)
+ scheme, token, found := strings.Cut(authorization, " ")
+ if !found || !strings.EqualFold(scheme, "Bearer") {
+ return "", false
+ }
+ token = strings.TrimSpace(token)
+ if token == "" {
+ return "", false
+ }
+ return token, true
+}
diff --git a/app/pkg/web/headers_test.go b/app/pkg/web/headers_test.go
new file mode 100644
index 000000000..5c847a409
--- /dev/null
+++ b/app/pkg/web/headers_test.go
@@ -0,0 +1,63 @@
+package web_test
+
+import (
+ "testing"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+func TestIsJSONContentType(t *testing.T) {
+ testCases := []struct {
+ contentType string
+ expected bool
+ }{
+ {"application/json", true},
+ {"application/json; charset=utf-8", true},
+ {"application/json;charset=UTF-8", true},
+ {"Application/JSON", true},
+ {"", false},
+ {"text/plain", false},
+ {"text/plain; x=application/json", false},
+ {"application/x-www-form-urlencoded", false},
+ {"multipart/form-data; boundary=x", false},
+ {"application/jsonx", false},
+ {"application/json;;;=", false},
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.contentType, func(t *testing.T) {
+ RegisterT(t)
+ Expect(web.IsJSONContentType(tc.contentType)).Equals(tc.expected)
+ })
+ }
+}
+
+func TestParseBearerToken(t *testing.T) {
+ testCases := []struct {
+ header string
+ expectedToken string
+ expectedOk bool
+ }{
+ {"Bearer MY-KEY", "MY-KEY", true},
+ {"Bearer MY-KEY ", "MY-KEY", true},
+ {"bearer MY-KEY", "MY-KEY", true},
+ {"BEARER MY-KEY", "MY-KEY", true},
+ {"", "", false},
+ {"Bearer", "", false},
+ {"Bearer ", "", false},
+ {"BearerMY-KEY", "", false},
+ {"Basic dXNlcjpwYXNz", "", false},
+ {"Basic Bearer MY-KEY", "", false},
+ {"Token Bearer", "", false},
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.header, func(t *testing.T) {
+ RegisterT(t)
+ token, ok := web.ParseBearerToken(tc.header)
+ Expect(ok).Equals(tc.expectedOk)
+ Expect(token).Equals(tc.expectedToken)
+ })
+ }
+}
diff --git a/public/services/actions/webhook.ts b/public/services/actions/webhook.ts
index 930075006..cf84d80d1 100644
--- a/public/services/actions/webhook.ts
+++ b/public/services/actions/webhook.ts
@@ -14,7 +14,7 @@ export const deleteWebhook = async (id: number): Promise<Result> => {
}
export const testWebhook = async (id: number): Promise<Result<WebhookTriggerResult>> => {
- return await http.get(`/_api/admin/webhook/test/${id}`)
+ return await http.post(`/_api/admin/webhook/test/${id}`)
}
export const previewWebhook = async (type: WebhookType, url: string, content: string): Promise<Result<WebhookPreviewResult>> => {