Files
OwnCord/Server/ws/emit_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

403 lines
13 KiB
Go

package ws
import (
"context"
"testing"
"time"
)
// drainChan reads all pending messages from a buffered chan []byte within a
// short timeout. Returns the collected messages.
func drainChan(ch chan []byte, timeout time.Duration) [][]byte {
var msgs [][]byte
timer := time.NewTimer(timeout)
defer timer.Stop()
for {
select {
case msg := <-ch:
msgs = append(msgs, msg)
case <-timer.C:
return msgs
}
}
}
// newEmitTestHub creates a minimal Hub suitable for EmitEvents tests.
// No DB, no limiter, no registry — just the client map, broadcast channel,
// and the locks needed for delivery.
func newEmitTestHub() *Hub {
return &Hub{
clients: make(map[int64]*Client),
broadcast: make(chan broadcastMsg, 64),
clientEvents: make(chan clientEvent, 32),
stop: make(chan struct{}),
pubsub: NewPubSub(),
replayBuf: NewEventRingBuffer(100),
voiceKeyHolders: make(map[int64]int64),
topicLimiter: NewTopicRateLimiter(topicRateLimitPerSecond, time.Second),
}
}
// registerEmitTestClient creates a test client, registers it directly in the
// hub's client map, and returns the send channel for assertions.
func registerEmitTestClient(h *Hub, userID, channelID int64) chan []byte {
send := make(chan []byte, 192) // sized for all priority levels
c := NewTestClientWithChannel(h, userID, channelID, send)
// Wire high- and low-priority channels to the same observable channel so
// drainChan captures messages regardless of which priority path delivers.
c.sendHigh = send
c.sendLow = send
h.clients[userID] = c
// Subscribe to pub/sub topics so deliverBroadcast can reach this client.
h.pubsub.Subscribe(c, TopicGlobal)
h.pubsub.Subscribe(c, UserTopic(userID))
if channelID > 0 {
h.pubsub.Subscribe(c, ChannelTopic(channelID))
}
return send
}
// registerEmitTestVoiceClient creates a test client in a voice channel.
func registerEmitTestVoiceClient(h *Hub, userID, channelID, voiceChID int64) chan []byte {
send := make(chan []byte, 192)
c := NewTestClientWithChannel(h, userID, channelID, send)
c.sendHigh = send
c.sendLow = send
SetClientVoiceChID(c, voiceChID)
h.clients[userID] = c
// Subscribe to pub/sub topics so deliverBroadcast can reach this client.
h.pubsub.Subscribe(c, TopicGlobal)
h.pubsub.Subscribe(c, UserTopic(userID))
if channelID > 0 {
h.pubsub.Subscribe(c, ChannelTopic(channelID))
}
if voiceChID > 0 {
h.pubsub.Subscribe(c, ChannelTopic(voiceChID))
}
return send
}
// ── stub events for testing ──────────────────────────────────────────────────
type stubChannelEvent struct {
channelID int64
payload []byte
}
func (e stubChannelEvent) EventType() string { return "test_channel" }
func (e stubChannelEvent) ChannelID() int64 { return e.channelID }
func (e stubChannelEvent) Payload() []byte { return e.payload }
type stubExcludeSenderEvent struct {
channelID int64
excludeUserID int64
payload []byte
}
func (e stubExcludeSenderEvent) EventType() string { return "test_exclude" }
func (e stubExcludeSenderEvent) ChannelID() int64 { return e.channelID }
func (e stubExcludeSenderEvent) ExcludeUserID() int64 { return e.excludeUserID }
func (e stubExcludeSenderEvent) Payload() []byte { return e.payload }
type stubSequencedDMEvent struct {
channelID int64
participantIDs []int64
payload []byte
}
func (e stubSequencedDMEvent) EventType() string { return "test_dm" }
func (e stubSequencedDMEvent) ChannelID() int64 { return e.channelID }
func (e stubSequencedDMEvent) ParticipantIDs() []int64 { return e.participantIDs }
func (e stubSequencedDMEvent) Payload() []byte { return e.payload }
type stubUserTargetedEvent struct {
targetUserID int64
payload []byte
}
func (e stubUserTargetedEvent) EventType() string { return "test_targeted" }
func (e stubUserTargetedEvent) TargetUserID() int64 { return e.targetUserID }
func (e stubUserTargetedEvent) Payload() []byte { return e.payload }
type stubBroadcastAllEvent struct {
payload []byte
}
func (e stubBroadcastAllEvent) EventType() string { return "test_broadcast_all" }
func (e stubBroadcastAllEvent) Payload() []byte { return e.payload }
type stubVoiceChannelEvent struct {
voiceChannelID int64
excludeUserID int64
payload []byte
}
func (e stubVoiceChannelEvent) EventType() string { return "test_voice" }
func (e stubVoiceChannelEvent) VoiceChannelID() int64 { return e.voiceChannelID }
func (e stubVoiceChannelEvent) ExcludeUserID() int64 { return e.excludeUserID }
func (e stubVoiceChannelEvent) Payload() []byte { return e.payload }
type stubVoiceChannelGuardedEvent struct {
voiceChannelID int64
targetUserID int64
payload []byte
}
func (e stubVoiceChannelGuardedEvent) EventType() string { return "test_voice_guarded" }
func (e stubVoiceChannelGuardedEvent) VoiceChannelID() int64 { return e.voiceChannelID }
func (e stubVoiceChannelGuardedEvent) TargetUserID() int64 { return e.targetUserID }
func (e stubVoiceChannelGuardedEvent) Payload() []byte { return e.payload }
type stubUnknownEvent struct{}
func (e stubUnknownEvent) EventType() string { return "test_unknown" }
// ── tests ────────────────────────────────────────────────────────────────────
func TestEmitEvents_ChannelEvent_CallsBroadcastToChannel(t *testing.T) {
h := newEmitTestHub()
send1 := registerEmitTestClient(h, 1, 42)
_ = registerEmitTestClient(h, 2, 99) // different channel
payload := []byte(`{"type":"test"}`)
events := []Event{stubChannelEvent{channelID: 42, payload: payload}}
// BroadcastToChannel is async (via broadcast chan), so we run the
// hub loop briefly to deliver.
go h.Run()
defer h.Stop()
h.EmitEvents(context.Background(), events)
// Give the hub loop time to deliver.
msgs := drainChan(send1, 100*time.Millisecond)
if len(msgs) == 0 {
t.Fatal("expected client 1 (channel 42) to receive the channel event")
}
}
func TestEmitEvents_ExcludeSenderEvent(t *testing.T) {
h := newEmitTestHub()
sendSender := registerEmitTestClient(h, 1, 42)
sendOther := registerEmitTestClient(h, 2, 42)
payload := []byte(`{"type":"typing"}`)
events := []Event{stubExcludeSenderEvent{channelID: 42, excludeUserID: 1, payload: payload}}
h.EmitEvents(context.Background(), events)
// broadcastExcludeLow is synchronous — check immediately.
senderMsgs := drainChan(sendSender, 50*time.Millisecond)
otherMsgs := drainChan(sendOther, 50*time.Millisecond)
if len(senderMsgs) != 0 {
t.Errorf("sender should be excluded, got %d messages", len(senderMsgs))
}
if len(otherMsgs) != 1 {
t.Errorf("other client should receive 1 message, got %d", len(otherMsgs))
}
}
func TestEmitEvents_SequencedDMEvent(t *testing.T) {
h := newEmitTestHub()
send1 := registerEmitTestClient(h, 1, 0)
send2 := registerEmitTestClient(h, 2, 0)
send3 := registerEmitTestClient(h, 3, 0) // not a participant
payload := []byte(`{"type":"dm_msg"}`)
events := []Event{stubSequencedDMEvent{
channelID: 100,
participantIDs: []int64{1, 2},
payload: payload,
}}
h.EmitEvents(context.Background(), events)
msgs1 := drainChan(send1, 50*time.Millisecond)
msgs2 := drainChan(send2, 50*time.Millisecond)
msgs3 := drainChan(send3, 50*time.Millisecond)
if len(msgs1) != 1 {
t.Errorf("participant 1 should receive 1 message, got %d", len(msgs1))
}
if len(msgs2) != 1 {
t.Errorf("participant 2 should receive 1 message, got %d", len(msgs2))
}
if len(msgs3) != 0 {
t.Errorf("non-participant (client 3) should receive 0 messages, got %d", len(msgs3))
}
}
func TestEmitEvents_UserTargetedEvent(t *testing.T) {
h := newEmitTestHub()
send1 := registerEmitTestClient(h, 1, 0)
send2 := registerEmitTestClient(h, 2, 0)
payload := []byte(`{"type":"targeted"}`)
events := []Event{stubUserTargetedEvent{targetUserID: 2, payload: payload}}
h.EmitEvents(context.Background(), events)
msgs1 := drainChan(send1, 50*time.Millisecond)
msgs2 := drainChan(send2, 50*time.Millisecond)
if len(msgs1) != 0 {
t.Errorf("user 1 should not receive targeted event, got %d", len(msgs1))
}
if len(msgs2) != 1 {
t.Errorf("user 2 should receive 1 targeted message, got %d", len(msgs2))
}
}
func TestEmitEvents_BroadcastAllEvent(t *testing.T) {
h := newEmitTestHub()
send1 := registerEmitTestClient(h, 1, 42)
send2 := registerEmitTestClient(h, 2, 99)
payload := []byte(`{"type":"global"}`)
events := []Event{stubBroadcastAllEvent{payload: payload}}
// BroadcastToAll goes through the broadcast channel, need hub loop.
go h.Run()
defer h.Stop()
h.EmitEvents(context.Background(), events)
msgs1 := drainChan(send1, 100*time.Millisecond)
msgs2 := drainChan(send2, 100*time.Millisecond)
if len(msgs1) == 0 {
t.Error("user 1 should receive broadcast_all event")
}
if len(msgs2) == 0 {
t.Error("user 2 should receive broadcast_all event")
}
}
func TestEmitEvents_VoiceChannelEvent(t *testing.T) {
h := newEmitTestHub()
sendSender := registerEmitTestVoiceClient(h, 1, 0, 50)
sendOther := registerEmitTestVoiceClient(h, 2, 0, 50)
sendOutside := registerEmitTestVoiceClient(h, 3, 0, 99) // different voice channel
payload := []byte(`{"type":"voice_e2ee"}`)
events := []Event{stubVoiceChannelEvent{
voiceChannelID: 50,
excludeUserID: 1,
payload: payload,
}}
h.EmitEvents(context.Background(), events)
senderMsgs := drainChan(sendSender, 50*time.Millisecond)
otherMsgs := drainChan(sendOther, 50*time.Millisecond)
outsideMsgs := drainChan(sendOutside, 50*time.Millisecond)
if len(senderMsgs) != 0 {
t.Errorf("sender should be excluded from voice event, got %d", len(senderMsgs))
}
if len(otherMsgs) != 1 {
t.Errorf("voice participant should receive 1 message, got %d", len(otherMsgs))
}
if len(outsideMsgs) != 0 {
t.Errorf("client in different voice channel should not receive, got %d", len(outsideMsgs))
}
}
func TestEmitEvents_VoiceChannelGuardedEvent(t *testing.T) {
h := newEmitTestHub()
// Target is in voice channel 50.
sendTarget := registerEmitTestVoiceClient(h, 2, 0, 50)
// User 3 is in the same voice channel but is not the target.
sendOther := registerEmitTestVoiceClient(h, 3, 0, 50)
// User 4 is in a different voice channel.
sendOutside := registerEmitTestVoiceClient(h, 4, 0, 99)
payload := []byte(`{"type":"voice_e2ee_offer"}`)
events := []Event{stubVoiceChannelGuardedEvent{
voiceChannelID: 50,
targetUserID: 2,
payload: payload,
}}
h.EmitEvents(context.Background(), events)
targetMsgs := drainChan(sendTarget, 50*time.Millisecond)
otherMsgs := drainChan(sendOther, 50*time.Millisecond)
outsideMsgs := drainChan(sendOutside, 50*time.Millisecond)
if len(targetMsgs) != 1 {
t.Errorf("target in voice channel should receive 1 message, got %d", len(targetMsgs))
}
if len(otherMsgs) != 0 {
t.Errorf("non-target in same voice channel should not receive, got %d", len(otherMsgs))
}
if len(outsideMsgs) != 0 {
t.Errorf("client in different voice channel should not receive, got %d", len(outsideMsgs))
}
}
func TestEmitEvents_VoiceChannelGuardedEvent_TargetNotInChannel(t *testing.T) {
h := newEmitTestHub()
// Target is in voice channel 99, but event targets voice channel 50.
sendTarget := registerEmitTestVoiceClient(h, 2, 0, 99)
payload := []byte(`{"type":"voice_e2ee_offer"}`)
events := []Event{stubVoiceChannelGuardedEvent{
voiceChannelID: 50,
targetUserID: 2,
payload: payload,
}}
h.EmitEvents(context.Background(), events)
targetMsgs := drainChan(sendTarget, 50*time.Millisecond)
if len(targetMsgs) != 0 {
t.Errorf("target in wrong voice channel should not receive, got %d", len(targetMsgs))
}
}
func TestEmitEvents_EmptyEvents_NoOp(t *testing.T) {
h := newEmitTestHub()
_ = registerEmitTestClient(h, 1, 42)
// Should not panic or block.
h.EmitEvents(context.Background(), nil)
h.EmitEvents(context.Background(), []Event{})
}
func TestEmitEvents_MixedEventTypes_AllRouted(t *testing.T) {
h := newEmitTestHub()
sendCh := registerEmitTestClient(h, 1, 42)
sendTarget := registerEmitTestClient(h, 2, 0)
// BroadcastToChannel is async, need hub loop for channel events.
go h.Run()
defer h.Stop()
events := []Event{
stubExcludeSenderEvent{channelID: 42, excludeUserID: 99, payload: []byte(`{"e":1}`)},
stubUserTargetedEvent{targetUserID: 2, payload: []byte(`{"e":2}`)},
}
h.EmitEvents(context.Background(), events)
chMsgs := drainChan(sendCh, 100*time.Millisecond)
targetMsgs := drainChan(sendTarget, 100*time.Millisecond)
if len(chMsgs) != 1 {
t.Errorf("channel client should receive exclude event, got %d", len(chMsgs))
}
if len(targetMsgs) != 1 {
t.Errorf("targeted client should receive 1 message, got %d", len(targetMsgs))
}
}
func TestEmitEvents_UnknownType_LogsWarning(t *testing.T) {
h := newEmitTestHub()
_ = registerEmitTestClient(h, 1, 42)
// Should not panic; logs a warning (we verify no crash, not log content).
h.EmitEvents(context.Background(), []Event{stubUnknownEvent{}})
}