mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* fix(identity): 2 defect(s) (OC-0192, OC-0197)
OC-0192: bound raw display_name/about/avatar bytes before the quadratic
fixpoint sanitizer runs, in both the REST handler and UserService.UpdateProfile.
OC-0197: sanitize display_name before validateDisplayName so an
HTML-entity-encoded bidi override (e.g. "‮") can no longer pass
validation as ASCII and be decoded into the real character on the way to
storage.
* fix(ws): 1 defect(s) (OC-0196)
A transient DB error during WebSocket auth (session or user lookup) was
collapsed into the terminal auth_error frame, which the client treats as
non-recoverable: it stops reconnecting and clears stored credentials. A
sub-second SQLite hiccup therefore force-logged-out every reconnecting
client with a perfectly valid session. Send a non-terminal INTERNAL error
frame instead so normal backoff/reconnect retries.
* fix(api): 1 defect(s) (OC-0198)
* fix(ws): 1 defect(s) (OC-0200)
normalizeHostForCertCompare now unwraps a bracketed IPv6 literal after the
trailing-":443" strip and before lowercasing, matching tofu::cert_store_key's
normalization order. Without the unwrap, every cert-tofu host equality guard
took the "unrelated host" branch for bracketed-IPv6 servers.
* fix(api): 1 defect(s) (OC-0202)
* fix(admin): 1 defect(s) (OC-0203)
Channel permission override handlers applied requireGrantableOverride only
to the bits being written, so an all-zero PUT or a DELETE could clear a
deny bit the actor's own role does not hold — EffectivePerms =
(rolePerm &^ deny) | allow makes removing a deny an escalation. Both the
role-layer and per-user handlers now check the guard against the bits
already on the row.
* fix(client): 1 defect(s) (OC-0205)
* fix(client): 3 defect(s) (OC-0207, OC-0227, OC-0235)
* fix(client): 1 defect(s) (OC-0208)
* fix(voice): 3 defect(s) (OC-0209, OC-0212, OC-0213)
OC-0209: reject a replayed retired-key announce before verifyPeerAnnounce
runs, so the replay cannot overwrite the peer's displayed verification
status/session fingerprint with the retired key's before being rejected.
OC-0212: buffer an announce blocked as a TOFU pin mismatch and replay it
after a successful rePinPeerIdentity, so re-pinning actually restores the
peer for the live call instead of clearing the badge and leaving them
un-keyed (a mid-call peer never re-announces on its own).
OC-0213: skip retiring a departing peer's key when the local voice roster
still lists them as present — a rejoin announce published straight into
the send queue can overtake the buffered, stale voice_leave, and retiring
a still-live key would reject every later genuine re-announce as a replay.
* fix(ws): 1 defect(s) (OC-0211)
* fix(identity): 1 defect(s) (OC-0214)
The delete-account admin guard counted remaining admins with a raw
`banned = 0` filter, so an admin whose temporary ban had already lapsed
was treated as unusable. Use the shared notBannedClause, appended outside
the Sprintf format string because its strftime verbs (%Y, %H) would
otherwise be parsed as fmt directives.
* fix(client): 1 defect(s) (OC-0215)
* fix(voice): 1 defect(s) (OC-0216)
* fix(client): 1 defect(s) (OC-0217)
* fix(voice): 1 defect(s) (OC-0219)
rollbackVoiceJoin cleared the client's in-memory voiceChID but left its
VoiceTopic subscription in place, so a socket whose join failed after
voiceJoinComplete's Subscribe kept receiving that room's E2EE relays for
the rest of the connection. Use clearVoiceAndUnsubscribe instead, matching
every other path that takes a client out of voice while its WS stays up.
* fix(client): 2 defect(s) (OC-0220, OC-0224)
dmDisplayName: a group DM whose other members have all left keeps a live
is_group row, but the server leaves `recipient` zero-valued, so the empty
username fell through as a blank label. Fall back to a non-empty placeholder.
updateDmLastMessage: a queued chat_message redelivered for an id already
reflected in the `ready` snapshot double-counted the unread badge. Only
increment when the message id advances past lastMessageId.
* fix(client): 1 defect(s) (OC-0221)
Cap queued attachments at the server's 10-attachment limit in the message
composer. Past that the server rejects the whole chat_send frame as a
generic parse error, orphaning already-uploaded attachments; refusing
before the upload starts keeps composer state and the send in sync.
* fix(ws): 1 defect(s) (OC-0222)
handleReconnect built the resume auth_ok before applyConnectStatus settled
c.user.Status, so a resumed client was told its disconnect-time status
(routinely "offline") instead of the status it was coming online as.
Move applyConnectStatus ahead of reconnectWriteReplay, matching
handleFreshConnect's ordering.
* fix(mentions): 1 defect(s) (OC-0223)
* fix(admin): 1 defect(s) (OC-0225)
* fix(client): 1 defect(s) (OC-0226)
* fix(client): 1 defect(s) (OC-0228)
* fix(client): 1 defect(s) (OC-0230)
Route the Logs tab entry counter through renderLogEntries so every render path (filter change, Clear, Refresh, live entry) keeps the count in sync with the list.
* fix(voice): 1 defect(s) (OC-0231)
* fix(client): 1 defect(s) (OC-0232)
Reduce Motion toggle wrote the reduced-motion class directly, fighting the
OS-sync media-query listener that owns it when Sync with OS is on. Route the
side effect through syncOsMotionListener so whichever source owns the class
re-derives it.
* fix(client): 1 defect(s) (OC-0233)
notifyIncomingMessage titled the desktop notification with the raw
payload username, so the popup named the sender differently from the
message row it points at. Resolve the author the same way the message
list does (resolveAuthor over the live membersStore, then
resolveDisplayName).
* fix(client): 1 defect(s) (OC-0234)
* fix(client): 1 defect(s) (OC-0236)
* fix(ws): 1 defect(s) (OC-0237)
* fix(client): 4 defect(s) (OC-0193, OC-0201, OC-0204, OC-0218)
* fix(identity): 1 defect(s) (OC-0195)
Bound free-text profile fields by raw byte length before cleanText's
quadratic sanitizeToFixpoint pass runs, generalizing OC-0192's guard into
cleanTextBounded and applying it to HandlePresenceUpdate's custom_status,
SetCustomStatus, and group DM names.
* fix(dm): 1 defect(s) (OC-0199)
handleCreateDM now broadcasts dm_channel_open to the recipient when a 1:1 DM is newly created, matching handleCreateGroupDM. GetOrCreateDMChannel pre-seeds dm_open_state for both users, so the recipient's later OpenDM reported opened=false and nothing ever told them the DM existed.
* fix(voice): 1 defect(s) (OC-0206)
vad-worklet.js gate timing constants were copied from the setTimeout
fallback's ~16ms poll cadence, but AudioWorkletProcessor.process() runs
once per 128-sample render quantum (~2.667ms at the 48kHz AudioContext).
The mic gate therefore closed ~6x faster than intended (~32ms of silence
instead of ~200ms), with the startup grace and RMS post interval off by
the same factor. Scale the frame counts to render quanta.
* fix(client): 1 defect(s) (OC-0229)
* test(client): assert the real TOFU re-pin outcome and make the pin mock faithful
The e2e journey test asserted that "Trust New Key" makes the peer's verify
badge disappear. That is the behaviour OC-0212 identifies as the defect: a
mid-call peer never re-announces, so clearing the badge left the peer
un-keyed for the rest of the call with nothing on screen. Re-pinning now
replays the announce that was blocked as a mismatch and re-verifies it
against the pin just stored, so assert the peer actually lands verified.
The mock's store_identity_pin was a no-op recorder while get_identity_pin
served a static seed map, so the replayed announce re-read the stale pin and
re-failed — a mismatch the real keyring never produces. Back the pins with a
mutable map so a write is visible to the next read. The unreadable-store
(DC-08) and reject-keeps-blocked paths are unchanged and still pass.
* fix(dm): 1 defect(s) (OC-0194)
Add regression tests pinning the raw-byte bound on group DM names, for
both CreateGroupDM and RenameGroupDM.
The Server/service/dm.go source fix for OC-0194 already landed in
bdbd5ac (fix(identity): 1 defect(s) (OC-0195)), which generalized the
guard into cleanTextBounded and applied it to the group DM name paths
alongside the profile fields. This commit therefore carries the OC-0194
tests only; dm.go is unchanged.
Revert-proof: with dm.go restored to bdbd5ac^ (cleanText before the
rune-count check) both new tests fail — CreateGroupDM returns "recipient
not found" after 222ms and RenameGroupDM accepts the name after 251ms,
against a 150ms budget. With the fix in place both pass in 0.03s.
* fix(ws): 1 defect(s) (OC-0210)
* chore(findings): record the 2026-08-20 hunt's 46 findings as fixed
Appends OC-0192..OC-0237 from the 2026-08-20 converging hunt and marks each
fixed with its commit and the test that pins it. Pre-existing records are
byte-identical; nextId moves 192 -> 238 so the next hunt cannot collide with
these ids.
Every fix was independently revert-proofed: the commit's own source diff is
reverse-applied, its test must go red, and must return green once restored.
43 of 46 carry revertProof "pass" from that mechanical run. Three could not be
checked at file level and were proved by hand at hunk level instead, recorded
as "pass (hand-proved)": OC-0200, whose ws.ts edit no longer reverse-applies
because the merge kept main's equivalent implementation; OC-0215, whose Rust
tests live in-file under #[cfg(test)]; and OC-0194, which stacks on a helper
introduced by an earlier commit. No fix was found to rest on a vacuous test.
OC-0200 additionally carries a note: main fixed that same normalizer
independently while this branch was in flight, so the branch is no longer the
only thing closing it.
* docs: record the dm_channel_open emission on 1:1 DM creation
POST /api/v1/dms now emits dm_channel_open to the recipient when it creates a
channel (it previously emitted nothing on that path), so api.md states it the
way the sibling DM endpoints already state theirs.
The channels/members/DMs UX spec claimed the server broadcast the event "to
both parties" on this flow. That was never true — nothing was broadcast before,
and now only the recipient is sent it; the creator learns the channel from the
response body. This doc lists dispatcher.ts, dm.store.ts, ChannelSidebar.ts,
service/channel.go and dm.go among its sources of truth, all touched here, so
it is corrected in the same change per its maintenance rule.
---------
Co-authored-by: Claude <noreply@anthropic.com>
594 lines
22 KiB
Go
594 lines
22 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/owncord/server/db"
|
|
"github.com/owncord/server/permissions"
|
|
)
|
|
|
|
// newMentionFixture builds a channel 10 with three members (alice=1 author,
|
|
// bob=2 online, carol=3 offline) plus a moderator (mod=4) holding
|
|
// MENTION_EVERYONE. Every role can read channel 10.
|
|
func newMentionFixture(t *testing.T) (*MessageService, *ChannelService, *db.DB) {
|
|
t.Helper()
|
|
database := newTestDB(t)
|
|
seedRole(t, database, &db.Role{
|
|
ID: permissions.MemberRoleID,
|
|
Name: "member",
|
|
Permissions: permissions.SendMessages | permissions.ReadMessages,
|
|
Position: 1,
|
|
})
|
|
seedRole(t, database, &db.Role{
|
|
ID: permissions.ModeratorRoleID,
|
|
Name: "moderator",
|
|
Permissions: permissions.SendMessages | permissions.ReadMessages |
|
|
permissions.MentionEveryone,
|
|
Position: 60,
|
|
})
|
|
seedUser(t, database, &db.User{ID: 1, Username: "alice", Status: "online"})
|
|
seedUser(t, database, &db.User{ID: 2, Username: "Bob", Status: "online"})
|
|
seedUser(t, database, &db.User{ID: 3, Username: "carol", Status: "offline"})
|
|
seedUser(t, database, &db.User{ID: 4, Username: "mod", Status: "online"})
|
|
seedUserRole(t, database, 1, permissions.MemberRoleID)
|
|
seedUserRole(t, database, 2, permissions.MemberRoleID)
|
|
seedUserRole(t, database, 3, permissions.MemberRoleID)
|
|
seedUserRole(t, database, 4, permissions.ModeratorRoleID)
|
|
seedChannel(t, database, &db.Channel{ID: 10, Name: "general", Type: "text"})
|
|
|
|
checker := permissions.NewChecker(database)
|
|
permSvc := NewPermissionService(database, checker)
|
|
msgSvc := NewMessageService(database, permSvc, nil)
|
|
// Mention counts are written on a background goroutine in production; run
|
|
// them inline here so the tests can read the counts right after a send.
|
|
msgSvc.RunBackgroundInlineForTest()
|
|
return msgSvc, NewChannelService(database, permSvc), database
|
|
}
|
|
|
|
func sendAs(t *testing.T, svc *MessageService, userID int64, content string) *SendMessageResult {
|
|
t.Helper()
|
|
res, err := svc.SendMessage(context.Background(), SendMessageParams{
|
|
ChannelID: 10,
|
|
UserID: userID,
|
|
Username: "user",
|
|
RoleName: "member",
|
|
Content: content,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("SendMessage(%q): %v", content, err)
|
|
}
|
|
return res
|
|
}
|
|
|
|
func mentionCount(t *testing.T, database *db.DB, userID int64) int {
|
|
t.Helper()
|
|
n, err := database.GetMentionCount(context.Background(), userID, 10)
|
|
if err != nil {
|
|
t.Fatalf("GetMentionCount(%d): %v", userID, err)
|
|
}
|
|
return n
|
|
}
|
|
|
|
// ─── parsing ─────────────────────────────────────────────────────────────────
|
|
|
|
func TestParseMentionTokens(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
content string
|
|
wantTokens []string
|
|
wantEveryone bool
|
|
wantHere bool
|
|
}{
|
|
{name: "plain token", content: "hi @bob", wantTokens: []string{"bob"}},
|
|
{name: "lowercased", content: "hi @BoB", wantTokens: []string{"bob"}},
|
|
{name: "deduplicated", content: "@bob @bob @carol", wantTokens: []string{"bob", "carol"}},
|
|
{name: "no token", content: "no mentions here", wantTokens: nil},
|
|
{name: "email is not a mention", content: "write to bob@example.com", wantTokens: nil},
|
|
{name: "double at is not a mention", content: "@@bob", wantTokens: nil},
|
|
{name: "punctuation delimits", content: "(@bob), @carol!", wantTokens: []string{"bob", "carol"}},
|
|
{name: "everyone reserved", content: "@everyone hi", wantEveryone: true},
|
|
{name: "here reserved", content: "@here hi", wantHere: true},
|
|
{name: "case-insensitive reserved", content: "@EVERYONE", wantEveryone: true},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
tokens, everyone, here := parseMentionTokens(tt.content)
|
|
var got []string
|
|
for _, tok := range tokens {
|
|
got = append(got, tok.spellings[0])
|
|
}
|
|
if strings.Join(got, ",") != strings.Join(tt.wantTokens, ",") {
|
|
t.Errorf("tokens = %v, want %v", got, tt.wantTokens)
|
|
}
|
|
if everyone != tt.wantEveryone {
|
|
t.Errorf("everyone = %v, want %v", everyone, tt.wantEveryone)
|
|
}
|
|
if here != tt.wantHere {
|
|
t.Errorf("here = %v, want %v", here, tt.wantHere)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParseMentionTokens_TrailingPunctuationSpelling locks the fallback that
|
|
// makes "@bob." resolve to bob when no user is literally named "bob.".
|
|
func TestParseMentionTokens_TrailingPunctuationSpelling(t *testing.T) {
|
|
tokens, _, _ := parseMentionTokens("thanks @bob.")
|
|
if len(tokens) != 1 {
|
|
t.Fatalf("tokens = %d, want 1", len(tokens))
|
|
}
|
|
if got := tokens[0].spellings; len(got) != 2 || got[0] != "bob." || got[1] != "bob" {
|
|
t.Errorf("spellings = %v, want [bob. bob]", got)
|
|
}
|
|
}
|
|
|
|
func TestParseMentionTokens_CandidateCap(t *testing.T) {
|
|
var sb strings.Builder
|
|
for i := range maxMentionCandidates + 20 {
|
|
fmt.Fprintf(&sb, "@user%d ", i)
|
|
}
|
|
tokens, _, _ := parseMentionTokens(sb.String())
|
|
if len(tokens) != maxMentionCandidates {
|
|
t.Errorf("tokens = %d, want %d", len(tokens), maxMentionCandidates)
|
|
}
|
|
}
|
|
|
|
// ─── resolution on the send path ─────────────────────────────────────────────
|
|
|
|
func TestSendMessage_ResolvesKnownUsername(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
res := sendAs(t, svc, 1, "hey @Bob, look at this")
|
|
if len(res.Mentions) != 1 || res.Mentions[0] != 2 {
|
|
t.Fatalf("mentions = %v, want [2]", res.Mentions)
|
|
}
|
|
if res.MentionsEveryone {
|
|
t.Error("mentions_everyone should be false")
|
|
}
|
|
|
|
stored, err := database.GetMentionsByMessageIDs(context.Background(), []int64{res.MessageID})
|
|
if err != nil {
|
|
t.Fatalf("GetMentionsByMessageIDs: %v", err)
|
|
}
|
|
if len(stored[res.MessageID]) != 1 || stored[res.MessageID][0] != 2 {
|
|
t.Errorf("stored mentions = %v, want [2]", stored[res.MessageID])
|
|
}
|
|
}
|
|
|
|
func TestSendMessage_CaseInsensitiveUsername(t *testing.T) {
|
|
svc, _, _ := newMentionFixture(t)
|
|
|
|
res := sendAs(t, svc, 1, "hi @bOB")
|
|
if len(res.Mentions) != 1 || res.Mentions[0] != 2 {
|
|
t.Fatalf("mentions = %v, want [2]", res.Mentions)
|
|
}
|
|
}
|
|
|
|
// TestSendMessage_NonASCIIUppercaseUsernameResolves locks OC-0131: a username
|
|
// holding an uppercase non-ASCII letter is legal (auth.ValidateUsername only
|
|
// rejects control/format runes) and must still be @mentionable. Go's
|
|
// Unicode-aware strings.ToLower would fold "Émile" to "émile" before the
|
|
// lookup ever reaches SQL, but users.username is only COLLATE NOCASE, which
|
|
// folds ASCII A-Z only -- so a Unicode-lowered token can never match the
|
|
// stored non-ASCII-uppercase row, and the mention silently degrades to plain
|
|
// text.
|
|
func TestSendMessage_NonASCIIUppercaseUsernameResolves(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
seedUser(t, database, &db.User{ID: 5, Username: "Émile", Status: "online"})
|
|
seedUserRole(t, database, 5, permissions.MemberRoleID)
|
|
|
|
res := sendAs(t, svc, 1, "hey @Émile")
|
|
if len(res.Mentions) != 1 || res.Mentions[0] != 5 {
|
|
t.Fatalf("mentions = %v, want [5] (Émile must resolve)", res.Mentions)
|
|
}
|
|
}
|
|
|
|
func TestSendMessage_UnknownWordStaysText(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
res := sendAs(t, svc, 1, "@nobody @bob@example.com hello")
|
|
if len(res.Mentions) != 0 {
|
|
t.Fatalf("mentions = %v, want none", res.Mentions)
|
|
}
|
|
if res.Content != "@nobody @bob@example.com hello" {
|
|
t.Errorf("content was rewritten: %q", res.Content)
|
|
}
|
|
stored, err := database.GetMentionsByMessageIDs(context.Background(), []int64{res.MessageID})
|
|
if err != nil {
|
|
t.Fatalf("GetMentionsByMessageIDs: %v", err)
|
|
}
|
|
if len(stored) != 0 {
|
|
t.Errorf("stored mentions = %v, want none", stored)
|
|
}
|
|
}
|
|
|
|
func TestSendMessage_MentionCapped(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
// 25 distinct mentionable users, all readers of channel 10.
|
|
var sb strings.Builder
|
|
for i := range 25 {
|
|
id := int64(100 + i)
|
|
name := fmt.Sprintf("capuser%d", i)
|
|
seedUser(t, database, &db.User{ID: id, Username: name, Status: "online"})
|
|
seedUserRole(t, database, id, permissions.MemberRoleID)
|
|
sb.WriteString("@" + name + " ")
|
|
}
|
|
|
|
res := sendAs(t, svc, 1, sb.String())
|
|
if len(res.Mentions) != maxMentionsPerMessage {
|
|
t.Fatalf("mentions = %d, want %d", len(res.Mentions), maxMentionsPerMessage)
|
|
}
|
|
stored, err := database.GetMentionsByMessageIDs(context.Background(), []int64{res.MessageID})
|
|
if err != nil {
|
|
t.Fatalf("GetMentionsByMessageIDs: %v", err)
|
|
}
|
|
if len(stored[res.MessageID]) != maxMentionsPerMessage {
|
|
t.Errorf("stored = %d, want %d", len(stored[res.MessageID]), maxMentionsPerMessage)
|
|
}
|
|
}
|
|
|
|
// ─── @everyone / @here permission gate ───────────────────────────────────────
|
|
|
|
func TestSendMessage_EveryoneRequiresPermission(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
res := sendAs(t, svc, 1, "@everyone stand up") // alice is a plain member
|
|
if res.MentionsEveryone {
|
|
t.Fatal("@everyone without MENTION_EVERYONE must not gain mention semantics")
|
|
}
|
|
if got := mentionCount(t, database, 2); got != 0 {
|
|
t.Errorf("bob mention_count = %d, want 0", got)
|
|
}
|
|
|
|
res = sendAs(t, svc, 4, "@everyone stand up") // mod holds the bit
|
|
if !res.MentionsEveryone {
|
|
t.Fatal("@everyone with MENTION_EVERYONE must be honored")
|
|
}
|
|
}
|
|
|
|
func TestSendMessage_EveryoneCountsEveryReaderButAuthor(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
sendAs(t, svc, 4, "@everyone meeting now")
|
|
for _, uid := range []int64{1, 2, 3} {
|
|
if got := mentionCount(t, database, uid); got != 1 {
|
|
t.Errorf("user %d mention_count = %d, want 1", uid, got)
|
|
}
|
|
}
|
|
if got := mentionCount(t, database, 4); got != 0 {
|
|
t.Errorf("author mention_count = %d, want 0", got)
|
|
}
|
|
}
|
|
|
|
func TestSendMessage_HereSkipsOfflineUsers(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
sendAs(t, svc, 4, "@here quick question")
|
|
if got := mentionCount(t, database, 2); got != 1 {
|
|
t.Errorf("online bob mention_count = %d, want 1", got)
|
|
}
|
|
if got := mentionCount(t, database, 3); got != 0 {
|
|
t.Errorf("offline carol mention_count = %d, want 0", got)
|
|
}
|
|
}
|
|
|
|
// TestSendMessage_HereSkipsInvisibleUsers locks the phase-6 half of the @here
|
|
// rule. users.status stores the status the user *chose*, so an invisible reader
|
|
// holds the literal "invisible" here — a bare == "offline" test would ping them,
|
|
// which is the one thing "appear offline" exists to prevent. The fan-out has to
|
|
// collapse through db.BroadcastStatus first, so @here agrees with what everyone
|
|
// else can see of that reader.
|
|
func TestSendMessage_HereSkipsInvisibleUsers(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
if err := database.UpdateUserStatus(context.Background(), 2, db.StatusInvisible); err != nil {
|
|
t.Fatalf("UpdateUserStatus(invisible): %v", err)
|
|
}
|
|
|
|
sendAs(t, svc, 4, "@here quick question")
|
|
if got := mentionCount(t, database, 2); got != 0 {
|
|
t.Errorf("invisible bob mention_count = %d, want 0", got)
|
|
}
|
|
// A plain @everyone still reaches them: only @here narrows on presence.
|
|
sendAs(t, svc, 4, "@everyone meeting now")
|
|
if got := mentionCount(t, database, 2); got != 1 {
|
|
t.Errorf("invisible bob @everyone mention_count = %d, want 1", got)
|
|
}
|
|
}
|
|
|
|
// TestSendMessage_HereSkipsDisconnectedIdleDndUsers locks OC-0223: @here must
|
|
// treat a reader with no live connection as offline even when their stored
|
|
// status is idle/dnd, matching the read path's "no live connection is
|
|
// offline, whatever the row says" rule (ws/serve_ready.go presentableMembers).
|
|
// MarkUserDisconnected only ever rewrites "online" -> "offline" — an idle/dnd
|
|
// choice survives the disconnect by design, so a bare
|
|
// db.BroadcastStatus(r.Status) == db.StatusOffline test can never catch a
|
|
// disconnected idle/dnd reader without also consulting live connection state.
|
|
func TestSendMessage_HereSkipsDisconnectedIdleDndUsers(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
// bob's last chosen status was "dnd" before disconnecting (mirrors what
|
|
// MarkUserDisconnected leaves behind for a non-"online" status).
|
|
if err := database.UpdateUserStatus(context.Background(), 2, db.StatusDND); err != nil {
|
|
t.Fatalf("UpdateUserStatus(dnd): %v", err)
|
|
}
|
|
// bob has no live connection.
|
|
svc.SetOnlineChecker(func(userID int64) bool { return userID != 2 })
|
|
|
|
sendAs(t, svc, 4, "@here quick question")
|
|
if got := mentionCount(t, database, 2); got != 0 {
|
|
t.Errorf("disconnected dnd bob mention_count = %d, want 0", got)
|
|
}
|
|
|
|
// A plain @everyone still reaches them: only @here narrows on presence.
|
|
sendAs(t, svc, 4, "@everyone meeting now")
|
|
if got := mentionCount(t, database, 2); got != 1 {
|
|
t.Errorf("disconnected dnd bob @everyone mention_count = %d, want 1", got)
|
|
}
|
|
}
|
|
|
|
// TestSendMessage_EveryoneSkipsUsersWithoutRead locks that the @everyone
|
|
// fan-out honors per-channel denies, not just the base role mask.
|
|
func TestSendMessage_EveryoneSkipsUsersWithoutRead(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
seedChannelOverride(t, database, permissions.MemberRoleID, 10, 0, permissions.ReadMessages)
|
|
|
|
sendAs(t, svc, 4, "@everyone private notice")
|
|
for _, uid := range []int64{1, 2, 3} {
|
|
if got := mentionCount(t, database, uid); got != 0 {
|
|
t.Errorf("denied user %d mention_count = %d, want 0", uid, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestSendMessage_EveryoneHonorsUserOverrides locks the per-user layer in the
|
|
// @everyone fan-out: it is the last layer of the resolution order, so it must
|
|
// both DROP a reader the role admitted and ADD one the role excluded.
|
|
func TestSendMessage_EveryoneHonorsUserOverrides(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
// The role cannot read the channel at all...
|
|
seedChannelOverride(t, database, permissions.MemberRoleID, 10, 0, permissions.ReadMessages)
|
|
// ...but bob is individually granted READ back.
|
|
if err := database.UpsertChannelUserOverride(context.Background(), 10, 2, permissions.ReadMessages, 0); err != nil {
|
|
t.Fatalf("UpsertChannelUserOverride bob: %v", err)
|
|
}
|
|
|
|
sendAs(t, svc, 4, "@everyone notice")
|
|
if got := mentionCount(t, database, 2); got != 1 {
|
|
t.Errorf("bob (user allow) mention_count = %d, want 1", got)
|
|
}
|
|
if got := mentionCount(t, database, 3); got != 0 {
|
|
t.Errorf("carol (no override) mention_count = %d, want 0", got)
|
|
}
|
|
}
|
|
|
|
func TestSendMessage_EveryoneSkipsUserDenied(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
// carol alone is denied READ on a channel her role can read.
|
|
if err := database.UpsertChannelUserOverride(context.Background(), 10, 3, 0, permissions.ReadMessages); err != nil {
|
|
t.Fatalf("UpsertChannelUserOverride carol: %v", err)
|
|
}
|
|
|
|
sendAs(t, svc, 4, "@everyone notice")
|
|
if got := mentionCount(t, database, 2); got != 1 {
|
|
t.Errorf("bob mention_count = %d, want 1", got)
|
|
}
|
|
if got := mentionCount(t, database, 3); got != 0 {
|
|
t.Errorf("carol (user deny) mention_count = %d, want 0", got)
|
|
}
|
|
}
|
|
|
|
// A direct @mention of a user the channel's per-user deny excludes must not
|
|
// raise their badge either — mentionReaders is the single gate behind both.
|
|
func TestSendMessage_DirectMentionSkipsUserDenied(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
if err := database.UpsertChannelUserOverride(context.Background(), 10, 2, 0, permissions.ReadMessages); err != nil {
|
|
t.Fatalf("UpsertChannelUserOverride bob: %v", err)
|
|
}
|
|
|
|
sendAs(t, svc, 1, "@bob ping")
|
|
if got := mentionCount(t, database, 2); got != 0 {
|
|
t.Errorf("user-denied bob mention_count = %d, want 0", got)
|
|
}
|
|
}
|
|
|
|
// A single message mentioning several users at once must resolve each one
|
|
// independently against the reader set: readers get counted, a non-reader
|
|
// (denied READ_MESSAGES via a per-user override) does not — the case the
|
|
// mentioned-uid x reader lookup has to get right regardless of how it is
|
|
// implemented internally (loop or map).
|
|
func TestSendMessage_MultipleDirectMentionsResolveIndependently(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
if err := database.UpsertChannelUserOverride(context.Background(), 10, 3, 0, permissions.ReadMessages); err != nil {
|
|
t.Fatalf("UpsertChannelUserOverride carol: %v", err)
|
|
}
|
|
|
|
sendAs(t, svc, 1, "@bob @carol @mod hi")
|
|
|
|
if got := mentionCount(t, database, 2); got != 1 {
|
|
t.Errorf("bob (reader) mention_count = %d, want 1", got)
|
|
}
|
|
if got := mentionCount(t, database, 3); got != 0 {
|
|
t.Errorf("carol (denied read) mention_count = %d, want 0", got)
|
|
}
|
|
if got := mentionCount(t, database, 4); got != 1 {
|
|
t.Errorf("mod (reader) mention_count = %d, want 1", got)
|
|
}
|
|
}
|
|
|
|
// ─── mention counts ──────────────────────────────────────────────────────────
|
|
|
|
func TestSendMessage_DirectMentionIncrementsCount(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
sendAs(t, svc, 1, "@bob ping")
|
|
sendAs(t, svc, 1, "@bob again")
|
|
if got := mentionCount(t, database, 2); got != 2 {
|
|
t.Errorf("bob mention_count = %d, want 2", got)
|
|
}
|
|
if got := mentionCount(t, database, 3); got != 0 {
|
|
t.Errorf("uninvolved carol mention_count = %d, want 0", got)
|
|
}
|
|
}
|
|
|
|
// TestSendMessage_MentionCountsWrittenInBackground exercises the default async
|
|
// path: the fixture normally forces the inline seam, so here we restore the
|
|
// real `go fn()` dispatcher and confirm the count still lands shortly after
|
|
// SendMessage returns.
|
|
func TestSendMessage_MentionCountsWrittenInBackground(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
// Undo the fixture's inline seam so bg is the production `go fn()` again.
|
|
svc.bg = func(fn func()) { go fn() }
|
|
|
|
sendAs(t, svc, 1, "@Bob ping")
|
|
|
|
// The write is on a goroutine; poll briefly rather than assuming timing.
|
|
const deadline = 2 * time.Second
|
|
var got int
|
|
for waited := time.Duration(0); waited < deadline; waited += 10 * time.Millisecond {
|
|
if got = mentionCount(t, database, 2); got == 1 {
|
|
return
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
t.Fatalf("bob mention_count = %d after %s, want 1 (background write never landed)", got, deadline)
|
|
}
|
|
|
|
func TestSendMessage_SelfMentionDoesNotCount(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
sendAs(t, svc, 2, "note to self @bob")
|
|
if got := mentionCount(t, database, 2); got != 0 {
|
|
t.Errorf("self-mention mention_count = %d, want 0", got)
|
|
}
|
|
}
|
|
|
|
func TestSendMessage_BlockedAuthorDoesNotRaiseBadge(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
seedBlock(t, database, 2, 1) // bob blocked alice
|
|
|
|
sendAs(t, svc, 1, "@bob @carol hello")
|
|
if got := mentionCount(t, database, 2); got != 0 {
|
|
t.Errorf("blocker mention_count = %d, want 0", got)
|
|
}
|
|
if got := mentionCount(t, database, 3); got != 1 {
|
|
t.Errorf("carol mention_count = %d, want 1", got)
|
|
}
|
|
}
|
|
|
|
func TestChannelFocus_ClearsMentionCount(t *testing.T) {
|
|
msgSvc, chanSvc, database := newMentionFixture(t)
|
|
|
|
sendAs(t, msgSvc, 1, "@bob look")
|
|
if got := mentionCount(t, database, 2); got != 1 {
|
|
t.Fatalf("setup: bob mention_count = %d, want 1", got)
|
|
}
|
|
|
|
if _, err := chanSvc.HandleChannelFocus(context.Background(), 2, 10); err != nil {
|
|
t.Fatalf("HandleChannelFocus: %v", err)
|
|
}
|
|
if got := mentionCount(t, database, 2); got != 0 {
|
|
t.Errorf("after focus mention_count = %d, want 0", got)
|
|
}
|
|
}
|
|
|
|
// ─── edits ───────────────────────────────────────────────────────────────────
|
|
|
|
func TestEditMessage_ReplacesMentionsWithoutRecounting(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
res := sendAs(t, svc, 1, "@bob first")
|
|
if got := mentionCount(t, database, 2); got != 1 {
|
|
t.Fatalf("setup: bob mention_count = %d, want 1", got)
|
|
}
|
|
|
|
edited, err := svc.EditMessage(context.Background(), 1, res.MessageID, "@carol instead")
|
|
if err != nil {
|
|
t.Fatalf("EditMessage: %v", err)
|
|
}
|
|
if len(edited.Mentions) != 1 || edited.Mentions[0] != 3 {
|
|
t.Fatalf("edited mentions = %v, want [3]", edited.Mentions)
|
|
}
|
|
|
|
stored, err := database.GetMentionsByMessageIDs(context.Background(), []int64{res.MessageID})
|
|
if err != nil {
|
|
t.Fatalf("GetMentionsByMessageIDs: %v", err)
|
|
}
|
|
if len(stored[res.MessageID]) != 1 || stored[res.MessageID][0] != 3 {
|
|
t.Errorf("stored mentions = %v, want [3]", stored[res.MessageID])
|
|
}
|
|
|
|
// Edits never advance badges — bob keeps his one, carol gains none.
|
|
if got := mentionCount(t, database, 2); got != 1 {
|
|
t.Errorf("bob mention_count = %d, want 1", got)
|
|
}
|
|
if got := mentionCount(t, database, 3); got != 0 {
|
|
t.Errorf("carol mention_count = %d, want 0 (edits never increment)", got)
|
|
}
|
|
}
|
|
|
|
func TestEditMessage_EveryoneGateApplies(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
res := sendAs(t, svc, 1, "plain text")
|
|
if _, err := svc.EditMessage(context.Background(), 1, res.MessageID, "@everyone actually"); err != nil {
|
|
t.Fatalf("EditMessage: %v", err)
|
|
}
|
|
msg, err := database.GetMessage(context.Background(), res.MessageID)
|
|
if err != nil || msg == nil {
|
|
t.Fatalf("GetMessage: %v", err)
|
|
}
|
|
if msg.MentionsEveryone {
|
|
t.Error("edit by a member must not set mentions_everyone")
|
|
}
|
|
}
|
|
|
|
// ─── read-state fan-out ──────────────────────────────────────────────────────
|
|
|
|
func TestGetChannelUnreadCounts_CarriesMentionCount(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
|
|
sendAs(t, svc, 1, "@bob check the ready payload")
|
|
counts, err := database.GetChannelUnreadCounts(context.Background(), 2)
|
|
if err != nil {
|
|
t.Fatalf("GetChannelUnreadCounts: %v", err)
|
|
}
|
|
got, ok := counts[10]
|
|
if !ok {
|
|
t.Fatal("channel 10 missing from unread counts")
|
|
}
|
|
if got.MentionCount != 1 {
|
|
t.Errorf("mention_count = %d, want 1", got.MentionCount)
|
|
}
|
|
if got.UnreadCount != 1 {
|
|
t.Errorf("unread_count = %d, want 1", got.UnreadCount)
|
|
}
|
|
}
|
|
|
|
// TestSendMessage_DMMentionsResolve locks that DMs resolve usernames but never
|
|
// gain @everyone semantics — there is no permission surface behind a DM.
|
|
func TestSendMessage_DMMentionsResolve(t *testing.T) {
|
|
svc, _, database := newMentionFixture(t)
|
|
seedChannel(t, database, &db.Channel{ID: 50, Name: "dm-1-2", Type: "dm"})
|
|
seedDMParticipant(t, database, 50, 1)
|
|
seedDMParticipant(t, database, 50, 2)
|
|
|
|
res, err := svc.SendMessage(context.Background(), SendMessageParams{
|
|
ChannelID: 50, UserID: 1, Username: "alice", Content: "@bob @everyone hi",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("SendMessage: %v", err)
|
|
}
|
|
if len(res.Mentions) != 1 || res.Mentions[0] != 2 {
|
|
t.Errorf("mentions = %v, want [2]", res.Mentions)
|
|
}
|
|
if res.MentionsEveryone {
|
|
t.Error("DM must not honor @everyone")
|
|
}
|
|
}
|