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>
396 lines
16 KiB
Go
396 lines
16 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/owncord/server/db"
|
|
"github.com/owncord/server/permissions"
|
|
)
|
|
|
|
// Phase 6 profile fields. The rules that matter here are the ones a handler
|
|
// could plausibly skip: sanitization, the length bounds, "omitted means
|
|
// unchanged", and "empty means cleared". They live in the service precisely so
|
|
// every transport gets them, so they are tested against the service.
|
|
|
|
func newUserSvc(t *testing.T) (*UserService, *db.DB) {
|
|
t.Helper()
|
|
database := newTestDB(t)
|
|
seedUser(t, database, &db.User{ID: 1, Username: "ada", PasswordHash: "h"})
|
|
return NewUserService(database), database
|
|
}
|
|
|
|
func TestUpdateProfile_SetsAndClearsDisplayNameAndAbout(t *testing.T) {
|
|
svc, _ := newUserSvc(t)
|
|
ctx := context.Background()
|
|
|
|
name, about := "Ada L.", "counts on it"
|
|
u, err := svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada", DisplayName: &name, About: &about})
|
|
if err != nil {
|
|
t.Fatalf("UpdateProfile: %v", err)
|
|
}
|
|
if u.DisplayName == nil || *u.DisplayName != name {
|
|
t.Fatalf("display_name = %v, want %q", u.DisplayName, name)
|
|
}
|
|
if u.About == nil || *u.About != about {
|
|
t.Fatalf("about = %v, want %q", u.About, about)
|
|
}
|
|
|
|
// A patch that mentions neither field must leave both standing — the
|
|
// update writes every column, so this is the merge doing its job.
|
|
u, err = svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada"})
|
|
if err != nil {
|
|
t.Fatalf("UpdateProfile (username only): %v", err)
|
|
}
|
|
if u.DisplayName == nil || u.About == nil {
|
|
t.Fatalf("a username-only patch cleared other fields: %v / %v", u.DisplayName, u.About)
|
|
}
|
|
|
|
// An explicit empty string clears.
|
|
empty := ""
|
|
u, err = svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada", DisplayName: &empty, About: &empty})
|
|
if err != nil {
|
|
t.Fatalf("UpdateProfile (clear): %v", err)
|
|
}
|
|
if u.DisplayName != nil || u.About != nil {
|
|
t.Fatalf("expected cleared, got %v / %v", u.DisplayName, u.About)
|
|
}
|
|
}
|
|
|
|
// raceDetectingStore wraps a real Store and records whether two GetUserByID
|
|
// calls were ever in flight at once, to prove UpdateProfile's read-merge-
|
|
// write serializes per user rather than merely happening to avoid a race
|
|
// under a particular timing.
|
|
type raceDetectingStore struct {
|
|
Store
|
|
active int32
|
|
overlap int32
|
|
}
|
|
|
|
func (r *raceDetectingStore) GetUserByID(ctx context.Context, id int64) (*db.User, error) {
|
|
if atomic.AddInt32(&r.active, 1) > 1 {
|
|
atomic.AddInt32(&r.overlap, 1)
|
|
}
|
|
time.Sleep(5 * time.Millisecond) // widen the window a real race would need
|
|
defer atomic.AddInt32(&r.active, -1)
|
|
return r.Store.GetUserByID(ctx, id)
|
|
}
|
|
|
|
func TestUpdateProfile_ConcurrentUpdatesSerializePerUser(t *testing.T) {
|
|
database := newTestDB(t)
|
|
seedUser(t, database, &db.User{ID: 1, Username: "ada", PasswordHash: "h"})
|
|
rs := &raceDetectingStore{Store: database}
|
|
svc := NewUserService(rs)
|
|
ctx := context.Background()
|
|
|
|
// Simulates PATCH /users/me (sets display_name) racing
|
|
// POST /users/me/avatar (sets about, standing in for the avatar column;
|
|
// both calls pass the unrelated field's current value the way the real
|
|
// handlers do). Without serialization, whichever call's read lands
|
|
// between the other's read and write would revert that other call's
|
|
// change when it writes its own stale merge.
|
|
var wg sync.WaitGroup
|
|
wg.Add(2)
|
|
go func() {
|
|
defer wg.Done()
|
|
name := "Ada L."
|
|
if _, err := svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada", DisplayName: &name}); err != nil {
|
|
t.Errorf("UpdateProfile (display_name): %v", err)
|
|
}
|
|
}()
|
|
go func() {
|
|
defer wg.Done()
|
|
about := "counts on it"
|
|
if _, err := svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada", About: &about}); err != nil {
|
|
t.Errorf("UpdateProfile (about): %v", err)
|
|
}
|
|
}()
|
|
wg.Wait()
|
|
|
|
if got := atomic.LoadInt32(&rs.overlap); got != 0 {
|
|
t.Errorf("UpdateProfile's read-merge-write overlapped %d times, want 0 (must be serialized per user)", got)
|
|
}
|
|
|
|
u, err := database.GetUserByID(ctx, 1)
|
|
if err != nil {
|
|
t.Fatalf("GetUserByID: %v", err)
|
|
}
|
|
if u.DisplayName == nil || *u.DisplayName != "Ada L." {
|
|
t.Errorf("display_name = %v, want %q — must not be reverted by a concurrent update", u.DisplayName, "Ada L.")
|
|
}
|
|
if u.About == nil || *u.About != "counts on it" {
|
|
t.Errorf("about = %v, want %q — must not be reverted by a concurrent update", u.About, "counts on it")
|
|
}
|
|
}
|
|
|
|
// OC-0102: an avatar-only patch must not carry a username at all, so a stale
|
|
// pre-lock snapshot (handleUploadAvatar captures user.Username before the
|
|
// multipart parse / image decode / disk write, well before this function's
|
|
// per-user lock) can never overwrite a rename that commits in the meantime.
|
|
// UpdateProfile's read-merge-write already treats DisplayName/About this
|
|
// way (nil-vs-non-nil pointer); Username needs the same "unspecified means
|
|
// leave it alone" contract via its own zero value, since it is a plain
|
|
// string rather than a pointer.
|
|
func TestUpdateProfile_AvatarOnlyPatchDoesNotOverwriteUsername(t *testing.T) {
|
|
svc, database := newUserSvc(t)
|
|
ctx := context.Background()
|
|
|
|
// Models a concurrent PATCH /users/me rename that lands and commits
|
|
// first.
|
|
if _, err := svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "bob"}); err != nil {
|
|
t.Fatalf("rename UpdateProfile: %v", err)
|
|
}
|
|
|
|
// An avatar-only caller supplies no username intent at all — Username is
|
|
// left at its zero value, the way handleUploadAvatar's ProfilePatch must
|
|
// after the fix (it no longer fills Username from its stale snapshot).
|
|
avatarURL := "/api/v1/files/abc"
|
|
u, err := svc.UpdateProfile(ctx, 1, ProfilePatch{Avatar: &avatarURL})
|
|
if err != nil {
|
|
t.Fatalf("avatar-only UpdateProfile: %v", err)
|
|
}
|
|
if u.Username != "bob" {
|
|
t.Fatalf("username = %q, want %q — an avatar-only patch must not revert a concurrent rename", u.Username, "bob")
|
|
}
|
|
if u.Avatar == nil || *u.Avatar != avatarURL {
|
|
t.Fatalf("avatar = %v, want %q — the avatar itself must still be applied", u.Avatar, avatarURL)
|
|
}
|
|
|
|
stored, err := database.GetUserByID(ctx, 1)
|
|
if err != nil {
|
|
t.Fatalf("GetUserByID: %v", err)
|
|
}
|
|
if stored.Username != "bob" {
|
|
t.Fatalf("stored username = %q, want %q", stored.Username, "bob")
|
|
}
|
|
}
|
|
|
|
func TestUpdateProfile_SanitizesAndTrims(t *testing.T) {
|
|
svc, _ := newUserSvc(t)
|
|
name := " <b>Ada</b> "
|
|
about := "<script>alert(1)</script>hello"
|
|
u, err := svc.UpdateProfile(context.Background(), 1, ProfilePatch{
|
|
Username: "ada", DisplayName: &name, About: &about,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("UpdateProfile: %v", err)
|
|
}
|
|
if u.DisplayName == nil || *u.DisplayName != "Ada" {
|
|
t.Errorf("display_name = %v, want %q", u.DisplayName, "Ada")
|
|
}
|
|
if u.About == nil || strings.Contains(*u.About, "<") {
|
|
t.Errorf("about = %v, want markup stripped", u.About)
|
|
}
|
|
}
|
|
|
|
func TestUpdateProfile_RejectsOverlongFields(t *testing.T) {
|
|
svc, _ := newUserSvc(t)
|
|
ctx := context.Background()
|
|
|
|
tooLongName := strings.Repeat("a", MaxDisplayNameLen+1)
|
|
if _, err := svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada", DisplayName: &tooLongName}); !errors.Is(err, ErrBadRequest) {
|
|
t.Errorf("overlong display_name err = %v, want ErrBadRequest", err)
|
|
}
|
|
tooLongAbout := strings.Repeat("b", MaxAboutLen+1)
|
|
if _, err := svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada", About: &tooLongAbout}); !errors.Is(err, ErrBadRequest) {
|
|
t.Errorf("overlong about err = %v, want ErrBadRequest", err)
|
|
}
|
|
|
|
// Exactly at the bound is accepted, and the bound counts runes rather than
|
|
// bytes — otherwise a name in a non-Latin script would be a third as long.
|
|
atBound := strings.Repeat("é", MaxDisplayNameLen)
|
|
if _, err := svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada", DisplayName: &atBound}); err != nil {
|
|
t.Errorf("display_name at bound rejected: %v", err)
|
|
}
|
|
}
|
|
|
|
// OC-0192: UpdateProfile is the one function every transport (the REST
|
|
// handler, and any future non-REST caller — see ProfilePatch's doc comment)
|
|
// goes through, so the raw-length bound belongs here, not only in the
|
|
// handler. cleanText (sanitizeToFixpoint) is quadratic in input length, and
|
|
// nothing bounds DisplayName/About before line 140/143 run it — the rune-
|
|
// count checks there run cleanText's full (expensive) output before ever
|
|
// looking at how long it is. A caller that hands UpdateProfile an
|
|
// adversarial nested-entity payload must be rejected on a cheap byte-length
|
|
// check, not after the fixpoint sanitizer has already paid its cost on it.
|
|
func TestUpdateProfile_OversizedDisplayNameAndAboutRejectedBeforeSanitizing(t *testing.T) {
|
|
svc, _ := newUserSvc(t)
|
|
ctx := context.Background()
|
|
|
|
// Adversarial nested-entity payload (16 KB) — see sanitizeToFixpoint's
|
|
// doc comment (message.go) for why this shape is quadratic to sanitize.
|
|
huge := "&" + strings.Repeat("amp;", 4000) + "lt;"
|
|
|
|
start := time.Now()
|
|
_, err := svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada", DisplayName: &huge})
|
|
elapsed := time.Since(start)
|
|
if !errors.Is(err, ErrBadRequest) {
|
|
t.Errorf("oversized display_name err = %v, want ErrBadRequest", err)
|
|
}
|
|
// A guard that runs before sanitizing rejects in well under a
|
|
// millisecond; the pre-fix code spends well over 150ms in
|
|
// sanitizeToFixpoint on this payload before the rune-count check ever
|
|
// runs. 150ms gives generous margin over noise while staying far below
|
|
// the unguarded cost.
|
|
if elapsed > 150*time.Millisecond {
|
|
t.Errorf("oversized display_name took %v, want well under 150ms (raw field must be bounded before sanitizing)", elapsed)
|
|
}
|
|
|
|
start = time.Now()
|
|
_, err = svc.UpdateProfile(ctx, 1, ProfilePatch{Username: "ada", About: &huge})
|
|
elapsed = time.Since(start)
|
|
if !errors.Is(err, ErrBadRequest) {
|
|
t.Errorf("oversized about err = %v, want ErrBadRequest", err)
|
|
}
|
|
if elapsed > 150*time.Millisecond {
|
|
t.Errorf("oversized about took %v, want well under 150ms (raw field must be bounded before sanitizing)", elapsed)
|
|
}
|
|
}
|
|
|
|
func TestSetCustomStatus_RoundTripClearAndBound(t *testing.T) {
|
|
svc, database := newUserSvc(t)
|
|
ctx := context.Background()
|
|
|
|
if err := svc.SetCustomStatus(ctx, 1, " <i>debugging</i> "); err != nil {
|
|
t.Fatalf("SetCustomStatus: %v", err)
|
|
}
|
|
u, _ := database.GetUserByID(ctx, 1)
|
|
if u.CustomStatus == nil || *u.CustomStatus != "debugging" {
|
|
t.Fatalf("custom_status = %v, want sanitized+trimmed %q", u.CustomStatus, "debugging")
|
|
}
|
|
|
|
if err := svc.SetCustomStatus(ctx, 1, " "); err != nil {
|
|
t.Fatalf("SetCustomStatus (blank): %v", err)
|
|
}
|
|
u, _ = database.GetUserByID(ctx, 1)
|
|
if u.CustomStatus != nil {
|
|
t.Fatalf("whitespace-only text should clear, got %q", *u.CustomStatus)
|
|
}
|
|
|
|
if err := svc.SetCustomStatus(ctx, 1, strings.Repeat("x", MaxCustomStatusLen+1)); !errors.Is(err, ErrBadRequest) {
|
|
t.Errorf("overlong custom_status err = %v, want ErrBadRequest", err)
|
|
}
|
|
}
|
|
|
|
func TestClearCustomStatus(t *testing.T) {
|
|
svc, database := newUserSvc(t)
|
|
ctx := context.Background()
|
|
if err := svc.SetCustomStatus(ctx, 1, "afk"); err != nil {
|
|
t.Fatalf("SetCustomStatus: %v", err)
|
|
}
|
|
if err := svc.ClearCustomStatus(ctx, 1); err != nil {
|
|
t.Fatalf("ClearCustomStatus: %v", err)
|
|
}
|
|
u, _ := database.GetUserByID(ctx, 1)
|
|
if u.CustomStatus != nil {
|
|
t.Fatalf("custom_status = %q, want nil", *u.CustomStatus)
|
|
}
|
|
}
|
|
|
|
func TestAvatarFileURL(t *testing.T) {
|
|
if got := AvatarFileURL("abc"); got != "/api/v1/files/abc" {
|
|
t.Errorf("AvatarFileURL = %q", got)
|
|
}
|
|
}
|
|
|
|
func TestHandlePresenceUpdate_AcceptsInvisibleAndCarriesCustomStatus(t *testing.T) {
|
|
database := newTestDB(t)
|
|
seedUser(t, database, &db.User{ID: 1, Username: "ada", PasswordHash: "h"})
|
|
svc := NewChannelService(database, NewPermissionService(database, permissions.NewChecker(database)))
|
|
ctx := context.Background()
|
|
|
|
text := " <b>away</b> "
|
|
got, err := svc.HandlePresenceUpdate(ctx, 1, db.StatusInvisible, &text, nil)
|
|
if err != nil {
|
|
t.Fatalf("HandlePresenceUpdate: %v", err)
|
|
}
|
|
if got == nil || *got != "away" {
|
|
t.Fatalf("returned custom status = %v, want sanitized %q", got, "away")
|
|
}
|
|
u, _ := database.GetUserByID(ctx, 1)
|
|
// Stored as chosen — the invisible -> offline collapse is a broadcast-time
|
|
// concern, and storing it collapsed would make the next connect unable to
|
|
// tell "appear offline" from "not connected".
|
|
if u.Status != db.StatusInvisible {
|
|
t.Fatalf("stored status = %q, want invisible", u.Status)
|
|
}
|
|
|
|
// A later status flip that carries no custom_status field must leave the
|
|
// text alone AND still put it on the wire, or the auto-idle timer would
|
|
// blank everyone else's copy several times an hour.
|
|
got, err = svc.HandlePresenceUpdate(ctx, 1, db.StatusIdle, nil, nil)
|
|
if err != nil {
|
|
t.Fatalf("HandlePresenceUpdate (bare): %v", err)
|
|
}
|
|
if got == nil || *got != "away" {
|
|
t.Fatalf("bare status flip returned %v, want the stored %q", got, "away")
|
|
}
|
|
u, _ = database.GetUserByID(ctx, 1)
|
|
if u.CustomStatus == nil || *u.CustomStatus != "away" {
|
|
t.Fatalf("bare status flip changed the stored text: %v", u.CustomStatus)
|
|
}
|
|
}
|
|
|
|
// OC-0195: same defect as OC-0192 (TestUpdateProfile_OversizedDisplayNameAndAboutRejectedBeforeSanitizing)
|
|
// but reached over presence_update instead of PATCH /users/me. HandlePresenceUpdate
|
|
// applied MaxCustomStatusLen to cleanText's *output*, so an adversarial
|
|
// nested-entity payload paid the full quadratic sanitizeToFixpoint cost before
|
|
// ever being measured. The WS read limit (config.MaxMessageBytes, 1 MiB) admits
|
|
// a payload here far larger than PATCH /users/me's body ever could, and this
|
|
// runs on the connection's own readPump goroutine.
|
|
func TestHandlePresenceUpdate_OversizedCustomStatusRejectedBeforeSanitizing(t *testing.T) {
|
|
database := newTestDB(t)
|
|
seedUser(t, database, &db.User{ID: 1, Username: "ada", PasswordHash: "h"})
|
|
svc := NewChannelService(database, NewPermissionService(database, permissions.NewChecker(database)))
|
|
ctx := context.Background()
|
|
|
|
// Adversarial nested-entity payload (16 KB) — see sanitizeToFixpoint's
|
|
// doc comment (message.go) for why this shape is quadratic to sanitize.
|
|
huge := "&" + strings.Repeat("amp;", 4000) + "lt;"
|
|
|
|
start := time.Now()
|
|
_, err := svc.HandlePresenceUpdate(ctx, 1, db.StatusOnline, &huge, nil)
|
|
elapsed := time.Since(start)
|
|
if !errors.Is(err, ErrBadRequest) {
|
|
t.Errorf("oversized custom_status err = %v, want ErrBadRequest", err)
|
|
}
|
|
// A guard that runs before sanitizing rejects in well under a
|
|
// millisecond; the pre-fix code spends well over 150ms in
|
|
// sanitizeToFixpoint on this payload before the rune-count check ever
|
|
// runs. 150ms gives generous margin over noise while staying far below
|
|
// the unguarded cost.
|
|
if elapsed > 150*time.Millisecond {
|
|
t.Errorf("oversized custom_status took %v, want well under 150ms (raw field must be bounded before sanitizing)", elapsed)
|
|
}
|
|
// The rejected call must not have committed the status either.
|
|
u, _ := database.GetUserByID(ctx, 1)
|
|
if u.Status == db.StatusOnline {
|
|
t.Error("a rejected presence_update must not commit the status")
|
|
}
|
|
}
|
|
|
|
func TestHandlePresenceUpdate_RejectsUnknownStatusAndOverlongText(t *testing.T) {
|
|
database := newTestDB(t)
|
|
seedUser(t, database, &db.User{ID: 1, Username: "ada", PasswordHash: "h"})
|
|
svc := NewChannelService(database, NewPermissionService(database, permissions.NewChecker(database)))
|
|
ctx := context.Background()
|
|
|
|
if _, err := svc.HandlePresenceUpdate(ctx, 1, "afk", nil, nil); !errors.Is(err, ErrBadRequest) {
|
|
t.Errorf("unknown status err = %v, want ErrBadRequest", err)
|
|
}
|
|
long := strings.Repeat("x", MaxCustomStatusLen+1)
|
|
if _, err := svc.HandlePresenceUpdate(ctx, 1, db.StatusOnline, &long, nil); !errors.Is(err, ErrBadRequest) {
|
|
t.Errorf("overlong custom_status err = %v, want ErrBadRequest", err)
|
|
}
|
|
// The rejected call must not have committed the status either.
|
|
u, _ := database.GetUserByID(ctx, 1)
|
|
if u.Status == db.StatusOnline {
|
|
t.Error("a rejected presence_update must not commit the status")
|
|
}
|
|
}
|