Files
OwnCord/Server/service/block.go
T
J3vbandClaude Fable 5 6afa9e974c refactor(server): thread context.Context through the db layer and all callers
Fixes all 109 golangci-lint findings (106 contextcheck, 1 gocritic,
2 gosec) that accumulated after D2 wired dbgen (whose queries take ctx)
under ctx-less db.DB wrappers while CI lint was quota-dead. No nolint
comments added; every finding fixed by genuinely threading context.

- db: all 138 hand-written db.DB methods take ctx first; the dbCtx()
  Background shim is deleted; raw Query/QueryRow/Exec/Begin use their
  Context variants; the four redundant ctx-less passthroughs removed.
  db.Auditor/WriteAudit gain ctx.
- Seams: permissions.Checker (DB iface, HasChannelPerm,
  RequireChannelAccess) and the service.Store interface mirror the new
  signatures (ws.EventStore and plugin.PluginStore already did).
- Callers: api/admin handlers use r.Context(); ws per-message paths use
  the connection ctx via DispatchV2; hub loops and startup wiring use
  context.Background(); service methods thread ctx where they have one
  and Background where no ctx exists. Public service surface reached by
  ctx-holding chains (PermissionService.HasChannelPerm/GetRoleForUser/
  RequireChannelAccess, message/dm/block/invite/profile methods) is now
  ctx-first.
- Detached (context.WithoutCancel) where cancellation would break an
  invariant, found by a 3-lens adversarial review of the diff:
  * voice-leave background retries (a dead webhook/connection ctx killed
    retry 2 before it ran, leaving ghost capacity-holding voice rows)
  * rollbackVoiceJoin's compensating delete (its trigger IS the cancel)
  * post-2FA-change DeleteOtherSessions and logout DeleteSession (the
    security tail of a committed change must not die with the request)
  * all api/ws audit writes (a banned user could suppress their own
    login_blocked_banned row by aborting the request mid-bcrypt)
  * admin backup VACUUM INTO (an interrupt left a truncated .db that
    the backup list presented as restorable)
  * post-commit message/edit refetches (a committed message must still
    fan out when the sender disconnects)
  * hub settings-cache refresh (one dead connection could pin stale
    values for the 30s TTL)
- gocritic rangeValCopy fixed (index iteration); gosec G306 excluded in
  config with justification (generated source must stay world-readable)
  instead of flipping genprotocol output to 0o600.

Verified: gofmt/vet, all four build-tag variants, full suite, deadlock
pass, full -race pass, golangci-lint 0 issues uncapped.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 17:03:52 +02:00

79 lines
2.2 KiB
Go

package service
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/owncord/server/telemetry"
)
// BlockService handles user block/unblock operations.
type BlockService struct {
st Store
}
// NewBlockService creates a BlockService.
func NewBlockService(st Store) *BlockService {
return &BlockService{st: st}
}
// BlockUser blocks a target user. Validates the target exists and
// prevents self-blocking.
func (s *BlockService) BlockUser(ctx context.Context, blockerID, targetID int64) error {
ctx, span := telemetry.GlobalTracer("service/block").Start(ctx, "BlockService.BlockUser",
telemetry.Int64("blocker_id", blockerID),
telemetry.Int64("target_id", targetID),
)
start := time.Now()
defer func() {
telemetry.TimeSince(ctx, telemetry.NewAppMetrics().ServiceCallDurationSec, start,
telemetry.String("method", "BlockUser"))
span.End()
}()
if targetID <= 0 {
return fmt.Errorf("%w: user_id must be positive", ErrBadRequest)
}
if blockerID == targetID {
return fmt.Errorf("%w: cannot block yourself", ErrBadRequest)
}
target, err := s.st.GetUserByID(ctx, targetID)
if err != nil || target == nil {
return fmt.Errorf("%w: user not found", ErrNotFound)
}
if err := s.st.BlockUser(ctx, blockerID, targetID); err != nil {
return fmt.Errorf("%w: failed to block user", ErrInternal)
}
slog.Info("user blocked", "blocker_id", blockerID, "target_id", targetID)
return nil
}
// UnblockUser removes a block on a target user.
func (s *BlockService) UnblockUser(ctx context.Context, blockerID, targetID int64) error {
if targetID <= 0 {
return fmt.Errorf("%w: user_id must be positive", ErrBadRequest)
}
if err := s.st.UnblockUser(ctx, blockerID, targetID); err != nil {
return fmt.Errorf("%w: failed to unblock user", ErrInternal)
}
slog.Info("user unblocked", "blocker_id", blockerID, "target_id", targetID)
return nil
}
// ListBlocked returns all user IDs blocked by the given user.
func (s *BlockService) ListBlocked(ctx context.Context, blockerID int64) ([]int64, error) {
ids, err := s.st.ListBlockedUsers(ctx, blockerID)
if err != nil {
return nil, fmt.Errorf("%w: failed to list blocked users", ErrInternal)
}
if ids == nil {
ids = []int64{}
}
return ids, nil
}