Commit 913721b5 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix the two known security gaps: /remix auth+IDOR, Rooms websocket user_id forgery

POST /remix and GET /remix/{job_id} previously had no authentication at all -
user_id was a raw client-supplied form field, and job status was fetchable by
guessing sequential ids (IDOR). Both endpoints now require a logged-in user;
RemixJob gets a new user_id column (migration 347da5d41656) so job status is
scoped to its owner. Also closed an adjacent IDOR found while fixing this:
library_song_ids sourcing now scopes to the caller's own library, not any
song id.

WS /social/rooms/{room_id}/ws took user_id as an unauthenticated query
param - anyone could connect claiming to be any user. It now takes a JWT
access token instead (browsers can't set WS headers, so it travels as a
query param) and verifies it - signature, expiry, real user row - before
accepting the connection.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent c5585aed
Pipeline #1083 passed with stage
in 2 minutes and 53 seconds
"""add user_id to remix_jobs
Revision ID: 347da5d41656
Revises: 348a47d4b742
Create Date: 2026-08-15 18:40:30.727080
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '347da5d41656'
down_revision: Union[str, Sequence[str], None] = '348a47d4b742'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
op.add_column("remix_jobs", sa.Column("user_id", sa.Integer(), nullable=True))
def downgrade() -> None:
"""Downgrade schema."""
op.drop_column("remix_jobs", "user_id")
...@@ -7,7 +7,8 @@ from typing import List, Optional ...@@ -7,7 +7,8 @@ from typing import List, Optional
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Request, UploadFile from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Request, UploadFile
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import LibrarySong, RemixJob, get_db from src.core.database import LibrarySong, RemixJob, User, get_db
from src.core.security import get_current_user
from src.services import storage from src.services import storage
from src.services.remix_engine import render_remix_sync from src.services.remix_engine import render_remix_sync
...@@ -23,8 +24,8 @@ async def create_remix( ...@@ -23,8 +24,8 @@ async def create_remix(
prompt: str = Form(..., description="Natural-language description of the remix you want, e.g. 'blend the vocals of the first song over the beat of the second, slowed down and dreamy'"), prompt: str = Form(..., description="Natural-language description of the remix you want, e.g. 'blend the vocals of the first song over the beat of the second, slowed down and dreamy'"),
files: List[UploadFile] = File(default=[], description="Audio files to remix together"), files: List[UploadFile] = File(default=[], description="Audio files to remix together"),
library_song_ids: Optional[str] = Form(None, description="Comma-separated LibrarySong IDs to use as sources instead of (or alongside) uploaded files - using library songs is what lets the finished remix link back into the social/remix-tree graph"), library_song_ids: Optional[str] = Form(None, description="Comma-separated LibrarySong IDs to use as sources instead of (or alongside) uploaded files - using library songs is what lets the finished remix link back into the social/remix-tree graph"),
user_id: Optional[int] = Form(None, description="Attributes the resulting library entry and social post to this user"),
db: Session = Depends(get_db), db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
): ):
# Deliberately does nothing here except fast local I/O (save uploads, look up library # Deliberately does nothing here except fast local I/O (save uploads, look up library
# rows) - no identify_audio/Shazam/AcoustID calls. Those are real network calls that can # rows) - no identify_audio/Shazam/AcoustID calls. Those are real network calls that can
...@@ -53,7 +54,10 @@ async def create_remix( ...@@ -53,7 +54,10 @@ async def create_remix(
song_id = int(raw_id) song_id = int(raw_id)
except ValueError: except ValueError:
raise HTTPException(status_code=400, detail=f"Invalid library_song_ids value: {raw_id!r}") raise HTTPException(status_code=400, detail=f"Invalid library_song_ids value: {raw_id!r}")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first() # Scoped to the caller's own library - without this, any authenticated user could
# remix (and thereby read the audio of) another user's private library song just
# by guessing a sequential id.
song = db.query(LibrarySong).filter(LibrarySong.id == song_id, LibrarySong.user_id == current_user.id).first()
if not song or not song.file_path or not os.path.exists(song.file_path): if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=400, detail=f"Library song {song_id} not found or its file is missing.") raise HTTPException(status_code=400, detail=f"Library song {song_id} not found or its file is missing.")
input_paths.append(song.file_path) input_paths.append(song.file_path)
...@@ -74,19 +78,26 @@ async def create_remix( ...@@ -74,19 +78,26 @@ async def create_remix(
os.remove(p) os.remove(p)
raise HTTPException(status_code=500, detail=f"Failed to receive uploaded files: {e}") raise HTTPException(status_code=500, detail=f"Failed to receive uploaded files: {e}")
job = RemixJob(status="queued", prompt=prompt, input_paths=json.dumps(input_paths)) job = RemixJob(status="queued", prompt=prompt, input_paths=json.dumps(input_paths), user_id=current_user.id)
db.add(job) db.add(job)
db.commit() db.commit()
db.refresh(job) db.refresh(job)
background_tasks.add_task(render_remix_sync, job.id, input_paths, prompt, filenames, source_song_ids, user_id) background_tasks.add_task(render_remix_sync, job.id, input_paths, prompt, filenames, source_song_ids, current_user.id)
return {"job_id": job.id, "status": job.status, "status_url": f"/remix/{job.id}"} return {"job_id": job.id, "status": job.status, "status_url": f"/remix/{job.id}"}
@router.get("/{job_id}") @router.get("/{job_id}")
async def get_remix_status(job_id: int, request: Request, db: Session = Depends(get_db)): async def get_remix_status(
job = db.query(RemixJob).filter(RemixJob.id == job_id).first() job_id: int,
request: Request,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
# 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()
if not job: if not job:
raise HTTPException(status_code=404, detail="Remix job not found.") raise HTTPException(status_code=404, detail="Remix job not found.")
......
...@@ -7,7 +7,7 @@ from fastapi.responses import FileResponse ...@@ -7,7 +7,7 @@ from fastapi.responses import FileResponse
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, SessionLocal, User, Post, LiveLocation, LibrarySong, LiveRoom from src.core.database import get_db, SessionLocal, User, Post, LiveLocation, LibrarySong, LiveRoom
from src.core.security import get_current_user from src.core.security import get_current_user, decode_token
from src.services.room_manager import room_manager from src.services.room_manager import room_manager
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
import math import math
...@@ -313,8 +313,30 @@ def _set_room_current_song(room_id: int, song_id): ...@@ -313,8 +313,30 @@ def _set_room_current_song(room_id: int, song_id):
db.close() db.close()
def _user_id_from_ws_token(token: str) -> Optional[int]:
"""Browsers' native WebSocket API can't set an Authorization header, so the access token
travels as a query param instead - this still independently verifies it (signature +
expiry + real user row) rather than trusting a bare user_id, which is what let anyone
connect and act as any user before this."""
try:
payload = decode_token(token, expected_type="access")
except Exception:
return None
db = SessionLocal()
try:
user = db.query(User).filter(User.id == int(payload["sub"])).first()
return user.id if user else None
finally:
db.close()
@router.websocket("/rooms/{room_id}/ws") @router.websocket("/rooms/{room_id}/ws")
async def room_websocket(websocket: WebSocket, room_id: int, user_id: int): async def room_websocket(websocket: WebSocket, room_id: int, token: str):
user_id = _user_id_from_ws_token(token)
if user_id is None:
await websocket.close(code=4401)
return
room_row = _get_room_or_none(room_id) room_row = _get_room_or_none(room_id)
if not room_row: if not room_row:
await websocket.close(code=4404) await websocket.close(code=4404)
......
...@@ -262,6 +262,10 @@ class Correction(Base): ...@@ -262,6 +262,10 @@ class Correction(Base):
class RemixJob(Base): class RemixJob(Base):
__tablename__ = "remix_jobs" __tablename__ = "remix_jobs"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
# Nullable only for pre-auth rows from before this column existed - every job created via
# POST /remix now always has one, since that endpoint requires a logged-in user. Used to
# scope GET /remix/{job_id} to its owner (previously an IDOR: any sequential id worked).
user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
status = Column(String, default="queued") # queued, planning, separating, mixing, mastering, tagging, done, error status = Column(String, default="queued") # queued, planning, separating, mixing, mastering, tagging, done, error
stage_detail = Column(String, nullable=True) stage_detail = Column(String, nullable=True)
prompt = Column(String) prompt = Column(String)
......
...@@ -38,23 +38,36 @@ def _make_library_song(**overrides): ...@@ -38,23 +38,36 @@ def _make_library_song(**overrides):
db.close() db.close()
def test_remix_requires_at_least_one_file(client): def test_remix_requires_auth(client):
response = client.post("/remix", data={"prompt": "make it slower"}, files=[]) response = client.post("/remix", data={"prompt": "make it slower"}, files=[])
assert response.status_code == 401
def test_remix_status_requires_auth(client):
response = client.get("/remix/1")
assert response.status_code == 401
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)
assert response.status_code == 400 assert response.status_code == 400
def test_remix_rejects_more_than_five_songs(client, monkeypatch): def test_remix_rejects_more_than_five_songs(client, auth_as, monkeypatch):
headers, _ = auth_as()
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None) monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
files = [("files", (f"song{i}.wav", io.BytesIO(_wav_bytes()), "audio/wav")) for i in range(6)] files = [("files", (f"song{i}.wav", io.BytesIO(_wav_bytes()), "audio/wav")) for i in range(6)]
response = client.post("/remix", data={"prompt": "mashup"}, files=files) response = client.post("/remix", data={"prompt": "mashup"}, files=files, headers=headers)
assert response.status_code == 400 assert response.status_code == 400
def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatch): def test_remix_does_not_call_identify_audio_before_responding(client, auth_as, monkeypatch):
# The whole point of the earlier fix: identify_audio (real Shazam/AcoustID network # The whole point of the earlier fix: identify_audio (real Shazam/AcoustID network
# calls, ~30s each on a miss) must never run inside the request/response cycle - only # calls, ~30s each on a miss) must never run inside the request/response cycle - only
# inside the background job. If someone re-adds it to the endpoint, this call would # inside the background job. If someone re-adds it to the endpoint, this call would
# hang/raise instead of the fast, synchronous response below. # hang/raise instead of the fast, synchronous response below.
headers, user = auth_as()
captured = {} captured = {}
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None): def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
...@@ -75,13 +88,15 @@ def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatc ...@@ -75,13 +88,15 @@ def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatc
("files", ("song_a.wav", io.BytesIO(_wav_bytes()), "audio/wav")), ("files", ("song_a.wav", io.BytesIO(_wav_bytes()), "audio/wav")),
("files", ("song_b.wav", io.BytesIO(_wav_bytes()), "audio/wav")), ("files", ("song_b.wav", io.BytesIO(_wav_bytes()), "audio/wav")),
] ]
response = client.post("/remix", data={"prompt": "blend the vocals of the first over the beat of the second"}, files=files) response = client.post(
"/remix", data={"prompt": "blend the vocals of the first over the beat of the second"}, files=files, headers=headers
)
assert response.status_code == 200 assert response.status_code == 200
body = response.json() body = response.json()
assert body["status"] == "queued" assert body["status"] == "queued"
job_id = body["job_id"] job_id = body["job_id"]
status_response = client.get(f"/remix/{job_id}") status_response = client.get(f"/remix/{job_id}", headers=headers)
assert status_response.status_code == 200 assert status_response.status_code == 200
assert status_response.json()["job_id"] == job_id assert status_response.json()["job_id"] == job_id
...@@ -89,11 +104,12 @@ def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatc ...@@ -89,11 +104,12 @@ def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatc
assert len(captured["input_paths"]) == 2 assert len(captured["input_paths"]) == 2
assert captured["filenames"] == ["song_a.wav", "song_b.wav"] assert captured["filenames"] == ["song_a.wav", "song_b.wav"]
assert captured["source_song_ids"] == [None, None] assert captured["source_song_ids"] == [None, None]
assert captured["user_id"] is None assert captured["user_id"] == user.id
def test_remix_accepts_library_song_ids(client, monkeypatch): def test_remix_accepts_library_song_ids(client, auth_as, monkeypatch):
song_id, path = _make_library_song() headers, user = auth_as()
song_id, path = _make_library_song(user_id=user.id)
try: try:
captured = {} captured = {}
...@@ -107,25 +123,42 @@ def test_remix_accepts_library_song_ids(client, monkeypatch): ...@@ -107,25 +123,42 @@ def test_remix_accepts_library_song_ids(client, monkeypatch):
response = client.post( response = client.post(
"/remix", "/remix",
data={"prompt": "remix this", "library_song_ids": str(song_id), "user_id": "7"}, data={"prompt": "remix this", "library_song_ids": str(song_id)},
headers=headers,
) )
assert response.status_code == 200 assert response.status_code == 200
assert captured["input_paths"] == [path] assert captured["input_paths"] == [path]
assert captured["filenames"] == ["Library Song"] assert captured["filenames"] == ["Library Song"]
assert captured["source_song_ids"] == [song_id] assert captured["source_song_ids"] == [song_id]
assert captured["user_id"] == 7 # Always the authenticated caller now - no longer a client-supplied form field.
assert captured["user_id"] == user.id
finally: finally:
os.remove(path) os.remove(path)
def test_remix_rejects_unknown_library_song_id(client, monkeypatch): def test_remix_rejects_unknown_library_song_id(client, auth_as, monkeypatch):
headers, _ = auth_as()
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None) monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
response = client.post("/remix", data={"prompt": "remix this", "library_song_ids": "999999"}) response = client.post("/remix", data={"prompt": "remix this", "library_song_ids": "999999"}, headers=headers)
assert response.status_code == 400 assert response.status_code == 400
def test_remix_mixes_library_songs_and_uploads(client, monkeypatch): def test_remix_rejects_another_users_library_song_id(client, auth_as, monkeypatch):
song_id, path = _make_library_song(title="From Library") # IDOR check: owning a valid library_song_id isn't enough if it belongs to someone else.
_, owner = auth_as()
song_id, path = _make_library_song(user_id=owner.id)
try:
headers, _ = auth_as() # a second, different user
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
response = client.post("/remix", data={"prompt": "remix this", "library_song_ids": str(song_id)}, headers=headers)
assert response.status_code == 400
finally:
os.remove(path)
def test_remix_mixes_library_songs_and_uploads(client, auth_as, monkeypatch):
headers, user = auth_as()
song_id, path = _make_library_song(title="From Library", user_id=user.id)
try: try:
captured = {} captured = {}
...@@ -140,6 +173,7 @@ def test_remix_mixes_library_songs_and_uploads(client, monkeypatch): ...@@ -140,6 +173,7 @@ def test_remix_mixes_library_songs_and_uploads(client, monkeypatch):
"/remix", "/remix",
data={"prompt": "mashup", "library_song_ids": str(song_id)}, data={"prompt": "mashup", "library_song_ids": str(song_id)},
files=files, files=files,
headers=headers,
) )
assert response.status_code == 200 assert response.status_code == 200
assert captured["source_song_ids"] == [song_id, None] assert captured["source_song_ids"] == [song_id, None]
...@@ -148,9 +182,11 @@ def test_remix_mixes_library_songs_and_uploads(client, monkeypatch): ...@@ -148,9 +182,11 @@ def test_remix_mixes_library_songs_and_uploads(client, monkeypatch):
os.remove(path) os.remove(path)
def test_remix_status_surfaces_library_and_post_ids_when_done(client, monkeypatch): def test_remix_status_surfaces_library_and_post_ids_when_done(client, auth_as, monkeypatch):
from src.core.database import RemixJob, SessionLocal as SL from src.core.database import RemixJob, SessionLocal as SL
headers, _ = auth_as()
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None): def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
db = SL() db = SL()
try: try:
...@@ -166,16 +202,31 @@ def test_remix_status_surfaces_library_and_post_ids_when_done(client, monkeypatc ...@@ -166,16 +202,31 @@ def test_remix_status_surfaces_library_and_post_ids_when_done(client, monkeypatc
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render) monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))] files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post("/remix", data={"prompt": "test"}, files=files) response = client.post("/remix", data={"prompt": "test"}, files=files, headers=headers)
job_id = response.json()["job_id"] job_id = response.json()["job_id"]
status_response = client.get(f"/remix/{job_id}") status_response = client.get(f"/remix/{job_id}", headers=headers)
body = status_response.json() body = status_response.json()
assert body["status"] == "done" assert body["status"] == "done"
assert body["library_song_id"] == 123 assert body["library_song_id"] == 123
assert body["post_id"] == 456 assert body["post_id"] == 456
def test_remix_status_404_for_unknown_job(client): def test_remix_status_404_for_unknown_job(client, auth_as):
response = client.get("/remix/999999") headers, _ = auth_as()
response = client.get("/remix/999999", headers=headers)
assert response.status_code == 404
def test_remix_status_404_for_another_users_job(client, auth_as, monkeypatch):
# IDOR check: a valid, existing job id isn't enough if it belongs to someone else -
# previously any sequential id worked for anyone.
owner_headers, _ = auth_as()
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
create_response = client.post("/remix", data={"prompt": "test"}, files=files, headers=owner_headers)
job_id = create_response.json()["job_id"]
other_headers, _ = auth_as()
response = client.get(f"/remix/{job_id}", headers=other_headers)
assert response.status_code == 404 assert response.status_code == 404
This diff is collapsed.
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