Files
OwnCord/Server/service/user.go
T
J3vbandClaude Opus 4.8 7b178ff30b fix(security): harden server against verified code-review findings
Applies fixes for 20 adversarially-verified findings from a whole-codebase
security review (server side). All Go build-tag variants build, `go vet` is
clean, and the suite passes (the sole failing test, ws TestEmitEvents, is a
pre-existing nil-harness failure unrelated to these changes).

High severity:
- auth: close TOCTOU in TOTP verify rate-limit by recording each attempt
  atomically up-front (was Check-then-Allow), restoring the per-user
  brute-force cap.
- plugin: enforce the CPU/time budget on every WASM guest call via a
  WithTimeout context (WithCloseOnContextDone interrupts runaways); the
  configured budget was previously parsed but never applied.
- api/waf: inspect request bodies for chunked (ContentLength==-1) requests
  so the SQLi/XSS/RCE body rules can no longer be bypassed.
- ws: rate-limit voice_join/voice_leave and voice_e2ee announce/offer, which
  fan out to every participant and could force mass disconnects.

Medium severity:
- api: run bcrypt on the unknown-user login path (no || short-circuit) to
  remove the timing-based username-enumeration oracle.
- ws: verify LiveKit webhooks via the SDK receiver so the signature is bound
  to the body hash (kills forgery/replay).
- authz: require READ_MESSAGES for reactions and for plugin-command
  broadcasts; route the latter through RequireChannelAccess.
- api: cache the client-update signature fetch and rate-limit the endpoint.
- service: propagate DeleteOtherSessions failure from ChangePassword instead
  of silently reporting success.
- api: trust the rightmost non-proxy X-Forwarded-For entry, not the
  client-controllable leftmost one.
- plugin: route auto-registered commands through the conflict-checked
  RegisterCommand; pin the DNS-validated IP for host_http dials
  (DNS-rebinding TOCTOU).
- api: mark access-controlled downloads private/no-cache + Vary: Origin.

Low severity:
- auth: fail closed when a fully-shaped TOTP ciphertext fails GCM auth
  (was returning the ciphertext as plaintext).
- api: apply the livekit-proxy path allowlist to WebSocket upgrades too.
- service: verify attachment ownership before linking (IDOR).
- admin: bound the bootstrap setup invite (5 uses / 24h); re-verify the
  update binary hash immediately before rename+spawn (TOCTOU).
- service: require BanMembers + role hierarchy for moderation ban/unban.

chore: stop tracking the stray Server/owncord-server.exe build artifact.

Test infra: add uploader_id to the hand-rolled ws test attachment schemas and
make MemStore.GetAttachmentByID a no-op lookup, matching production/DB behavior.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 21:08:54 +02:00

95 lines
3.5 KiB
Go

package service
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/owncord/server/db"
"github.com/owncord/server/store"
"github.com/owncord/server/telemetry"
)
// UserService handles user profile and session operations.
type UserService struct {
st store.Store
}
// NewUserService creates a UserService.
func NewUserService(st store.Store) *UserService {
return &UserService{st: st}
}
// UpdateProfile updates a user's username and/or avatar.
// Returns the updated user for response building.
func (s *UserService) UpdateProfile(ctx context.Context, userID int64, username string, avatar *string) (*db.User, error) {
ctx, span := telemetry.GlobalTracer("service/user").Start(ctx, "UserService.UpdateProfile",
telemetry.Int64("user_id", userID),
)
start := time.Now()
defer func() {
telemetry.TimeSince(ctx, telemetry.NewAppMetrics().ServiceCallDurationSec, start,
telemetry.String("method", "UpdateProfile"))
span.End()
}()
if err := s.st.UpdateUserProfile(userID, username, avatar); err != nil {
if db.IsUniqueConstraintError(err) {
return nil, fmt.Errorf("%w: username is already taken", ErrConflict)
}
return nil, fmt.Errorf("%w: failed to update profile", ErrInternal)
}
user, err := s.st.GetUserByID(userID)
if err != nil {
return nil, fmt.Errorf("%w: failed to fetch updated user", ErrInternal)
}
_ = s.st.LogAudit(userID, "profile_update", "user", userID,
fmt.Sprintf("username=%s", username))
slog.Info("profile updated", "user_id", userID, "username", username)
return user, nil
}
// ChangePassword updates the user's password and revokes other sessions.
// Returns the number of other sessions revoked.
func (s *UserService) ChangePassword(userID int64, newPasswordHash string, keepSessionID int64) (int64, error) {
if err := s.st.UpdateUserPassword(userID, newPasswordHash); err != nil {
return 0, fmt.Errorf("%w: failed to update password", ErrInternal)
}
revoked, err := s.st.DeleteOtherSessions(userID, keepSessionID)
if err != nil {
slog.Error("UserService.ChangePassword DeleteOtherSessions", "err", err, "user_id", userID)
// The password was updated, but other sessions could not be revoked, so
// devices authenticated under the old password remain valid. Surface this
// as a failure instead of silently reporting success — a password change
// is a security action and the caller must be able to warn/retry.
return revoked, fmt.Errorf("%w: password changed but failed to revoke other sessions", ErrInternal)
}
_ = s.st.LogAudit(userID, "password_change", "user", userID, "password changed")
slog.Info("password changed", "user_id", userID, "sessions_revoked", revoked)
return revoked, nil
}
// ListSessions returns all active sessions for a user.
func (s *UserService) ListSessions(userID int64) ([]db.Session, error) {
sessions, err := s.st.ListUserSessions(userID)
if err != nil {
return nil, fmt.Errorf("%w: failed to list sessions", ErrInternal)
}
return sessions, nil
}
// RevokeSession deletes a specific session owned by the user.
func (s *UserService) RevokeSession(userID, sessionID int64) error {
if err := s.st.DeleteSessionByID(sessionID, userID); err != nil {
if errors.Is(err, db.ErrNotFound) {
return fmt.Errorf("%w: session not found", ErrNotFound)
}
return fmt.Errorf("%w: failed to revoke session", ErrInternal)
}
_ = s.st.LogAudit(userID, "session_revoke", "session", sessionID, "session revoked")
slog.Info("session revoked", "user_id", userID, "session_id", sessionID)
return nil
}