mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* fix(admin): reject banned users in admin auth (F1) adminAuthMiddleware accepted a Bearer token on session validity plus the ADMINISTRATOR bit alone and never consulted ban state, so a ban never revoked admin-panel access. Adds the auth.IsEffectivelyBanned guard that api.AuthMiddleware already uses, at both admin credential-resolution points. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(ws): gate the voice-channel text subscription on READ_MESSAGES (F2) registerNow subscribed any client with voice state to that channel's text-message topic regardless of READ_MESSAGES. The handshake's already-computed readable-channel set is now passed into registerNow and the subscription only happens when the voice channel is in it, preserving authorized reconnect delivery. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(service): require READ_MESSAGES to delete messages (F4) The non-DM delete gate checked MANAGE_MESSAGES without READ_MESSAGES, so a role locked out of a private channel could still delete every message in it. Requires ReadMessages alongside ManageMessages (and alongside SendMessages on the author path) and derives the mod flag from that same gate. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(service): require READ_MESSAGES alongside MANAGE_MESSAGES in SetMessagePinned (F8) Pin/unpin checked only MANAGE_MESSAGES, so a role denied READ on a private channel could still pin and unpin its messages. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(service): enforce the DM block at every DM interaction sink (F5) The DM block was only checked on send, leaving edit, reactions, pins and typing as bypasses. One shared requireDMNotBlocked is now called from all of them. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(ws): re-check CONNECT_VOICE when minting a refreshed LiveKit token (F6) voice_token_refresh re-minted a LiveKit token without re-checking CONNECT_VOICE, so a revoked permission kept working for the life of the session. The permission is now re-checked where the token is minted, and a 60s sweep evicts participants whose permission was revoked. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(ws): rate-limit voice_e2ee_offer after validation, keyed on server state (F7) The limiter key was built from unvalidated client input, letting an attacker grow the limiter map without bound. The limiter now runs after validation and keys on (sender, voiceChannelID), never on client input. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(ws): deliver voice_state/voice_leave only to roles that may read the channel (F9) Voice state of private channels was broadcast to every connected client, leaking channel membership. All 11 emit sites now route through one READ-filtered fan-out, channel-tagged so replay filters too. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): redact the LiveKit access token from proxy dial-failure logs (F10) A dial failure wrote the LiveKit access-token JWT into the server log via the URL in the error. redactKey now runs on the error before it reaches slog. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(auth): reserve the [deleted-N] username namespace (F11, F12) The tombstone username namespace used by account deletion was freely registrable, letting a user impersonate a deleted account. The namespace is now reserved at validation, and DeleteAccount retries with a random suffix on collision. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): strip Unicode format characters from upload filenames (F13) The attachment filename sanitizer stripped control characters but not unicode.Cf, allowing bidi-override extension spoofing. Cf is now stripped alongside controls and foreign path separators are cut. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): reserve the login attempt before the bcrypt compare (F3) The per-username lockout was a read-only IsLockedOut check followed by a failure recorded only after the ~250ms bcrypt compare, so N concurrent requests all passed the stale check before any of them recorded a failure. The per-username cap is the only cross-IP brute-force defence (the middleware limits per IP), so a distributed burst landed N guesses per 15-minute window instead of 10. Both counters are now reserved atomically with limiter.Allow before the compare, and the lockout decision moves to the read-only limiter.Check so the reservation is not double-counted. The limits are sized at threshold+1, which leaves the sequential accepted-input set byte-identical to the previous behaviour: failures 1-10 still land, the 10th still trips the lockout, and the account owner's correct password on attempt 10 still returns 200. Sizing at threshold instead would make 9 cheap wrong guesses convert the victim's own correct password into a 15-minute lockout - the regression that got two earlier attempts at this fix rejected, now pinned by a boundary test. Deliberately scoped to handleLogin. The report also suggested widening to the password-confirmation endpoints, but those are authenticated, share a single pw_confirm_fail key across the TOTP endpoints, and widening there is what got the first attempt rejected. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(deps): bump five Rust dependencies in /Client/tauri-client/src-tauri Rolls up dependabot #1259, #1260, #1261, #1262 and #1263: tauri-build 2.5.6 -> 2.6.3 tauri-plugin-fs 2.4.5 -> 2.5.1 tauri-plugin-http 2.5.7 -> 2.5.9 tauri-plugin-store 2.4.2 -> 2.4.4 webpki-roots 1.0.6 -> 1.0.9 All five are lockfile-only; the manifest constraints already permitted the new versions. The five PRs each rewrote overlapping regions of the same Cargo.lock and so could not be merged independently, so the lockfile was regenerated with cargo update --precise for each crate instead. The combined result is smaller than the sum of the five diffs because they share transitive updates. Verified with cargo check --locked --all-targets (exit 0). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(deps): bump typescript-eslint from 8.58.0 to 8.65.0 in /Client/tauri-client Dependabot #1258. 8.65.0 improves @typescript-eslint/no-unnecessary-type-assertion, which surfaces four assertions that were already redundant and now fail the lint gate. They are removed here rather than in a follow-up so no commit in this branch leaves `npm run lint` red: UserBar.ts / members.store.ts "online" as UserStatus -> "online" (the receiver already accepts the literal) media.ts drops `as RequestInit` on a literal that is already assignable LoginForm.ts drops `as { message: unknown }` made redundant by the `"message" in err` narrowing All four are the rule's own autofix. Verified: npm run typecheck, npm run lint, npm run format:check all clean, and the unit suite is 3572/3572 green across 129 files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
241 lines
8.3 KiB
Go
241 lines
8.3 KiB
Go
package db_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/owncord/server/db"
|
|
)
|
|
|
|
// ─── DeleteAccount — last admin guard ────────────────────────────────────────
|
|
|
|
func TestDeleteAccount_LastOwnerBlocked(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
// Create a single owner (role_id=1). No other admins exist.
|
|
ownerID := seedUser(t, database, "owner")
|
|
setRole(t, database, ownerID, 1) // Owner
|
|
|
|
err := database.DeleteAccount(context.Background(), ownerID)
|
|
if !errors.Is(err, db.ErrLastAdmin) {
|
|
t.Errorf("DeleteAccount(last owner) = %v, want ErrLastAdmin", err)
|
|
}
|
|
}
|
|
|
|
func TestDeleteAccount_LastAdminBlocked(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
adminID := seedUser(t, database, "admin")
|
|
setRole(t, database, adminID, 2) // Admin
|
|
|
|
err := database.DeleteAccount(context.Background(), adminID)
|
|
if !errors.Is(err, db.ErrLastAdmin) {
|
|
t.Errorf("DeleteAccount(last admin) = %v, want ErrLastAdmin", err)
|
|
}
|
|
}
|
|
|
|
func TestDeleteAccount_AllowedWhenOtherAdminExists(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
admin1 := seedUser(t, database, "admin1")
|
|
admin2 := seedUser(t, database, "admin2")
|
|
setRole(t, database, admin1, 2) // Admin
|
|
setRole(t, database, admin2, 2) // Admin
|
|
|
|
err := database.DeleteAccount(context.Background(), admin1)
|
|
if err != nil {
|
|
t.Fatalf("DeleteAccount with another admin present: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestDeleteAccount_AdminAllowedWhenOwnerExists(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
ownerID := seedUser(t, database, "owner")
|
|
adminID := seedUser(t, database, "admin")
|
|
setRole(t, database, ownerID, 1) // Owner
|
|
setRole(t, database, adminID, 2) // Admin
|
|
|
|
// Admin can delete because owner still exists.
|
|
err := database.DeleteAccount(context.Background(), adminID)
|
|
if err != nil {
|
|
t.Fatalf("DeleteAccount(admin with owner present): %v", err)
|
|
}
|
|
}
|
|
|
|
// ─── DeleteAccount — member deletion ─────────────────────────────────────────
|
|
|
|
func TestDeleteAccount_MemberSucceeds(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
userID := seedUser(t, database, "alice") // default role_id=4
|
|
|
|
err := database.DeleteAccount(context.Background(), userID)
|
|
if err != nil {
|
|
t.Fatalf("DeleteAccount(member): %v", err)
|
|
}
|
|
}
|
|
|
|
// ─── DeleteAccount — anonymisation ───────────────────────────────────────────
|
|
|
|
func TestDeleteAccount_AnonymisesUsername(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
userID := seedUser(t, database, "alice")
|
|
|
|
if err := database.DeleteAccount(context.Background(), userID); err != nil {
|
|
t.Fatalf("DeleteAccount: %v", err)
|
|
}
|
|
|
|
user, err := database.GetUserByID(context.Background(), userID)
|
|
if err != nil {
|
|
t.Fatalf("GetUserByID after delete: %v", err)
|
|
}
|
|
|
|
expected := fmt.Sprintf("[deleted-%d]", userID)
|
|
if user.Username != expected {
|
|
t.Errorf("Username = %q, want %q", user.Username, expected)
|
|
}
|
|
}
|
|
|
|
func TestDeleteAccount_ClearsPassword(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
userID := seedUser(t, database, "bob")
|
|
|
|
database.DeleteAccount(context.Background(), userID) //nolint:errcheck
|
|
|
|
user, _ := database.GetUserByID(context.Background(), userID)
|
|
if user.PasswordHash != "" {
|
|
t.Errorf("PasswordHash = %q, want empty", user.PasswordHash)
|
|
}
|
|
}
|
|
|
|
func TestDeleteAccount_ClearsAvatarAndTOTP(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
userID := seedUser(t, database, "charlie")
|
|
|
|
// Set avatar and TOTP before deletion.
|
|
database.ExecContext(context.Background(), "UPDATE users SET avatar = 'pic.png', totp_secret = 'SECRET' WHERE id = ?", userID) //nolint:errcheck
|
|
|
|
database.DeleteAccount(context.Background(), userID) //nolint:errcheck
|
|
|
|
user, _ := database.GetUserByID(context.Background(), userID)
|
|
if user.Avatar != nil {
|
|
t.Errorf("Avatar = %v, want nil", user.Avatar)
|
|
}
|
|
if user.TOTPSecret != nil {
|
|
t.Errorf("TOTPSecret = %v, want nil", user.TOTPSecret)
|
|
}
|
|
}
|
|
|
|
func TestDeleteAccount_SetsBannedAndOffline(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
userID := seedUser(t, database, "dave")
|
|
|
|
database.DeleteAccount(context.Background(), userID) //nolint:errcheck
|
|
|
|
user, _ := database.GetUserByID(context.Background(), userID)
|
|
if !user.Banned {
|
|
t.Error("Banned should be true after deletion")
|
|
}
|
|
if user.Status != "offline" {
|
|
t.Errorf("Status = %q, want 'offline'", user.Status)
|
|
}
|
|
}
|
|
|
|
// ─── DeleteAccount — related data cleanup ────────────────────────────────────
|
|
|
|
func TestDeleteAccount_DeletesSessions(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
userID := seedUser(t, database, "eve")
|
|
|
|
// Insert a session directly.
|
|
database.ExecContext(context.Background(),
|
|
"INSERT INTO sessions (user_id, token, expires_at) VALUES (?, 'tok123', datetime('now', '+1 day'))",
|
|
userID,
|
|
) //nolint:errcheck
|
|
|
|
database.DeleteAccount(context.Background(), userID) //nolint:errcheck
|
|
|
|
var count int
|
|
database.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM sessions WHERE user_id = ?", userID).Scan(&count) //nolint:errcheck
|
|
if count != 0 {
|
|
t.Errorf("sessions count = %d, want 0", count)
|
|
}
|
|
}
|
|
|
|
func TestDeleteAccount_SoftDeletesMessages(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
userID := seedUser(t, database, "frank")
|
|
chID := seedChannel(t, database, "general")
|
|
|
|
msgID, _ := database.CreateMessage(context.Background(), chID, userID, "hello world", nil)
|
|
|
|
database.DeleteAccount(context.Background(), userID) //nolint:errcheck
|
|
|
|
msg, err := database.GetMessage(context.Background(), msgID)
|
|
if err != nil {
|
|
t.Fatalf("GetMessage after delete: %v", err)
|
|
}
|
|
if !msg.Deleted {
|
|
t.Error("message should be soft-deleted")
|
|
}
|
|
if msg.Content != "" {
|
|
t.Errorf("message content = %q, want empty", msg.Content)
|
|
}
|
|
}
|
|
|
|
func TestDeleteAccount_NonexistentUser(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
|
|
err := database.DeleteAccount(context.Background(), 999999)
|
|
if err == nil {
|
|
t.Error("DeleteAccount(nonexistent) should return error")
|
|
}
|
|
}
|
|
|
|
// TestDeleteAccount_SquattedAnonNameStillDeletes locks the erasure path against
|
|
// a targeted denial of service: users.username is UNIQUE COLLATE NOCASE, so an
|
|
// attacker who renamed themselves to the victim's "[deleted-<id>]" made the
|
|
// anonymising UPDATE fail, rolled the whole transaction back, and left the
|
|
// victim permanently unable to delete their own account. auth.ValidateUsername
|
|
// now reserves the namespace, but DeleteAccount must survive a squatted name on
|
|
// its own — including one already in the database from before the rule existed.
|
|
func TestDeleteAccount_SquattedAnonNameStillDeletes(t *testing.T) {
|
|
database := openMigratedMemory(t)
|
|
victimID := seedUser(t, database, "victim")
|
|
squatterID := seedUser(t, database, "squatter")
|
|
|
|
squatted := fmt.Sprintf("[deleted-%d]", victimID)
|
|
if _, err := database.ExecContext(context.Background(),
|
|
"UPDATE users SET username = ? WHERE id = ?", squatted, squatterID,
|
|
); err != nil {
|
|
t.Fatalf("squat username: %v", err)
|
|
}
|
|
|
|
if err := database.DeleteAccount(context.Background(), victimID); err != nil {
|
|
t.Fatalf("DeleteAccount must not be blockable by a squatted name: %v", err)
|
|
}
|
|
|
|
victim, err := database.GetUserByID(context.Background(), victimID)
|
|
if err != nil || victim == nil {
|
|
t.Fatalf("GetUserByID after delete: %v", err)
|
|
}
|
|
if strings.EqualFold(victim.Username, squatted) {
|
|
t.Fatalf("victim kept the squatted name %q", victim.Username)
|
|
}
|
|
if !strings.HasPrefix(victim.Username, fmt.Sprintf("[deleted-%d-", victimID)) {
|
|
t.Errorf("Username = %q, want a suffixed [deleted-%d-…] fallback", victim.Username, victimID)
|
|
}
|
|
// The erasure itself must still have happened.
|
|
if !victim.Banned || victim.PasswordHash != "" {
|
|
t.Errorf("account not anonymised: banned=%v password=%q", victim.Banned, victim.PasswordHash)
|
|
}
|
|
}
|
|
|
|
// ─── Helper ──────────────────────────────────────────────────────────────────
|
|
|
|
func setRole(t *testing.T, database *db.DB, userID, roleID int64) {
|
|
t.Helper()
|
|
if _, err := database.ExecContext(context.Background(), "UPDATE users SET role_id = ? WHERE id = ?", roleID, userID); err != nil {
|
|
t.Fatalf("setRole(%d, %d): %v", userID, roleID, err)
|
|
}
|
|
}
|