Files
OwnCord/Server/api/livekit_proxy_test.go
T
J3vbandClaude Opus 5 17b17eb1b3 fix(security): close all 13 findings from the 2026-07-28 server scan, plus dependabot rollup (#1264)
* fix(admin): reject banned users in admin auth (F1)

adminAuthMiddleware accepted a Bearer token on session validity plus the
ADMINISTRATOR bit alone and never consulted ban state, so a ban never
revoked admin-panel access. Adds the auth.IsEffectivelyBanned guard that
api.AuthMiddleware already uses, at both admin credential-resolution points.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ws): gate the voice-channel text subscription on READ_MESSAGES (F2)

registerNow subscribed any client with voice state to that channel's
text-message topic regardless of READ_MESSAGES. The handshake's
already-computed readable-channel set is now passed into registerNow and the
subscription only happens when the voice channel is in it, preserving
authorized reconnect delivery.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(service): require READ_MESSAGES to delete messages (F4)

The non-DM delete gate checked MANAGE_MESSAGES without READ_MESSAGES, so a
role locked out of a private channel could still delete every message in it.
Requires ReadMessages alongside ManageMessages (and alongside SendMessages on
the author path) and derives the mod flag from that same gate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(service): require READ_MESSAGES alongside MANAGE_MESSAGES in SetMessagePinned (F8)

Pin/unpin checked only MANAGE_MESSAGES, so a role denied READ on a private
channel could still pin and unpin its messages.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(service): enforce the DM block at every DM interaction sink (F5)

The DM block was only checked on send, leaving edit, reactions, pins and
typing as bypasses. One shared requireDMNotBlocked is now called from all of
them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ws): re-check CONNECT_VOICE when minting a refreshed LiveKit token (F6)

voice_token_refresh re-minted a LiveKit token without re-checking
CONNECT_VOICE, so a revoked permission kept working for the life of the
session. The permission is now re-checked where the token is minted, and a
60s sweep evicts participants whose permission was revoked.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ws): rate-limit voice_e2ee_offer after validation, keyed on server state (F7)

The limiter key was built from unvalidated client input, letting an attacker
grow the limiter map without bound. The limiter now runs after validation and
keys on (sender, voiceChannelID), never on client input.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ws): deliver voice_state/voice_leave only to roles that may read the channel (F9)

Voice state of private channels was broadcast to every connected client,
leaking channel membership. All 11 emit sites now route through one
READ-filtered fan-out, channel-tagged so replay filters too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(api): redact the LiveKit access token from proxy dial-failure logs (F10)

A dial failure wrote the LiveKit access-token JWT into the server log via the
URL in the error. redactKey now runs on the error before it reaches slog.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): reserve the [deleted-N] username namespace (F11, F12)

The tombstone username namespace used by account deletion was freely
registrable, letting a user impersonate a deleted account. The namespace is
now reserved at validation, and DeleteAccount retries with a random suffix on
collision.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(api): strip Unicode format characters from upload filenames (F13)

The attachment filename sanitizer stripped control characters but not
unicode.Cf, allowing bidi-override extension spoofing. Cf is now stripped
alongside controls and foreign path separators are cut.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(api): reserve the login attempt before the bcrypt compare (F3)

The per-username lockout was a read-only IsLockedOut check followed by a
failure recorded only after the ~250ms bcrypt compare, so N concurrent
requests all passed the stale check before any of them recorded a failure.
The per-username cap is the only cross-IP brute-force defence (the middleware
limits per IP), so a distributed burst landed N guesses per 15-minute window
instead of 10.

Both counters are now reserved atomically with limiter.Allow before the
compare, and the lockout decision moves to the read-only limiter.Check so the
reservation is not double-counted. The limits are sized at threshold+1, which
leaves the sequential accepted-input set byte-identical to the previous
behaviour: failures 1-10 still land, the 10th still trips the lockout, and the
account owner's correct password on attempt 10 still returns 200. Sizing at
threshold instead would make 9 cheap wrong guesses convert the victim's own
correct password into a 15-minute lockout - the regression that got two
earlier attempts at this fix rejected, now pinned by a boundary test.

Deliberately scoped to handleLogin. The report also suggested widening to the
password-confirmation endpoints, but those are authenticated, share a single
pw_confirm_fail key across the TOTP endpoints, and widening there is what got
the first attempt rejected.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(deps): bump five Rust dependencies in /Client/tauri-client/src-tauri

Rolls up dependabot #1259, #1260, #1261, #1262 and #1263:

  tauri-build        2.5.6 -> 2.6.3
  tauri-plugin-fs    2.4.5 -> 2.5.1
  tauri-plugin-http  2.5.7 -> 2.5.9
  tauri-plugin-store 2.4.2 -> 2.4.4
  webpki-roots       1.0.6 -> 1.0.9

All five are lockfile-only; the manifest constraints already permitted the
new versions. The five PRs each rewrote overlapping regions of the same
Cargo.lock and so could not be merged independently, so the lockfile was
regenerated with cargo update --precise for each crate instead. The combined
result is smaller than the sum of the five diffs because they share
transitive updates.

Verified with cargo check --locked --all-targets (exit 0).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(deps): bump typescript-eslint from 8.58.0 to 8.65.0 in /Client/tauri-client

Dependabot #1258.

8.65.0 improves @typescript-eslint/no-unnecessary-type-assertion, which
surfaces four assertions that were already redundant and now fail the lint
gate. They are removed here rather than in a follow-up so no commit in this
branch leaves `npm run lint` red:

  UserBar.ts / members.store.ts  "online" as UserStatus -> "online"
                                 (the receiver already accepts the literal)
  media.ts                       drops `as RequestInit` on a literal that is
                                 already assignable
  LoginForm.ts                   drops `as { message: unknown }` made
                                 redundant by the `"message" in err` narrowing

All four are the rule's own autofix. Verified: npm run typecheck, npm run
lint, npm run format:check all clean, and the unit suite is 3572/3572 green
across 129 files.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-29 12:48:47 +02:00

279 lines
9.3 KiB
Go

package api
import (
"bytes"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// --- isWebSocketUpgrade tests ---
func TestIsWebSocketUpgrade_ValidUpgrade(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Connection", "Upgrade")
r.Header.Set("Upgrade", "websocket")
if !isWebSocketUpgrade(r) {
t.Error("expected true for valid WebSocket upgrade")
}
}
func TestIsWebSocketUpgrade_CaseInsensitive(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Connection", "upgrade")
r.Header.Set("Upgrade", "WebSocket")
if !isWebSocketUpgrade(r) {
t.Error("expected true for case-insensitive upgrade headers")
}
}
func TestIsWebSocketUpgrade_MissingConnectionHeader(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Upgrade", "websocket")
if isWebSocketUpgrade(r) {
t.Error("expected false when Connection header is missing")
}
}
func TestIsWebSocketUpgrade_MissingUpgradeHeader(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Connection", "Upgrade")
if isWebSocketUpgrade(r) {
t.Error("expected false when Upgrade header is missing")
}
}
func TestIsWebSocketUpgrade_NonWebsocketUpgrade(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Connection", "Upgrade")
r.Header.Set("Upgrade", "h2c")
if isWebSocketUpgrade(r) {
t.Error("expected false for non-websocket upgrade")
}
}
func TestIsWebSocketUpgrade_ConnectionKeepAlive(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Connection", "keep-alive")
r.Header.Set("Upgrade", "websocket")
if isWebSocketUpgrade(r) {
t.Error("expected false when Connection is keep-alive")
}
}
// --- isOriginAllowed tests ---
func TestIsOriginAllowed_EmptyOriginAllowed(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
// No Origin header = same-origin or non-browser
if !isOriginAllowed(r, []string{"https://example.com"}) {
t.Error("expected true when no Origin header (same-origin)")
}
}
func TestIsOriginAllowed_MatchingOrigin(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Origin", "https://example.com")
if !isOriginAllowed(r, []string{"https://example.com"}) {
t.Error("expected true for matching origin")
}
}
func TestIsOriginAllowed_CaseInsensitive(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Origin", "HTTPS://EXAMPLE.COM")
if !isOriginAllowed(r, []string{"https://example.com"}) {
t.Error("expected true for case-insensitive origin match")
}
}
func TestIsOriginAllowed_NonMatchingOrigin(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Origin", "https://evil.com")
if isOriginAllowed(r, []string{"https://example.com"}) {
t.Error("expected false for non-matching origin")
}
}
func TestIsOriginAllowed_WildcardAllowsAll(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Origin", "https://anything.com")
if !isOriginAllowed(r, []string{"*"}) {
t.Error("expected true for wildcard origin")
}
}
func TestIsOriginAllowed_EmptyAllowlistDenies(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Origin", "https://example.com")
if isOriginAllowed(r, []string{}) {
t.Error("expected false when allowlist is empty")
}
}
func TestIsOriginAllowed_MultipleAllowedOrigins(t *testing.T) {
r := httptest.NewRequest("GET", "/livekit/", nil)
r.Header.Set("Origin", "https://b.com")
allowed := []string{"https://a.com", "https://b.com", "https://c.com"}
if !isOriginAllowed(r, allowed) {
t.Error("expected true for origin in multi-origin allowlist")
}
}
// --- NewLiveKitProxy HTTP routing tests ---
func TestLiveKitProxy_BlocksAdminPath(t *testing.T) {
proxy := NewLiveKitProxy("http://localhost:7880", []string{"*"})
r := httptest.NewRequest("GET", "/admin/dashboard", nil)
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 for /admin path, got %d", w.Code)
}
}
func TestLiveKitProxy_BlocksMetricsPath(t *testing.T) {
proxy := NewLiveKitProxy("http://localhost:7880", []string{"*"})
r := httptest.NewRequest("GET", "/metrics", nil)
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 for /metrics path, got %d", w.Code)
}
}
func TestLiveKitProxy_BlocksDebugPath(t *testing.T) {
proxy := NewLiveKitProxy("http://localhost:7880", []string{"*"})
r := httptest.NewRequest("GET", "/debug/pprof", nil)
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 for /debug path, got %d", w.Code)
}
}
func TestLiveKitProxy_BlocksTwirpPath(t *testing.T) {
proxy := NewLiveKitProxy("http://localhost:7880", []string{"*"})
r := httptest.NewRequest("POST", "/twirp/livekit.RoomService/ListRooms", nil)
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 for /twirp path, got %d", w.Code)
}
}
func TestLiveKitProxy_AllowsNormalPath(t *testing.T) {
// Use a test backend that returns 200
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK")) //nolint:errcheck
}))
defer backend.Close()
proxy := NewLiveKitProxy(backend.URL, []string{"*"})
r := httptest.NewRequest("GET", "/rtc", nil)
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("expected 200 for normal path, got %d", w.Code)
}
}
func TestLiveKitProxy_BlocksCrossOriginHTTP(t *testing.T) {
proxy := NewLiveKitProxy("http://localhost:7880", []string{"https://myapp.com"})
r := httptest.NewRequest("GET", "/rtc", nil)
r.Header.Set("Origin", "https://evil.com")
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 for cross-origin HTTP, got %d", w.Code)
}
}
func TestLiveKitProxy_AllowsSameOriginHTTP(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer backend.Close()
proxy := NewLiveKitProxy(backend.URL, []string{"https://myapp.com"})
r := httptest.NewRequest("GET", "/rtc", nil)
r.Header.Set("Origin", "https://myapp.com")
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("expected 200 for same-origin HTTP, got %d", w.Code)
}
}
func TestLiveKitProxy_DoesNotBlockUserMetrics(t *testing.T) {
// "/user-metrics" should NOT be blocked (only "/metrics" segment is blocked)
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer backend.Close()
proxy := NewLiveKitProxy(backend.URL, []string{"*"})
r := httptest.NewRequest("GET", "/user-metrics", nil)
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
// The path is split by "/" — "user-metrics" is one segment, not "metrics"
// Wait — actually the blocked check splits by "/" and checks each segment.
// "/user-metrics" splits to ["", "user-metrics"] so "user-metrics" != "metrics". Should pass.
if w.Code != http.StatusOK {
t.Errorf("expected 200 for /user-metrics (not an exact segment match), got %d", w.Code)
}
}
// TestProxyWebSocket_DialFailureDoesNotLogAccessToken locks the credential out
// of the log stream: websocket.Dial wraps a *url.Error carrying the full
// backend URL, so a dial failure (LiveKit down, restarting, refused) used to
// print the caller's live room-join JWT at Warn level — replayable inside its
// 5-minute TTL by anyone reading stdout or the admin panel's log ring buffer.
func TestProxyWebSocket_DialFailureDoesNotLogAccessToken(t *testing.T) {
const token = "eyJhbGciOiJIUzI1NiJ9.SECRET-LIVEKIT-JWT-PAYLOAD.c2lnbmF0dXJl"
var logs bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})))
t.Cleanup(func() { slog.SetDefault(prev) })
// Port 1 on loopback refuses connections, which is the exact branch where
// the wrapped *url.Error carries the query string.
proxy := NewLiveKitProxy("http://127.0.0.1:1", []string{"*"})
r := httptest.NewRequest("GET", "/rtc?access_token="+token, nil)
r.Header.Set("Connection", "Upgrade")
r.Header.Set("Upgrade", "websocket")
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
if w.Code != http.StatusBadGateway {
t.Fatalf("expected 502 when the backend refuses the dial, got %d", w.Code)
}
out := logs.String()
if out == "" {
t.Fatal("expected the dial failure to be logged at all")
}
if strings.Contains(out, token) {
t.Fatalf("the LiveKit access token leaked into the log stream:\n%s", out)
}
if !strings.Contains(out, "backend dial failed") {
t.Errorf("the failure must still be diagnosable, got:\n%s", out)
}
}
func TestLiveKitProxy_InvalidURL_FallsBackToLocalhost(t *testing.T) {
// Should not panic with invalid URL
proxy := NewLiveKitProxy("://invalid", []string{"*"})
r := httptest.NewRequest("GET", "/rtc", nil)
w := httptest.NewRecorder()
// This will fail to connect to localhost:7880, but should not panic
proxy.ServeHTTP(w, r)
// We expect a 502 or similar because localhost:7880 isn't running
if w.Code == http.StatusOK {
t.Error("expected non-200 for invalid backend URL fallback")
}
}