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)
response = client.post("/remix", data={"prompt": "remix this", "library_song_ids": "999999"}, headers=headers)
assert response.status_code == 400
def test_remix_rejects_another_users_library_song_id(client, auth_as, monkeypatch):
# 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) 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": str(song_id)}, headers=headers)
assert response.status_code == 400 assert response.status_code == 400
finally:
os.remove(path)
def test_remix_mixes_library_songs_and_uploads(client, monkeypatch): def test_remix_mixes_library_songs_and_uploads(client, auth_as, monkeypatch):
song_id, path = _make_library_song(title="From Library") 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
...@@ -4,7 +4,7 @@ import tempfile ...@@ -4,7 +4,7 @@ import tempfile
from src.core.database import LibrarySong, LiveRoom, SessionLocal from src.core.database import LibrarySong, LiveRoom, SessionLocal
def _make_room(dj_id=1, name="Test Room"): def _make_room(dj_id, name="Test Room"):
db = SessionLocal() db = SessionLocal()
try: try:
room = LiveRoom(dj_id=dj_id, name=name, is_active=True) room = LiveRoom(dj_id=dj_id, name=name, is_active=True)
...@@ -16,7 +16,7 @@ def _make_room(dj_id=1, name="Test Room"): ...@@ -16,7 +16,7 @@ def _make_room(dj_id=1, name="Test Room"):
db.close() db.close()
def _make_library_song(user_id=1, **overrides): def _make_library_song(user_id, **overrides):
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp") fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f: with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes for room stream test") f.write(b"fake mp3 bytes for room stream test")
...@@ -33,39 +33,78 @@ def _make_library_song(user_id=1, **overrides): ...@@ -33,39 +33,78 @@ def _make_library_song(user_id=1, **overrides):
db.close() db.close()
def test_websocket_closes_for_unknown_room(client): def _token(headers):
return headers["Authorization"].split(" ", 1)[1]
def test_websocket_rejects_missing_token(client):
from starlette.websockets import WebSocketDisconnect from starlette.websockets import WebSocketDisconnect
import pytest import pytest
room_id = _make_room(dj_id=1)
with pytest.raises(WebSocketDisconnect): with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/social/rooms/999999/ws?user_id=1"): with client.websocket_connect(f"/social/rooms/{room_id}/ws"):
pass pass
def test_websocket_snapshot_on_connect(client): def test_websocket_rejects_invalid_token(client):
from starlette.websockets import WebSocketDisconnect
import pytest
room_id = _make_room(dj_id=1) room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws: with pytest.raises(WebSocketDisconnect):
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token=not-a-real-token"):
pass
def test_websocket_ignores_a_client_supplied_user_id_and_uses_the_token(client, auth_as):
# Regression check for the original hole: user_id used to be a trusted, unauthenticated
# query param. Now there's no such param at all - even if one is still sent, the server
# only ever trusts who the token says you are.
headers, real_user = auth_as()
room_id = _make_room(dj_id=real_user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}&user_id=999999") as ws:
snapshot = ws.receive_json()
assert snapshot["presence"] == [real_user.id]
def test_websocket_closes_for_unknown_room(client, auth_as):
from starlette.websockets import WebSocketDisconnect
import pytest
headers, _ = auth_as()
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect(f"/social/rooms/999999/ws?token={_token(headers)}"):
pass
def test_websocket_snapshot_on_connect(client, auth_as):
headers, user = auth_as()
room_id = _make_room(dj_id=user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}") as ws:
snapshot = ws.receive_json() snapshot = ws.receive_json()
assert snapshot["type"] == "snapshot" assert snapshot["type"] == "snapshot"
assert snapshot["dj_id"] == 1 assert snapshot["dj_id"] == user.id
assert snapshot["presence"] == [1] assert snapshot["presence"] == [user.id]
assert snapshot["chat_history"] == [] assert snapshot["chat_history"] == []
assert snapshot["fire_count"] == 0 assert snapshot["fire_count"] == 0
assert snapshot["dj_queue"] == [] assert snapshot["dj_queue"] == []
def test_websocket_broadcasts_chat_between_clients(client): def test_websocket_broadcasts_chat_between_clients(client, auth_as):
room_id = _make_room(dj_id=1) headers1, user1 = auth_as()
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws1: headers2, user2 = auth_as()
room_id = _make_room(dj_id=user1.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers1)}") as ws1:
ws1.receive_json() # snapshot ws1.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws2: with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers2)}") as ws2:
ws2.receive_json() # snapshot ws2.receive_json() # snapshot
joined = ws1.receive_json() joined = ws1.receive_json()
assert joined == {"type": "user_joined", "user_id": 2} assert joined == {"type": "user_joined", "user_id": user2.id}
ws2.send_json({"type": "chat", "text": "hey everyone"}) ws2.send_json({"type": "chat", "text": "hey everyone"})
chat_on_ws1 = ws1.receive_json() chat_on_ws1 = ws1.receive_json()
assert chat_on_ws1 == {"type": "chat", "user_id": 2, "text": "hey everyone"} assert chat_on_ws1 == {"type": "chat", "user_id": user2.id, "text": "hey everyone"}
# Broadcasts (chat/reactions) intentionally include the sender too - simpler, # Broadcasts (chat/reactions) intentionally include the sender too - simpler,
# more predictable than an asymmetric "everyone except me" rule, and clients # more predictable than an asymmetric "everyone except me" rule, and clients
...@@ -73,12 +112,13 @@ def test_websocket_broadcasts_chat_between_clients(client): ...@@ -73,12 +112,13 @@ def test_websocket_broadcasts_chat_between_clients(client):
# This bit a manual live-server test script during development (it assumed # This bit a manual live-server test script during development (it assumed
# sender exclusion and read messages out of order) - locking it in explicitly. # sender exclusion and read messages out of order) - locking it in explicitly.
chat_echoed_to_sender = ws2.receive_json() chat_echoed_to_sender = ws2.receive_json()
assert chat_echoed_to_sender == {"type": "chat", "user_id": 2, "text": "hey everyone"} assert chat_echoed_to_sender == {"type": "chat", "user_id": user2.id, "text": "hey everyone"}
def test_websocket_reaction_increments_fire_count(client): def test_websocket_reaction_increments_fire_count(client, auth_as):
room_id = _make_room(dj_id=1) headers, user = auth_as()
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws: room_id = _make_room(dj_id=user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}") as ws:
ws.receive_json() # snapshot ws.receive_json() # snapshot
ws.send_json({"type": "reaction", "emoji": "🔥"}) ws.send_json({"type": "reaction", "emoji": "🔥"})
reaction = ws.receive_json() reaction = ws.receive_json()
...@@ -87,48 +127,53 @@ def test_websocket_reaction_increments_fire_count(client): ...@@ -87,48 +127,53 @@ def test_websocket_reaction_increments_fire_count(client):
assert reaction["fire_count"] == 1 assert reaction["fire_count"] == 1
def test_websocket_dj_handoff_flow(client): def test_websocket_dj_handoff_flow(client, auth_as):
room_id = _make_room(dj_id=1) dj_headers, dj_user = auth_as()
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws: listener_headers, listener_user = auth_as()
room_id = _make_room(dj_id=dj_user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(dj_headers)}") as dj_ws:
dj_ws.receive_json() # snapshot dj_ws.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as listener_ws: with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(listener_headers)}") as listener_ws:
listener_ws.receive_json() # snapshot listener_ws.receive_json() # snapshot
dj_ws.receive_json() # user_joined for user 2 dj_ws.receive_json() # user_joined for the listener
listener_ws.send_json({"type": "request_aux"}) listener_ws.send_json({"type": "request_aux"})
queue_update_on_listener = listener_ws.receive_json() queue_update_on_listener = listener_ws.receive_json()
queue_update_on_dj = dj_ws.receive_json() queue_update_on_dj = dj_ws.receive_json()
assert queue_update_on_listener == {"type": "queue_updated", "dj_queue": [2]} assert queue_update_on_listener == {"type": "queue_updated", "dj_queue": [listener_user.id]}
assert queue_update_on_dj == {"type": "queue_updated", "dj_queue": [2]} assert queue_update_on_dj == {"type": "queue_updated", "dj_queue": [listener_user.id]}
dj_ws.send_json({"type": "pass_aux"}) dj_ws.send_json({"type": "pass_aux"})
dj_changed_on_dj = dj_ws.receive_json() dj_changed_on_dj = dj_ws.receive_json()
dj_changed_on_listener = listener_ws.receive_json() dj_changed_on_listener = listener_ws.receive_json()
assert dj_changed_on_dj == {"type": "dj_changed", "dj_id": 2, "dj_queue": []} assert dj_changed_on_dj == {"type": "dj_changed", "dj_id": listener_user.id, "dj_queue": []}
assert dj_changed_on_listener == {"type": "dj_changed", "dj_id": 2, "dj_queue": []} assert dj_changed_on_listener == {"type": "dj_changed", "dj_id": listener_user.id, "dj_queue": []}
db = SessionLocal() db = SessionLocal()
try: try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first() room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
assert room.dj_id == 2 assert room.dj_id == listener_user.id
finally: finally:
db.close() db.close()
def test_websocket_only_dj_can_pass_aux(client): def test_websocket_only_dj_can_pass_aux(client, auth_as):
room_id = _make_room(dj_id=1) dj_headers, dj_user = auth_as()
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws: headers, _ = auth_as()
room_id = _make_room(dj_id=dj_user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}") as ws:
ws.receive_json() # snapshot ws.receive_json() # snapshot
ws.send_json({"type": "pass_aux"}) ws.send_json({"type": "pass_aux"})
error = ws.receive_json() error = ws.receive_json()
assert error == {"type": "error", "detail": "Only the current DJ can pass the aux."} assert error == {"type": "error", "detail": "Only the current DJ can pass the aux."}
def test_websocket_only_dj_can_set_now_playing(client): def test_websocket_only_dj_can_set_now_playing(client, auth_as):
song_id, path = _make_library_song() dj_headers, dj_user = auth_as()
song_id, path = _make_library_song(user_id=dj_user.id)
try: try:
room_id = _make_room(dj_id=1) room_id = _make_room(dj_id=dj_user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws: with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(dj_headers)}") as dj_ws:
dj_ws.receive_json() # snapshot dj_ws.receive_json() # snapshot
dj_ws.send_json({"type": "now_playing", "song_id": song_id}) dj_ws.send_json({"type": "now_playing", "song_id": song_id})
update = dj_ws.receive_json() update = dj_ws.receive_json()
...@@ -136,7 +181,7 @@ def test_websocket_only_dj_can_set_now_playing(client): ...@@ -136,7 +181,7 @@ def test_websocket_only_dj_can_set_now_playing(client):
"type": "now_playing_changed", "type": "now_playing_changed",
"song_id": song_id, "song_id": song_id,
"song": {"id": song_id, "title": "Test Anthem", "artist": "Test Artist", "album": "Test Album", "coverart": None}, "song": {"id": song_id, "title": "Test Anthem", "artist": "Test Artist", "album": "Test Album", "coverart": None},
"dj_id": 1, "dj_id": dj_user.id,
} }
db = SessionLocal() db = SessionLocal()
...@@ -149,34 +194,39 @@ def test_websocket_only_dj_can_set_now_playing(client): ...@@ -149,34 +194,39 @@ def test_websocket_only_dj_can_set_now_playing(client):
os.remove(path) os.remove(path)
def test_websocket_now_playing_rejects_a_song_that_does_not_exist(client): def test_websocket_now_playing_rejects_a_song_that_does_not_exist(client, auth_as):
room_id = _make_room(dj_id=1) headers, user = auth_as()
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws: room_id = _make_room(dj_id=user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}") as dj_ws:
dj_ws.receive_json() # snapshot dj_ws.receive_json() # snapshot
dj_ws.send_json({"type": "now_playing", "song_id": 999999}) dj_ws.send_json({"type": "now_playing", "song_id": 999999})
error = dj_ws.receive_json() error = dj_ws.receive_json()
assert error == {"type": "error", "detail": "That song no longer exists."} assert error == {"type": "error", "detail": "That song no longer exists."}
def test_websocket_non_dj_cannot_set_now_playing(client): def test_websocket_non_dj_cannot_set_now_playing(client, auth_as):
room_id = _make_room(dj_id=1) dj_headers, dj_user = auth_as()
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as listener_ws: headers, _ = auth_as()
room_id = _make_room(dj_id=dj_user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}") as listener_ws:
listener_ws.receive_json() # snapshot listener_ws.receive_json() # snapshot
listener_ws.send_json({"type": "now_playing", "song_id": 1}) listener_ws.send_json({"type": "now_playing", "song_id": 1})
error = listener_ws.receive_json() error = listener_ws.receive_json()
assert error == {"type": "error", "detail": "Only the current DJ can change what's playing."} assert error == {"type": "error", "detail": "Only the current DJ can change what's playing."}
def test_websocket_snapshot_includes_current_song_once_playing(client): def test_websocket_snapshot_includes_current_song_once_playing(client, auth_as):
song_id, path = _make_library_song() dj_headers, dj_user = auth_as()
listener_headers, _ = auth_as()
song_id, path = _make_library_song(user_id=dj_user.id)
try: try:
room_id = _make_room(dj_id=1) room_id = _make_room(dj_id=dj_user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws: with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(dj_headers)}") as dj_ws:
dj_ws.receive_json() # snapshot dj_ws.receive_json() # snapshot
dj_ws.send_json({"type": "now_playing", "song_id": song_id}) dj_ws.send_json({"type": "now_playing", "song_id": song_id})
dj_ws.receive_json() # now_playing_changed dj_ws.receive_json() # now_playing_changed
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as listener_ws: with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(listener_headers)}") as listener_ws:
snapshot = listener_ws.receive_json() snapshot = listener_ws.receive_json()
assert snapshot["current_song_id"] == song_id assert snapshot["current_song_id"] == song_id
assert snapshot["current_song"]["title"] == "Test Anthem" assert snapshot["current_song"]["title"] == "Test Anthem"
...@@ -185,9 +235,10 @@ def test_websocket_snapshot_includes_current_song_once_playing(client): ...@@ -185,9 +235,10 @@ def test_websocket_snapshot_includes_current_song_once_playing(client):
def test_stream_room_song_works_regardless_of_who_uploaded_it(client, auth_as): def test_stream_room_song_works_regardless_of_who_uploaded_it(client, auth_as):
song_id, path = _make_library_song(user_id=999) # uploaded by someone else entirely _, other_user = auth_as()
song_id, path = _make_library_song(user_id=other_user.id) # uploaded by someone else entirely
try: try:
room_id = _make_room(dj_id=1) room_id = _make_room(dj_id=other_user.id)
db = SessionLocal() db = SessionLocal()
try: try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first() room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
...@@ -205,8 +256,8 @@ def test_stream_room_song_works_regardless_of_who_uploaded_it(client, auth_as): ...@@ -205,8 +256,8 @@ def test_stream_room_song_works_regardless_of_who_uploaded_it(client, auth_as):
def test_stream_room_song_404s_when_nothing_is_playing(client, auth_as): def test_stream_room_song_404s_when_nothing_is_playing(client, auth_as):
room_id = _make_room(dj_id=1) headers, user = auth_as()
headers, _ = auth_as() room_id = _make_room(dj_id=user.id)
response = client.get(f"/social/rooms/{room_id}/stream", headers=headers) response = client.get(f"/social/rooms/{room_id}/stream", headers=headers)
assert response.status_code == 404 assert response.status_code == 404
...@@ -217,13 +268,15 @@ def test_stream_room_song_404s_for_unknown_room(client, auth_as): ...@@ -217,13 +268,15 @@ def test_stream_room_song_404s_for_unknown_room(client, auth_as):
assert response.status_code == 404 assert response.status_code == 404
def test_websocket_user_left_broadcast_on_disconnect(client): def test_websocket_user_left_broadcast_on_disconnect(client, auth_as):
room_id = _make_room(dj_id=1) headers1, user1 = auth_as()
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws1: headers2, user2 = auth_as()
room_id = _make_room(dj_id=user1.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers1)}") as ws1:
ws1.receive_json() # snapshot ws1.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws2: with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers2)}") as ws2:
ws2.receive_json() # snapshot ws2.receive_json() # snapshot
ws1.receive_json() # user_joined ws1.receive_json() # user_joined
left = ws1.receive_json() left = ws1.receive_json()
assert left == {"type": "user_left", "user_id": 2} assert left == {"type": "user_left", "user_id": user2.id}
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