Commit f05e01b4 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Gate AI Remix behind a flag and add admin account moderation

Remix is shelved until after beta launch: new REMIX_ENABLED config
flag (off by default) returns 403 from both /remix endpoints, mirroring
the frontend's existing VITE_ENABLE_REMIX gate. Full test coverage on
the underlying pipeline is preserved via an autouse fixture that force-
enables the flag for every existing test except the two new ones
covering the disabled response.

Admins can now moderate accounts: new User.is_active and
suspended_until columns back a soft-delete design (no FK cascades
exist anywhere in this schema, so a real row delete would orphan 20+
tables) enforced everywhere identity is resolved - login, refresh,
every authenticated request, and websockets - not just at login.
New endpoints extend the existing admin user list: username search,
rename, deactivate/reactivate, suspend/unsuspend, and password reset.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent abf8d0e0
Pipeline #1219 failed with stage
in 3 minutes and 32 seconds
......@@ -13,6 +13,10 @@ JWT_SECRET=
DOCS_USERNAME=choose_a_username
DOCS_PASSWORD=choose_a_strong_password
# Gate for the AI Remix feature (/remix) - shelved until after beta launch. Off (false) if
# unset. Mirrors the frontend's VITE_ENABLE_REMIX.
REMIX_ENABLED=false
# Where uploaded/tagged audio lives locally. Defaults to ./var/storage if unset.
LOCAL_STORAGE_ROOT=./var/storage
......
"""add is_active and suspended_until to users
Revision ID: b1f4a0d7e3c2
Revises: 6c99d29c0175
Create Date: 2026-10-10 11:20:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'b1f4a0d7e3c2'
down_revision: Union[str, Sequence[str], None] = '6c99d29c0175'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# Note: autogenerate also wanted to add a FK constraint on remix_jobs.user_id - a known
# pre-existing drift between the model and the actual schema history in this project, not
# related to this change. Deliberately left out, same as every prior migration that's hit it.
op.add_column('users', sa.Column('is_active', sa.Boolean(), server_default='1', nullable=False))
op.add_column('users', sa.Column('suspended_until', sa.DateTime(), nullable=True))
def downgrade() -> None:
"""Downgrade schema."""
op.drop_column('users', 'suspended_until')
op.drop_column('users', 'is_active')
......@@ -9,6 +9,7 @@ from starlette.background import BackgroundTask
from src.core.database import AuthAttempt, RefreshToken, User, UserProfile, get_db
from src.core.security import (
check_account_usable,
create_access_token,
create_refresh_token,
decode_token,
......@@ -189,6 +190,10 @@ async def auth_login(req: UsernameLoginReq, request: Request, db: Session = Depe
password_ok = verify_password(req.password, (user.password_hash if user else None) or _DUMMY_PASSWORD_HASH)
if not user or not user.password_hash or not password_ok:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid username or password")
# Checked only after the password is confirmed correct, not before - an account-locked
# message for a wrong password would leak the account's lock status to anyone who merely
# guesses the username, without even knowing the real password.
check_account_usable(user)
return _issue_tokens(db, user.id)
......@@ -272,9 +277,14 @@ async def auth_refresh(req: RefreshReq, db: Session = Depends(get_db)):
if not stored or stored.revoked_at is not None or stored.expires_at < _utcnow():
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Refresh token invalid or revoked")
user = db.query(User).filter(User.id == int(payload["sub"])).first()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Refresh token invalid or revoked")
check_account_usable(user)
stored.revoked_at = _utcnow()
db.commit()
return _issue_tokens(db, int(payload["sub"]))
return _issue_tokens(db, user.id)
@router.post("/logout")
......
......@@ -8,6 +8,7 @@ from typing import List, Optional
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, UploadFile, status
from sqlalchemy.orm import Session
from src.core.config import REMIX_ENABLED
from src.core.database import LibrarySong, RemixJob, User, get_db
from src.core.security import get_current_user
from src.services import storage
......@@ -47,6 +48,9 @@ async def create_remix(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
if not REMIX_ENABLED:
raise HTTPException(status_code=403, detail="Remix is coming soon - this feature is disabled until after beta launch.")
_check_remix_rate_limit(db, current_user.id)
# Deliberately does nothing here except fast local I/O (save uploads, look up library
......@@ -116,6 +120,9 @@ async def get_remix_status(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
if not REMIX_ENABLED:
raise HTTPException(status_code=403, detail="Remix is coming soon - this feature is disabled until after beta launch.")
# Scoped to the caller's own job - previously any sequential id worked for anyone
# (IDOR), leaking prompts, plan details, and finished download URLs.
job = db.query(RemixJob).filter(RemixJob.id == job_id, RemixJob.user_id == current_user.id).first()
......
import math
import os
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from typing import Optional
import httpx
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from src.core.config import logger
......@@ -20,7 +20,7 @@ from src.core.database import (
SoundmarkSuggestion,
User,
)
from src.core.security import get_current_business_admin, get_current_super_admin, get_current_user, get_current_user_for_stream, is_super_admin
from src.core.security import get_current_business_admin, get_current_super_admin, get_current_user, get_current_user_for_stream, hash_password, is_super_admin
router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"])
......@@ -259,6 +259,20 @@ class RoleUpdate(BaseModel):
role: str
class UserEditReq(BaseModel):
"""Partial update - all fields optional so the admin UI can send just the one thing being
changed (rename vs. activate/deactivate vs. suspend) without resubmitting the rest."""
username: Optional[str] = Field(None, min_length=3, max_length=32, regex=r"^[a-zA-Z0-9_]+$")
is_active: Optional[bool] = None
# Hours from now to suspend until; 0 (or omitted with is_active untouched) clears any
# existing suspension. A float so "suspend for 30 minutes" (0.5) is still expressible.
suspend_hours: Optional[float] = None
class PasswordResetReq(BaseModel):
new_password: str = Field(min_length=8, max_length=200)
# ---- Consumer endpoints (any authenticated user) ----
......@@ -356,22 +370,35 @@ async def reverse_geocode(lat: float, lon: float, current_user: User = Depends(g
return {"status": "success", "display_name": data.get("display_name")}
def _serialize_admin_user(u: User) -> dict:
return {
"id": u.id,
"username": u.username,
"phone_number": u.phone_number,
"role": u.role,
"is_active": u.is_active,
"suspended_until": u.suspended_until.isoformat() if u.suspended_until else None,
}
@router.get("/admin/users")
def list_users(
role: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)
role: Optional[str] = None,
q: Optional[str] = None,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
"""Lets the super admin panel find/list users to promote to business_admin or assign as a
soundmark's owner."""
"""Lets the super admin panel find/list users to promote to business_admin, assign as a
soundmark's owner, or manage directly (edit/deactivate/suspend/reset password below). `q`
is a plain substring match against username - good enough at this app's scale, no need for
a real search index."""
query = db.query(User)
if role:
query = query.filter(User.role == role)
if q:
query = query.filter(User.username.ilike(f"%{q}%"))
users = query.order_by(User.id).all()
return {
"status": "success",
"users": [
{"id": u.id, "username": u.username, "phone_number": u.phone_number, "role": u.role} for u in users
],
}
return {"status": "success", "users": [_serialize_admin_user(u) for u in users]}
@router.patch("/admin/users/{user_id}/role")
......@@ -391,6 +418,63 @@ def update_user_role(
return {"status": "success", "user": {"id": user.id, "username": user.username, "role": user.role}}
@router.patch("/admin/users/{user_id}")
def edit_user(
user_id: int,
body: UserEditReq,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
"""Covers everything short of role (its own endpoint above) and password (its own endpoint
below, since resetting a credential deserves a distinct audit-friendly action rather than
being one field among several here): rename, deactivate/reactivate (soft delete - see the
User.is_active comment in database.py for why this isn't a real row delete), and time-boxed
suspension. A super admin can lock their own account via this same endpoint - not blocked
deliberately, since a real account-compromise response shouldn't have a built-in exception
for whoever happens to be a super admin."""
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
if body.username is not None:
taken = db.query(User).filter(User.username == body.username, User.id != user_id).first()
if taken:
raise HTTPException(status_code=409, detail="Username already taken")
user.username = body.username
if body.is_active is not None:
user.is_active = body.is_active
if body.suspend_hours is not None:
user.suspended_until = (
datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(hours=body.suspend_hours)
if body.suspend_hours > 0
else None
)
db.commit()
db.refresh(user)
return {"status": "success", "user": _serialize_admin_user(user)}
@router.post("/admin/users/{user_id}/reset-password")
def admin_reset_password(
user_id: int,
body: PasswordResetReq,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
"""Sets a new password directly, bypassing the old one - for support/account-recovery
requests. Doesn't touch username/password-based accounts' other state (role, active
status); a Telegram-only account (no password_hash yet) can also be given one this way."""
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
user.password_hash = hash_password(body.new_password)
db.commit()
return {"status": "success"}
# ---- Review queue (business_admin+, scoped to what they can moderate) ----
......
......@@ -14,6 +14,11 @@ LALAL_API_KEY = os.getenv("LALAL_API_KEY")
DOCS_USERNAME = os.getenv("DOCS_USERNAME")
DOCS_PASSWORD = os.getenv("DOCS_PASSWORD")
# Gate for the AI Remix feature (POST/GET /remix) - shelved until after beta launch
# (2026-10-09). Off by default, same posture as the frontend's VITE_ENABLE_REMIX
# (stax_webapp/src/config/flags.ts), which already hides the nav entry/route.
REMIX_ENABLED = os.getenv("REMIX_ENABLED", "false").lower() == "true"
# Origins allowed to call this API from a browser (the stax_webapp frontend, dev and prod).
# Comma-separated in the env var. Auth here is a Bearer token in localStorage, never a
# cookie, so allowing these origins doesn't need allow_credentials.
......
......@@ -46,6 +46,15 @@ class User(Base):
# passes False for a genuinely new account. Declared here (not just in the migration) since
# tests boot their schema via Base.metadata.create_all, which never runs Alembic.
has_completed_onboarding = Column(Boolean, nullable=False, server_default='1')
# Admin-controlled account lock (soft delete, not a real row delete - deleting the row
# outright would leave 20+ FK columns across the schema dangling, since none of them have
# cascade/ondelete configured). False blocks login and any already-issued token immediately
# (checked in get_current_user, not just at login). server_default of true so every
# existing row stays active.
is_active = Column(Boolean, nullable=False, server_default='1')
# Time-boxed alternative to is_active - set to a future timestamp to lock the account until
# then; naturally "expires" once that time passes (checked live, no cleanup job needed).
suspended_until = Column(DateTime, nullable=True)
class RefreshToken(Base):
__tablename__ = "refresh_tokens"
......
......@@ -77,6 +77,17 @@ def decode_token(token: str, expected_type: str) -> dict:
return payload
def check_account_usable(user: User) -> None:
"""Raises if an admin has locked this account (deactivated or time-boxed suspended) -
shared by the login endpoint (auth.py) and every already-authenticated request below, so
locking an account takes effect immediately rather than only at next login. 403 (not 401):
the credentials/token are valid, the account itself just isn't usable right now."""
if not user.is_active:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="This account has been deactivated.")
if user.suspended_until and user.suspended_until > datetime.now(timezone.utc).replace(tzinfo=None):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="This account is temporarily suspended.")
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
db: Session = Depends(get_db),
......@@ -87,6 +98,7 @@ def get_current_user(
user = db.query(User).filter(User.id == int(payload["sub"])).first()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
check_account_usable(user)
return user
......@@ -111,6 +123,7 @@ def get_current_user_for_stream(
user = db.query(User).filter(User.id == int(payload["sub"])).first()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
check_account_usable(user)
return user
......@@ -126,7 +139,13 @@ def user_id_from_ws_token(token: str) -> Optional[int]:
db = SessionLocal()
try:
user = db.query(User).filter(User.id == int(payload["sub"])).first()
return user.id if user else None
if not user:
return None
try:
check_account_usable(user)
except HTTPException:
return None
return user.id
finally:
db.close()
......
......@@ -47,13 +47,14 @@ _user_ids = itertools.count(10_000)
def make_user(db_session):
"""Creates a real User row (as if they'd completed Telegram login) without going through
the actual Telegram auth flow - test_auth.py covers that flow itself with mocks."""
def _make(phone_number: str = None, telegram_session_string: str = "fake-session-string", role: str = "user"):
def _make(phone_number: str = None, telegram_session_string: str = "fake-session-string", role: str = "user", username: str = None):
uid = next(_user_ids)
user = User(
id=uid,
phone_number=phone_number or f"+1555{uid}",
telegram_session_string=telegram_session_string,
role=role,
username=username,
)
db_session.add(user)
db_session.commit()
......
......@@ -80,6 +80,57 @@ def test_auth_login_missing_fields(client):
assert response.status_code == 422
def test_auth_login_rejects_deactivated_account(client, db_session):
client.post("/auth/register", json={"username": "deactivateduser", "password": "correcthorse"})
user = db_session.query(User).filter(User.username == "deactivateduser").first()
user.is_active = False
db_session.commit()
response = client.post("/auth/login", json={"username": "deactivateduser", "password": "correcthorse"})
assert response.status_code == 403
def test_auth_login_rejects_suspended_account(client, db_session):
from datetime import datetime, timedelta, timezone
client.post("/auth/register", json={"username": "suspendeduser", "password": "correcthorse"})
user = db_session.query(User).filter(User.username == "suspendeduser").first()
user.suspended_until = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(hours=1)
db_session.commit()
response = client.post("/auth/login", json={"username": "suspendeduser", "password": "correcthorse"})
assert response.status_code == 403
def test_auth_login_allows_account_with_expired_suspension(client, db_session):
from datetime import datetime, timedelta, timezone
client.post("/auth/register", json={"username": "formerlysuspended", "password": "correcthorse"})
user = db_session.query(User).filter(User.username == "formerlysuspended").first()
user.suspended_until = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(hours=1)
db_session.commit()
response = client.post("/auth/login", json={"username": "formerlysuspended", "password": "correcthorse"})
assert response.status_code == 200
def test_deactivating_account_locks_out_an_already_issued_token(client, db_session):
# Not just a login-time check - an admin deactivating someone mid-session should take
# effect immediately, not only the next time they try to log in.
register = client.post("/auth/register", json={"username": "liveSessionUser", "password": "correcthorse"})
token = register.json()["access_token"]
headers = {"Authorization": f"Bearer {token}"}
assert client.get("/auth/me", headers=headers).status_code == 200
user = db_session.query(User).filter(User.username == "liveSessionUser").first()
user.is_active = False
db_session.commit()
response = client.get("/auth/me", headers=headers)
assert response.status_code == 403
def test_auth_login_rate_limited_per_username(client):
client.post("/auth/register", json={"username": "bruteforcetarget", "password": "correcthorse1"})
......
......@@ -2,10 +2,21 @@ import io
import os
import tempfile
import pytest
from src.api.routers import remix as remix_router
from src.core.database import LibrarySong, SessionLocal
@pytest.fixture(autouse=True)
def _remix_enabled(monkeypatch):
# Remix is off by default in production (src.core.config.REMIX_ENABLED, shelved until
# after beta launch) - force it on for every test in this file so the suite keeps
# exercising the real feature logic, not just the disabled-gate response. The two tests
# below that specifically cover the disabled state re-patch it back to False themselves.
monkeypatch.setattr(remix_router, "REMIX_ENABLED", True)
def _wav_bytes():
# A tiny valid WAV file is enough - the engine itself is mocked out below,
# these tests only exercise the API contract (validation, job bookkeeping).
......@@ -48,6 +59,20 @@ def test_remix_status_requires_auth(client):
assert response.status_code == 401
def test_remix_disabled_by_default_returns_403(client, auth_as, monkeypatch):
monkeypatch.setattr(remix_router, "REMIX_ENABLED", False)
headers, _ = auth_as()
response = client.post("/remix", data={"prompt": "make it slower"}, files=[], headers=headers)
assert response.status_code == 403
def test_remix_status_disabled_by_default_returns_403(client, auth_as, monkeypatch):
monkeypatch.setattr(remix_router, "REMIX_ENABLED", False)
headers, _ = auth_as()
response = client.get("/remix/1", headers=headers)
assert response.status_code == 403
def test_remix_requires_at_least_one_file(client, auth_as):
headers, _ = auth_as()
response = client.post("/remix", data={"prompt": "make it slower"}, files=[], headers=headers)
......
......@@ -604,6 +604,98 @@ def test_role_update_rejects_invalid_role(client, auth_as):
assert response.status_code == 422
def test_admin_user_list_search_matches_username_substring(client, auth_as):
headers, _ = auth_as(role="super_admin")
_, target = auth_as(username="findable_zebra")
response = client.get("/soundmarks/admin/users", params={"q": "zebra"}, headers=headers)
assert response.status_code == 200
ids = {u["id"] for u in response.json()["users"]}
assert target.id in ids
def test_admin_renames_a_user(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
_, plain_user = auth_as(username="oldname")
response = client.patch(f"/soundmarks/admin/users/{plain_user.id}", json={"username": "newname"}, headers=headers)
assert response.status_code == 200
db_session.refresh(plain_user)
assert plain_user.username == "newname"
def test_admin_rename_rejects_taken_username(client, auth_as):
headers, _ = auth_as(role="super_admin")
_, existing = auth_as(username="taken_name")
_, plain_user = auth_as(username="wants_taken_name")
response = client.patch(f"/soundmarks/admin/users/{plain_user.id}", json={"username": "taken_name"}, headers=headers)
assert response.status_code == 409
def test_admin_deactivates_and_reactivates_a_user(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
_, plain_user = auth_as()
response = client.patch(f"/soundmarks/admin/users/{plain_user.id}", json={"is_active": False}, headers=headers)
assert response.status_code == 200
assert response.json()["user"]["is_active"] is False
db_session.refresh(plain_user)
assert plain_user.is_active is False
response = client.patch(f"/soundmarks/admin/users/{plain_user.id}", json={"is_active": True}, headers=headers)
assert response.status_code == 200
db_session.refresh(plain_user)
assert plain_user.is_active is True
def test_admin_suspends_and_unsuspends_a_user(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
_, plain_user = auth_as()
response = client.patch(f"/soundmarks/admin/users/{plain_user.id}", json={"suspend_hours": 2}, headers=headers)
assert response.status_code == 200
db_session.refresh(plain_user)
assert plain_user.suspended_until is not None
response = client.patch(f"/soundmarks/admin/users/{plain_user.id}", json={"suspend_hours": 0}, headers=headers)
assert response.status_code == 200
db_session.refresh(plain_user)
assert plain_user.suspended_until is None
def test_admin_resets_a_users_password(client, auth_as):
headers, _ = auth_as(role="super_admin")
client.post("/auth/register", json={"username": "needsreset", "password": "oldpassword"})
assert client.post("/auth/login", json={"username": "needsreset", "password": "oldpassword"}).status_code == 200
# Look up the id the register call created, by username, through the admin list endpoint
# rather than reaching into the DB directly - exercises the real lookup path a UI would use.
listing = client.get("/soundmarks/admin/users", params={"q": "needsreset"}, headers=headers)
user_id = listing.json()["users"][0]["id"]
response = client.post(f"/soundmarks/admin/users/{user_id}/reset-password", json={"new_password": "brandnewpassword"}, headers=headers)
assert response.status_code == 200
assert client.post("/auth/login", json={"username": "needsreset", "password": "oldpassword"}).status_code == 401
assert client.post("/auth/login", json={"username": "needsreset", "password": "brandnewpassword"}).status_code == 200
def test_admin_user_management_requires_super_admin(client, auth_as):
headers, _ = auth_as(role="business_admin")
_, plain_user = auth_as()
assert client.patch(f"/soundmarks/admin/users/{plain_user.id}", json={"is_active": False}, headers=headers).status_code == 403
assert client.post(f"/soundmarks/admin/users/{plain_user.id}/reset-password", json={"new_password": "whatever123"}, headers=headers).status_code == 403
def test_admin_edit_user_404_for_unknown_id(client, auth_as):
headers, _ = auth_as(role="super_admin")
response = client.patch("/soundmarks/admin/users/999999", json={"is_active": False}, headers=headers)
assert response.status_code == 404
# ---- Song proposals & voting (community tier only) ----
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment