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

+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) {