mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* fix(client): 1 defect(s) (OC-0201)
* fix(service): 1 defect(s) (OC-0202)
HandleTyping built the per-user-per-channel rate-limit key before resolving the channel or checking read permission, so forged channel ids could pin unbounded dead entries in the shared process-wide RateLimiter.
* fix(client): 2 defect(s) (OC-0203, OC-0224)
* fix(server): 1 defect(s) (OC-0204)
* fix(ws): 2 defect(s) (OC-0205, OC-0211)
* fix(admin): 2 defect(s) (OC-0209, OC-0212)
* fix(client): 1 defect(s) (OC-0210)
* fix(db): 1 defect(s) (OC-0213)
* fix(ws): 1 defect(s) (OC-0214)
Route handler-driven PresenceEvent through BroadcastToAll instead of BroadcastToAllLow so every source of a user's presence shares one ordered per-client FIFO.
* fix(admin): 1 defect(s) (OC-0215)
PATCH /users/{id} combining banned + role_id committed and broadcast the ban before authorizing the role change, so a refused role change returned an error while leaving the target banned. Authorize the role change up front via the new ModerationService.AuthorizeRoleChange.
* fix(db): 1 defect(s) (OC-0216)
LinkAttachmentsToMessage no longer claims an attachment that is a user's live avatar (users.avatar points at it). Once message_id is set, handleServeFile's avatar branch (gated on ChannelID == nil) is unreachable and the file falls under the message's channel ACL / soft-delete state, permanently disagreeing with users.avatar about who may read it.
* fix(emoji): 1 defect(s) (OC-0217)
* fix(client): 1 defect(s) (OC-0218)
The data-copy phase of an HTTP proxy tunnel was unbounded. Steps 1-2 of
handle_connection (header read, TCP connect, TLS handshake) each run under
a 10s guard, but step 3 called io::copy_bidirectional with no deadline. A
remote that completes the TLS handshake and then neither responds nor
closes parks the spawned connection task, the loopback socket and the
remote TLS session indefinitely: copy_bidirectional only resolves once
BOTH directions finish, so closing the local side alone does not free it.
Wrap the copy in copy_with_deadline, a generic helper bounded by
DATA_PHASE_TIMEOUT (600s). The bound is deliberately far looser than the
10s setup guards because this phase carries the REST body, including
attachment and avatar uploads, so it must reclaim only genuinely stuck
connections rather than merely slow ones. The helper is generic over the
stream types so it can be exercised without a live TLS connection.
Regression test drives two in-memory duplex pairs whose far ends stay
alive, so neither half ever observes EOF and raw copy_bidirectional would
block forever; the test asserts the call resolves on its own deadline with
ErrorKind::TimedOut.
Claude-Session: https://claude.ai/code/session_01ENMDTh8gDLiHCaRFdMYRiL
* fix(ws): 1 defect(s) (OC-0219)
* fix(client): 1 defect(s) (OC-0221)
UpdateNotifier scheduled its deferred update check with a setTimeout whose
handle was never retained, so destroy() could not cancel it. A component torn
down inside the 3s window (page swap / logout) still fired performCheck() and
issued a network update check against the old server URL. Retain the timer
handle and clear it in destroy().
* fix(dm): 1 defect(s) (OC-0222)
* fix(client): 1 defect(s) (OC-0223)
* fix(voice): 1 defect(s) (OC-0225)
The Grant-Microphone retry's .finally hardcoded grantMicBtn.disabled = false, undoing updateFrozen()'s socket-down freeze when the WS socket dropped while the mic permission request was in flight. Delegate the state back to render().
* fix(admin): 1 defect(s) (OC-0226)
handleApplyUpdate broadcasts a 'restarting in 5s' notice before the on-disk
swap. Every failure path in the swap returned silently, leaving clients
counting down to a restart that never happened. Extract the swap into
applyStagedUpdate and send a corrective 'update_aborted' broadcast from a
deferred guard on every path that does not reach the respawn.
* fix(admin): 1 defect(s) (OC-0227)
PATCH /channels/{id} accepted a blank or whitespace-only name, leaving the
channel unidentifiable in clients. updateChannelRequest.validate() now
rejects it the way handleCreateChannel already did.
* fix(identity): 1 defect(s) (OC-0228)
* fix(admin): run deferred cleanup before the update restart exits
The fix batch left three golangci-lint findings and two prettier findings
that CI gates on.
applyStagedUpdate called os.Exit(0) in the same function that defers both
staged.Close() and the corrective "update_aborted" broadcast, so neither
ran (gocritic exitAfterDefer). Return a bool instead and let the caller
exit once those defers have run — on Windows, releasing the staged binary's
file handle is the reason the restart exists at all, so this is a real fix
rather than a lint appeasement. The exported test hook calls the function as
a statement, so the added result does not affect it.
Also modernize a bulk-insert loop to range-over-int, compare backup bytes
with bytes.Equal, and reflow two test files to prettier's output.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ENMDTh8gDLiHCaRFdMYRiL
* test(ws): pin the live presence path against the invisible custom-status leak
OC-0207 and OC-0211 are the same defect at two emitters: hub_broadcast.go's
BroadcastPresence (connect/reconnect) and event.go's presenceEvents (live
presence_update). The fix for OC-0211 closed both sites in one change, but
only the hub_broadcast side got a regression test.
This pins the event.go sibling: an invisible user's real custom status must
be blanked on the PresenceOthersEvent frame while the owner's own
PresenceSelfEvent still carries it. Without it, a later change could reopen
the live path while the committed test kept passing.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ENMDTh8gDLiHCaRFdMYRiL
* fix(ws): 1 defect(s) (OC-0206)
* test(ws): silence a contextcheck false positive in the reconnect race test
RefreshChannelVisibility takes no context by design — it is reached through
the admin HubBroadcaster interface, which carries none, so it builds its own
internally. contextcheck flags the call only because the test closure around
it holds a ctx for its override write, so there is nothing to propagate.
Suppress at the call site rather than widen a production interface (and its
mocks) to satisfy a lint in a test.
golangci-lint v2.11.3 (the version ci.yml pins) now reports 0 issues.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ENMDTh8gDLiHCaRFdMYRiL
---------
Co-authored-by: Claude <noreply@anthropic.com>
275 lines
11 KiB
Go
275 lines
11 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"github.com/owncord/server/db"
|
|
"github.com/owncord/server/permissions"
|
|
"github.com/owncord/server/telemetry"
|
|
)
|
|
|
|
// ModerationService handles user ban/unban operations.
|
|
type ModerationService struct {
|
|
st Store
|
|
perms *PermissionService
|
|
}
|
|
|
|
// NewModerationService creates a ModerationService.
|
|
func NewModerationService(st Store, perms *PermissionService) *ModerationService {
|
|
return &ModerationService{st: st, perms: perms}
|
|
}
|
|
|
|
// roleFor loads a principal's role through the permission cache. Every failure
|
|
// is Forbidden: an unresolvable role must never authorize a moderation action.
|
|
// The which argument names the principal in the error message ("actor" or
|
|
// "target").
|
|
func (s *ModerationService) roleFor(ctx context.Context, userID int64, which string) (*db.Role, error) {
|
|
if s.perms == nil {
|
|
// No permission service wired — fail closed rather than allow unchecked actions.
|
|
return nil, fmt.Errorf("%w: permission service unavailable", ErrForbidden)
|
|
}
|
|
role, err := s.perms.GetRoleForUser(ctx, userID)
|
|
if err != nil || role == nil {
|
|
return nil, fmt.Errorf("%w: failed to load %s role", ErrForbidden, which)
|
|
}
|
|
return role, nil
|
|
}
|
|
|
|
// requirePerm verifies the actor holds perm (or the Administrator bypass) and
|
|
// returns the actor's role for follow-up hierarchy checks. It deliberately
|
|
// takes no target: it runs before any target lookup so an actor without
|
|
// authority always sees Forbidden and never NotFound — these paths cannot be
|
|
// used to enumerate user ids.
|
|
func (s *ModerationService) requirePerm(ctx context.Context, actorID, perm int64) (*db.Role, error) {
|
|
actorRole, err := s.roleFor(ctx, actorID, "actor")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !permissions.HasServerPerm(actorRole.Permissions, perm) {
|
|
return nil, fmt.Errorf("%w: missing %s permission", ErrForbidden, permissions.Name(perm))
|
|
}
|
|
return actorRole, nil
|
|
}
|
|
|
|
// requireBanPermission verifies the actor holds BAN_MEMBERS. See requirePerm.
|
|
func (s *ModerationService) requireBanPermission(ctx context.Context, actorID int64) error {
|
|
_, err := s.requirePerm(ctx, actorID, permissions.BanMembers)
|
|
return err
|
|
}
|
|
|
|
// requireOutranks enforces the role hierarchy: the actor must strictly
|
|
// outrank the target so a user cannot moderate a peer or a higher-ranked user
|
|
// (e.g. the owner) — mirroring the position-based hierarchy used elsewhere.
|
|
// Runs after the permission and existence checks, so only callers that already
|
|
// hold authority reach it.
|
|
func (s *ModerationService) requireOutranks(ctx context.Context, actorID, targetID int64) error {
|
|
actorRole, err := s.roleFor(ctx, actorID, "actor")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return s.requireOutranksRole(ctx, actorRole, targetID)
|
|
}
|
|
|
|
// requireOutranksRole is requireOutranks with the actor's role already loaded.
|
|
func (s *ModerationService) requireOutranksRole(ctx context.Context, actorRole *db.Role, targetID int64) error {
|
|
targetRole, err := s.roleFor(ctx, targetID, "target")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if actorRole.Position <= targetRole.Position {
|
|
return fmt.Errorf("%w: cannot moderate a user of equal or higher rank", ErrForbidden)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// BanUser bans a target user. Validates the target exists and
|
|
// prevents self-banning.
|
|
func (s *ModerationService) BanUser(ctx context.Context, actorID, targetID int64, reason string, expires *time.Time) error {
|
|
ctx, span := telemetry.GlobalTracer("service/moderation").Start(ctx, "ModerationService.BanUser",
|
|
telemetry.Int64("actor_id", actorID),
|
|
telemetry.Int64("target_id", targetID),
|
|
)
|
|
start := time.Now()
|
|
defer func() {
|
|
telemetry.TimeSince(ctx, telemetry.NewAppMetrics().ServiceCallDurationSec, start,
|
|
telemetry.String("method", "BanUser"))
|
|
span.End()
|
|
}()
|
|
|
|
if targetID <= 0 {
|
|
return fmt.Errorf("%w: user_id must be positive", ErrBadRequest)
|
|
}
|
|
if actorID == targetID {
|
|
return fmt.Errorf("%w: cannot ban yourself", ErrBadRequest)
|
|
}
|
|
|
|
// Authorization before existence: an actor without ban authority learns
|
|
// nothing about which user ids exist.
|
|
if err := s.requireBanPermission(ctx, actorID); err != nil {
|
|
return err
|
|
}
|
|
target, err := s.st.GetUserByID(ctx, targetID)
|
|
if err != nil || target == nil {
|
|
return fmt.Errorf("%w: user not found", ErrNotFound)
|
|
}
|
|
if err := s.requireOutranks(ctx, actorID, targetID); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := s.st.BanUser(ctx, targetID, reason, expires); err != nil {
|
|
return fmt.Errorf("%w: failed to ban user: %v", ErrInternal, err)
|
|
}
|
|
|
|
// Audit rows must survive a request canceled after the ban committed.
|
|
db.WriteAudit(context.WithoutCancel(ctx), s.st, actorID, "user_ban", "user", targetID, reason)
|
|
|
|
slog.Info("user banned", "actor_id", actorID, "target_id", targetID, "reason", reason)
|
|
return nil
|
|
}
|
|
|
|
// AuthorizeRoleChange runs every ChangeUserRole precondition — MANAGE_ROLES,
|
|
// target existence, the actor-outranks-target rule, role existence, and the
|
|
// assign-below-own-rank rule — without mutating anything, and in the same
|
|
// authorization-before-existence order as every other check in this file (see
|
|
// BanUser): an actor without MANAGE_ROLES learns nothing about which user ids
|
|
// exist. It exists so a caller that also performs another mutation in the
|
|
// same request (the admin PATCH /users/{id} handler, which can ban and
|
|
// role-change in one call) can authorize the role change *before* committing
|
|
// the other mutation: checking only at ChangeUserRole time means a refused
|
|
// role change is discovered only after the ban already landed, leaving a
|
|
// "failed" request half-applied (OC-0215). It returns the validated actor
|
|
// role, target user, and target role so callers that go on to commit (like
|
|
// ChangeUserRole) don't need to re-fetch any of them.
|
|
func (s *ModerationService) AuthorizeRoleChange(ctx context.Context, actorID, targetID, newRoleID int64) (actorRole *db.Role, target *db.User, newRole *db.Role, err error) {
|
|
if targetID <= 0 {
|
|
return nil, nil, nil, fmt.Errorf("%w: user_id must be positive", ErrBadRequest)
|
|
}
|
|
if actorID == targetID {
|
|
return nil, nil, nil, fmt.Errorf("%w: cannot change your own role", ErrBadRequest)
|
|
}
|
|
|
|
// Authorization before existence — see BanUser.
|
|
actorRole, err = s.requirePerm(ctx, actorID, permissions.ManageRoles)
|
|
if err != nil {
|
|
return nil, nil, nil, err
|
|
}
|
|
target, err = s.st.GetUserByID(ctx, targetID)
|
|
if err != nil || target == nil {
|
|
return nil, nil, nil, fmt.Errorf("%w: user not found", ErrNotFound)
|
|
}
|
|
if err := s.requireOutranksRole(ctx, actorRole, targetID); err != nil {
|
|
return nil, nil, nil, err
|
|
}
|
|
|
|
newRole, err = s.st.GetRoleByID(ctx, newRoleID)
|
|
if err != nil || newRole == nil {
|
|
return nil, nil, nil, fmt.Errorf("%w: role not found", ErrBadRequest)
|
|
}
|
|
// Administrator bypasses permission bits, never the hierarchy: the owner
|
|
// role is above every admin, so only the owner can grant it.
|
|
if newRole.Position >= actorRole.Position {
|
|
return nil, nil, nil, fmt.Errorf("%w: cannot assign a role at or above your own rank", ErrForbidden)
|
|
}
|
|
return actorRole, target, newRole, nil
|
|
}
|
|
|
|
// ChangeUserRole assigns newRoleID to the target user. It enforces
|
|
// MANAGE_ROLES plus two hierarchy rules the admin panel previously had none
|
|
// of: the actor must strictly outrank the target, and may not hand out a role
|
|
// positioned at or above their own — otherwise any admin could promote anyone
|
|
// (including themselves via a second account) to Owner.
|
|
//
|
|
// It returns the role that was assigned so callers (the member_update
|
|
// broadcast and visibility refresh, in particular) can use it directly
|
|
// instead of re-reading it: a re-read is racing a possible concurrent role
|
|
// delete for no reason, since this call already loaded and validated the
|
|
// exact same row under the same request.
|
|
func (s *ModerationService) ChangeUserRole(ctx context.Context, actorID, targetID, newRoleID int64) (*db.Role, error) {
|
|
_, target, newRole, err := s.AuthorizeRoleChange(ctx, actorID, targetID, newRoleID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err := s.st.UpdateUserRole(ctx, targetID, newRoleID); err != nil {
|
|
return nil, fmt.Errorf("%w: failed to update role: %v", ErrInternal, err)
|
|
}
|
|
// Drop the target's cached role immediately: without this a demotion keeps
|
|
// granting the old bits (and the old rank) for up to permCacheTTL.
|
|
s.perms.InvalidateUser(targetID)
|
|
|
|
// Audit rows must survive a request canceled after the update committed.
|
|
db.WriteAudit(context.WithoutCancel(ctx), s.st, actorID, "role_change", "user", targetID,
|
|
fmt.Sprintf("changed %s role to %s", target.Username, newRole.Name))
|
|
|
|
slog.Info("role changed", "actor_id", actorID, "target_id", targetID, "new_role_id", newRoleID)
|
|
return newRole, nil
|
|
}
|
|
|
|
// ForceLogout revokes every session of the target user (the client's "Kick").
|
|
// Gated on KICK_MEMBERS plus the same hierarchy rule as ban, so a moderator
|
|
// cannot log out an admin or the owner.
|
|
func (s *ModerationService) ForceLogout(ctx context.Context, actorID, targetID int64) error {
|
|
if targetID <= 0 {
|
|
return fmt.Errorf("%w: user_id must be positive", ErrBadRequest)
|
|
}
|
|
if actorID == targetID {
|
|
return fmt.Errorf("%w: cannot force-logout yourself", ErrBadRequest)
|
|
}
|
|
|
|
// Authorization before existence — see BanUser.
|
|
actorRole, err := s.requirePerm(ctx, actorID, permissions.KickMembers)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
target, err := s.st.GetUserByID(ctx, targetID)
|
|
if err != nil || target == nil {
|
|
return fmt.Errorf("%w: user not found", ErrNotFound)
|
|
}
|
|
if err := s.requireOutranksRole(ctx, actorRole, targetID); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := s.st.ForceLogoutUser(ctx, targetID); err != nil {
|
|
return fmt.Errorf("%w: failed to log out user: %v", ErrInternal, err)
|
|
}
|
|
|
|
// Audit rows must survive a request canceled after the sessions were cut.
|
|
db.WriteAudit(context.WithoutCancel(ctx), s.st, actorID, "force_logout", "user", targetID,
|
|
"all sessions terminated")
|
|
|
|
slog.Info("force logout", "actor_id", actorID, "target_id", targetID)
|
|
return nil
|
|
}
|
|
|
|
// UnbanUser removes a ban on a target user.
|
|
func (s *ModerationService) UnbanUser(ctx context.Context, actorID, targetID int64) error {
|
|
if targetID <= 0 {
|
|
return fmt.Errorf("%w: user_id must be positive", ErrBadRequest)
|
|
}
|
|
|
|
// Authorization before existence — see BanUser.
|
|
if err := s.requireBanPermission(ctx, actorID); err != nil {
|
|
return err
|
|
}
|
|
target, err := s.st.GetUserByID(ctx, targetID)
|
|
if err != nil || target == nil {
|
|
return fmt.Errorf("%w: user not found", ErrNotFound)
|
|
}
|
|
if err := s.requireOutranks(ctx, actorID, targetID); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := s.st.UnbanUser(ctx, targetID); err != nil {
|
|
return fmt.Errorf("%w: failed to unban user: %v", ErrInternal, err)
|
|
}
|
|
|
|
// Audit rows must survive a request canceled after the unban committed.
|
|
db.WriteAudit(context.WithoutCancel(ctx), s.st, actorID, "user_unban", "user", targetID, "")
|
|
|
|
slog.Info("user unbanned", "actor_id", actorID, "target_id", targetID)
|
|
return nil
|
|
}
|