fix: phantom user merge on claim failure, referral assignment, account merge hardening

- Fix orphaned subscriptions/GuestPurchase when phantom claim fails with
  IntegrityError — now merges phantom into existing user across all 3 call sites
- Add explicit db.commit() after merge in both active-user and registration paths
- Fix remnawave_uuid transfer ordering (clear→flush→assign) to prevent unique
  constraint violation during flush
- Clear phantom.referral_code on soft-delete to prevent unique constraint issues
- Add status != DELETED filter to find_phantom_user_by_username (defense in depth)
- Add WARNING-level logging on phantom claims for admin audit trail
- Add functional index on lower(username) for phantom lookup performance (migration 0048)
- Add ON DELETE CASCADE to subscription_servers.subscription_id (migration 0047)
- Add admin endpoint POST /users/{id}/assign-referrer with recursive CTE cycle
  detection, self-enrichment prevention, and audit logging
- Harden account_merge_service: add SubscriptionServer, RioPayPayment,
  SeverPayPayment, SavedPaymentMethod, GuestPurchase, NewsArticle handling
- Fix logger key typo get= → error= in promocode activation
This commit is contained in:
Fringg
2026-03-23 13:59:38 +03:00
parent 172924df0e
commit fad77f8c80
8 changed files with 328 additions and 12 deletions
@@ -0,0 +1,74 @@
"""add ON DELETE CASCADE and index to subscription_servers.subscription_id
Revision ID: 0047
Revises: 0046
Create Date: 2026-03-23
Recreates the FK constraint on subscription_servers.subscription_id
with ON DELETE CASCADE so that deleting a subscription automatically
removes dependent subscription_servers rows. Also adds an index
on subscription_id for efficient CASCADE deletes and joins.
"""
from collections.abc import Sequence
from alembic import op
from sqlalchemy import text
revision: str = '0047'
down_revision: str | None = '0046'
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _get_actual_fk_name(connection, table: str, column: str) -> str | None:
"""Look up actual FK constraint name from pg_constraint."""
result = connection.execute(
text("""
SELECT con.conname
FROM pg_constraint con
JOIN pg_class rel ON rel.oid = con.conrelid
JOIN pg_namespace nsp ON nsp.oid = rel.relnamespace
JOIN pg_attribute att ON att.attrelid = con.conrelid
AND att.attnum = ANY(con.conkey)
WHERE rel.relname = :table
AND att.attname = :column
AND con.contype = 'f'
AND nsp.nspname = 'public'
LIMIT 1
"""),
{'table': table, 'column': column},
)
row = result.fetchone()
return row[0] if row else None
def upgrade() -> None:
connection = op.get_bind()
actual_fk = _get_actual_fk_name(connection, 'subscription_servers', 'subscription_id')
if actual_fk:
op.drop_constraint(actual_fk, 'subscription_servers', type_='foreignkey')
op.create_foreign_key(
'subscription_servers_subscription_id_fkey',
'subscription_servers',
'subscriptions',
['subscription_id'],
['id'],
ondelete='CASCADE',
)
op.create_index('ix_subscription_servers_subscription_id', 'subscription_servers', ['subscription_id'])
def downgrade() -> None:
op.drop_index('ix_subscription_servers_subscription_id', 'subscription_servers')
connection = op.get_bind()
actual_fk = _get_actual_fk_name(connection, 'subscription_servers', 'subscription_id')
if actual_fk:
op.drop_constraint(actual_fk, 'subscription_servers', type_='foreignkey')
op.create_foreign_key(
'subscription_servers_subscription_id_fkey',
'subscription_servers',
'subscriptions',
['subscription_id'],
['id'],
)
@@ -0,0 +1,35 @@
"""add functional index on lower(username) for phantom user lookup
Revision ID: 0048
Revises: 0047
Create Date: 2026-03-23
The find_phantom_user_by_username query uses func.lower(User.username)
which cannot use a regular B-tree index on username. This adds a
functional index to avoid sequential scans on the users table.
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = '0048'
down_revision: str | None = '0047'
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
with op.get_context().autocommit_block():
op.execute(
sa.text(
'CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_users_username_lower '
'ON users (lower(username))'
)
)
def downgrade() -> None:
with op.get_context().autocommit_block():
op.execute(sa.text('DROP INDEX CONCURRENTLY IF EXISTS ix_users_username_lower'))