security: remediate all P0-P2 audit findings (12 tasks)

P0 fixes:
- WebSocket origin checking (reject untrusted origins)
- WS session token moved from URL query param to first message frame
- WebAuthn login cookie now uses Secure flag via shared SetSessionCookie
- PostgreSQL sslmode configurable via POSTGRES_SSLMODE env (default: require)
- Fixed DatabaseDSN to use real password instead of masked placeholder

P1 fixes:
- Per-IP rate limiting middleware (auth: 5 req/s, invites: 2 req/s)
- Security headers on all responses (CSP, X-Frame-Options, nosniff, etc.)
- WS broadcasts scoped to server members (prevents cross-server data leak)
- Webhook tokens stored as SHA-256 hashes (not plaintext)

P2 fixes:
- CSRF protection via Origin header validation on state-changing requests
- MANAGE_CHANNELS permission enforced on channel update/delete
- Upload validation: 25MB limit, extension allowlist, server-side MIME check
- File serve: path traversal protection + Content-Disposition: attachment

Files: 23 changed, +499/-100. Builds clean (go build, go vet, npm build).
Zero CVEs (govulncheck, npm audit).
This commit is contained in:
2026-06-29 09:30:50 -04:00
parent 5373105368
commit 130187c7be
23 changed files with 504 additions and 105 deletions
+68 -19
View File
@@ -21,7 +21,28 @@ const (
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
CheckOrigin: func(r *http.Request) bool { return true }, // default: allow all (overridden by SetAllowedOrigins)
}
// SetAllowedOrigins replaces the default upgrader with one that validates
// the Origin header against a trusted set. Call once at startup.
func SetAllowedOrigins(origins []string) {
originSet := make(map[string]struct{}, len(origins))
for _, o := range origins {
originSet[o] = struct{}{}
}
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return false
}
_, ok := originSet[origin]
return ok
},
}
}
// Client is a middleman between the websocket connection and the hub.
@@ -118,31 +139,59 @@ func (c *Client) writePump() {
}
}
// ServeWS handles websocket requests from the peer. It authenticates the
// client via a session token passed as the "token" query parameter.
// authMessage is the first frame the client must send after connecting.
type authMessage struct {
Token string `json:"token"`
}
// ServeWS handles websocket requests from the peer. It upgrades the
// connection first, then waits for an auth message frame containing the
// session token. This avoids leaking the token in the URL (which would
// appear in server logs, browser history, and Referer headers).
func ServeWS(db *sql.DB, hub *Hub, logger *slog.Logger, w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token")
if token == "" {
http.Error(w, `{"error":"missing token"}`, http.StatusUnauthorized)
return
}
var userID string
err := db.QueryRowContext(context.Background(),
`SELECT user_id FROM sessions WHERE token = $1 AND expires_at > NOW()`,
token,
).Scan(&userID)
if err != nil {
http.Error(w, `{"error":"invalid or expired session"}`, http.StatusUnauthorized)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Error("websocket upgrade failed", "error", err)
return
}
// Short deadline for the auth frame; we don't want unauthenticated
// connections hanging around consuming resources.
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
_, raw, err := conn.ReadMessage()
if err != nil {
logger.Warn("ws auth: failed to read auth message", "error", err)
conn.WriteMessage(websocket.TextMessage, []byte(`{"error":"auth timeout"}`))
conn.Close()
return
}
var auth authMessage
if err := json.Unmarshal(raw, &auth); err != nil || auth.Token == "" {
logger.Warn("ws auth: invalid auth message")
conn.WriteMessage(websocket.TextMessage, []byte(`{"error":"missing token"}`))
conn.Close()
return
}
var userID string
err = db.QueryRowContext(context.Background(),
`SELECT user_id FROM sessions WHERE token = $1 AND expires_at > NOW()`,
auth.Token,
).Scan(&userID)
if err != nil {
logger.Warn("ws auth: invalid session", "error", err)
conn.WriteMessage(websocket.TextMessage, []byte(`{"error":"invalid session"}`))
conn.Close()
return
}
// Auth succeeded. Clear the auth deadline (readPump sets its own).
conn.SetReadDeadline(time.Time{})
// Send ready signal so the client knows auth passed.
conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"ready"}`))
client := &Client{
Hub: hub,
Conn: conn,