fix(web): harden WebSocket and net host boundaries

- WS handshake: same-origin CheckOrigin instead of allow-all
- route_ws require_auth/需要登录: broadcast/room need a session by default,
  explicit opt-out for public feeds; unauthenticated handshakes get 401
- WS limits: 1 MiB per message, 256 replies per connect; transport errors
  return {ok:false, error} instead of an empty success; empty rooms GC'd
- net host: enforce the 8 MiB response cap while reading (incl. error and
  SSE error paths) so a peer cannot exhaust memory
- url_encode: %20 for space (URL segment semantics, not form +)
- docs: sync 网页 (route_ws 需要登录, connect caps) and CHANGELOG
- tests: gold expectations, live fixture opt-out, hub GC, ws auth gate

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-22 15:14:35 +08:00
1 parent 8e23a5395a
commit 86b183e2d7
15 files changed
+233 -28

No files matched your search

+19 -2
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/gorilla/websocket"
@@ -12,8 +13,19 @@ import (
"github.com/marqdo/marqdo/plugins/web/internal/ws"
)
var wsUpgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
const maxWSMessageBytes = 1 << 20
var wsUpgrader = websocket.Upgrader{CheckOrigin: sameOrigin}
// Browsers send Origin for a cross-site WebSocket handshake. Permit clients
// without Origin, but reject browser origins that differ from this application.
func sameOrigin(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
u, err := url.Parse(origin)
return err == nil && strings.EqualFold(u.Host, r.Host)
}
func (st *state) mountWSRoutes(mux *http.ServeMux) {
@@ -57,11 +69,16 @@ func pathValuesOf(r *http.Request, routePath string) map[string]string {
}
func (st *state) handleWS(w http.ResponseWriter, r *http.Request, path string, spec ws.RouteSpec) {
if spec.RequireAuth && session.UsernameFromCookie(r.Header.Get("Cookie")) == "" {
http.Error(w, "WebSocket authentication required", http.StatusUnauthorized)
return
}
conn, err := wsUpgrader.Upgrade(w, r, nil)
if err != nil {
return
}
defer conn.Close()
conn.SetReadLimit(maxWSMessageBytes)
vals := pathValuesOf(r, path)
switch spec.Mode {
@@ -0,0 +1,55 @@
package httpx
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/ws"
)
func TestHandleWSRejectsUnauthenticatedHandshake(t *testing.T) {
st := &state{}
r := httptest.NewRequest("GET", "http://app.example/live", nil)
w := httptest.NewRecorder()
st.handleWS(w, r, "/live", ws.RouteSpec{Mode: ws.ModeBroadcast, RequireAuth: true})
if w.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated ws handshake code=%d, want 401", w.Code)
}
}
func TestHandleWSAllowsPublicRouteThroughAuthGate(t *testing.T) {
st := &state{}
r := httptest.NewRequest("GET", "http://app.example/live", nil)
w := httptest.NewRecorder()
// Public route: must not 401. Upgrade then fails on the recorder (no
// Hijacker), which is fine — only the auth gate is under test.
st.handleWS(w, r, "/live", ws.RouteSpec{Mode: ws.ModeBroadcast, RequireAuth: false})
if w.Code == http.StatusUnauthorized {
t.Fatalf("public ws route unexpectedly requires authentication")
}
}
func TestSameOriginWebSocketHandshake(t *testing.T) {
cases := []struct {
name string
origin string
want bool
}{
{name: "non-browser client", want: true},
{name: "same origin", origin: "https://app.example", want: true},
{name: "different origin", origin: "https://evil.example", want: false},
{name: "malformed origin", origin: "://bad", want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
r := httptest.NewRequest("GET", "http://app.example/live", nil)
if tc.origin != "" {
r.Header.Set("Origin", tc.origin)
}
if got := sameOrigin(r); got != tc.want {
t.Fatalf("sameOrigin(%q)=%v, want %v", tc.origin, got, tc.want)
}
})
}
}
+13 -1
View File
@@ -9,6 +9,11 @@ import (
"github.com/gorilla/websocket"
)
const (
maxMessageBytes = 1 << 20
maxMessages = 256
)
// Connect dials url, sends one text message, collects text replies until close or timeout.
// Mirrors Rust ws::connect; errors are returned as {ok:false, error}.
func Connect(url, message string, headers map[string]any, timeoutSec uint64) map[string]any {
@@ -29,6 +34,7 @@ func Connect(url, message string, headers map[string]any, timeoutSec uint64) map
return map[string]any{"ok": false, "error": fmt.Sprintf("ws connect: %v", err)}
}
defer conn.Close()
conn.SetReadLimit(maxMessageBytes)
if err := conn.SetWriteDeadline(time.Now().Add(timeout)); err != nil {
return map[string]any{"ok": false, "error": fmt.Sprintf("ws send: %v", err)}
@@ -45,9 +51,15 @@ func Connect(url, message string, headers map[string]any, timeoutSec uint64) map
}
mt, data, err := conn.ReadMessage()
if err != nil {
break
if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
break
}
return map[string]any{"ok": false, "error": fmt.Sprintf("ws receive: %v", err)}
}
if mt == websocket.TextMessage {
if len(messages) == maxMessages {
return map[string]any{"ok": false, "error": "ws receive: too many messages"}
}
messages = append(messages, string(data))
}
if mt == websocket.CloseMessage {
+15
View File
@@ -42,7 +42,22 @@ func unsubscribe(path string, ch chan string) {
}
room.mu.Lock()
delete(room.subs, ch)
empty := len(room.subs) == 0
room.mu.Unlock()
if !empty {
return
}
// A room can be derived from a URL path. Remove empty rooms so a stream of
// one-off room names cannot leave metadata allocated for the process lifetime.
globalHub.mu.Lock()
if globalHub.room[path] == room {
room.mu.Lock()
if len(room.subs) == 0 {
delete(globalHub.room, path)
}
room.mu.Unlock()
}
globalHub.mu.Unlock()
}
// JoinRoom subscribes to a named room (G-WS1). Same backing store as path broadcast.
+32
View File
@@ -35,6 +35,38 @@ func TestBroadcastFanout(t *testing.T) {
unsubscribe(path, ch2)
}
func TestUnsubscribeRemovesEmptyRoom(t *testing.T) {
path := "/t-empty-room-gc"
ch := subscribe(path)
unsubscribe(path, ch)
globalHub.mu.Lock()
_, ok := globalHub.room[path]
globalHub.mu.Unlock()
if ok {
t.Fatalf("empty room %q was not garbage-collected", path)
}
}
func TestResubscribeDuringCleanupKeepsRoom(t *testing.T) {
path := "/t-room-rejoin"
ch := subscribe(path)
ch2 := subscribe(path)
unsubscribe(path, ch)
unsubscribe(path, ch2)
ch3 := subscribe(path)
Publish(path, "still-alive")
if got := readOne(ch3); got != "still-alive" {
t.Fatalf("re-subscribed chan got %q", got)
}
unsubscribe(path, ch3)
globalHub.mu.Lock()
_, ok := globalHub.room[path]
globalHub.mu.Unlock()
if ok {
t.Fatalf("empty room %q was not garbage-collected after rejoin", path)
}
}
func readOne(ch chan string) string {
select {
case s := <-ch:
+19 -4
View File
@@ -9,10 +9,11 @@ import (
// RouteSpec is one ws_routes entry (mode + optional room_key / on_message / presence).
type RouteSpec struct {
Mode Mode
RoomKey string
OnMessage string
Presence bool
Mode Mode
RoomKey string
OnMessage string
Presence bool
RequireAuth bool
}
// RouteWS registers path → {mode, room_key?, on_message?, presence?} on app.ws_routes.
@@ -28,6 +29,12 @@ func RouteWS(appBag map[string]any, path string, args map[string]any) (map[strin
}
onMsg := OnMessageFromArgs(args)
presence := PresenceFromArgs(args)
// Stateful fan-out routes are private by default. Echo and drain remain
// useful for public health checks and demos; authors can opt out explicitly.
requireAuth := mode == ModeBroadcast || mode == ModeRoom
if v, ok := first(args, "require_auth", "需要登录"); ok && v != nil {
requireAuth = boolish(v)
}
out := clone(appBag)
wsRoutes := map[string]any{}
if r, ok := out["ws_routes"].(map[string]any); ok {
@@ -43,6 +50,9 @@ func RouteWS(appBag map[string]any, path string, args map[string]any) (map[strin
if presence {
spec["presence"] = true
}
if requireAuth {
spec["require_auth"] = true
}
wsRoutes[path] = spec
out["ws_routes"] = wsRoutes
return out, nil
@@ -165,6 +175,11 @@ func parseRouteSpec(spec any) RouteSpec {
} else if p, ok := t["在场"]; ok {
out.Presence = boolish(p)
}
if a, ok := t["require_auth"]; ok {
out.RequireAuth = boolish(a)
} else if a, ok := t["需要登录"]; ok {
out.RequireAuth = boolish(a)
}
case string:
out.Mode = ParseMode(t)
default:
+21
View File
@@ -26,6 +26,27 @@ func TestRouteWSBroadcastMode(t *testing.T) {
if room["mode"] != "broadcast" {
t.Fatalf("bag mode=%v", room["mode"])
}
if room["require_auth"] != true {
t.Fatalf("broadcast must require authentication by default: %v", room)
}
}
func TestRouteWSPublicBroadcastOptOut(t *testing.T) {
a := app.New(nil)
out, err := ws.RouteWS(a, "/live", map[string]any{
"mode": "broadcast",
"require_auth": false,
})
if err != nil {
t.Fatal(err)
}
spec, err := ws.RouteSpecOf(out, "/live")
if err != nil {
t.Fatal(err)
}
if spec.RequireAuth {
t.Fatalf("explicit public route unexpectedly requires authentication: %+v", spec)
}
}
func TestRouteWSEchoDefault(t *testing.T) {
+1 -1
View File
@@ -258,7 +258,7 @@ static int register_core(void) {
if (host_register((char *)"web_app_sitemap", (char *)"app,path,base,table,loc,limit,items", web_app_sitemap) != 0) return 1;
if (host_register((char *)"web_app_robots", (char *)"app,body,sitemap", web_app_robots) != 0) return 1;
if (host_register((char *)"web_sitemap_build", (char *)"base,items", web_sitemap_build) != 0) return 1;
if (host_register((char *)"web_app_route_ws", (char *)"app,path,echo,mode,room_key,on_message,presence", web_app_route_ws) != 0) return 1;
if (host_register((char *)"web_app_route_ws", (char *)"app,path,echo,mode,room_key,on_message,presence,require_auth", web_app_route_ws) != 0) return 1;
if (host_register((char *)"web_ws_connect", (char *)"url,message,headers,timeout_sec", web_ws_connect) != 0) return 1;
if (host_register((char *)"web_cache_new", (char *)"url", web_cache_new) != 0) return 1;
if (host_register((char *)"web_cache_get", (char *)"url,key", web_cache_get) != 0) return 1;