Commit ab7b741e authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Stream audio directly instead of downloading the whole file first

Every stream endpoint (library, soundmarks, posts, live-location, rooms)
only accepted the access token via an Authorization header - fine for
apiFetch, but <audio src="..."> can't send custom headers, so the frontend
was fetching the entire file as a blob before playback could even start
(no progressive playback, no seeking). Added
get_current_user_for_stream, which accepts the token as a ?token= query
param too (same reasoning as the Rooms websocket fix), and switched all
five stream endpoints to it. FileResponse already supports Range requests
natively, so a direct <audio src> now gets real 206 Partial Content
responses - confirmed live (curl -H "Range: ..." against
/library/stream/1?token=...).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 913721b5
Pipeline #1085 passed with stage
in 3 minutes and 16 seconds
...@@ -5,7 +5,7 @@ from pydantic import BaseModel ...@@ -5,7 +5,7 @@ from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack, User from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack, User
from src.core.security import get_current_user from src.core.security import get_current_user, get_current_user_for_stream
router = APIRouter(tags=["Library & Playlists"]) router = APIRouter(tags=["Library & Playlists"])
...@@ -18,7 +18,7 @@ async def get_library(db: Session = Depends(get_db), current_user: User = Depend ...@@ -18,7 +18,7 @@ async def get_library(db: Session = Depends(get_db), current_user: User = Depend
return {"status": "success", "library": songs} return {"status": "success", "library": songs}
@router.get("/library/stream/{file_id}") @router.get("/library/stream/{file_id}")
async def stream_audio(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def stream_audio(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id, LibrarySong.user_id == current_user.id).first() song = db.query(LibrarySong).filter(LibrarySong.id == file_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=404, detail="Audio file not found") raise HTTPException(status_code=404, detail="Audio file 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, decode_token from src.core.security import get_current_user, get_current_user_for_stream, 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
...@@ -137,7 +137,7 @@ def get_remix_tree(post_id: int, db: Session = Depends(get_db), current_user: Us ...@@ -137,7 +137,7 @@ def get_remix_tree(post_id: int, db: Session = Depends(get_db), current_user: Us
@router.get("/posts/{post_id}/stream") @router.get("/posts/{post_id}/stream")
def stream_post_song(post_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def stream_post_song(post_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
"""Streams a post's song regardless of who uploaded it - a post's song_id isn't """Streams a post's song regardless of who uploaded it - a post's song_id isn't
necessarily the poster's own library song, same not-scoped-to-caller reasoning as the necessarily the poster's own library song, same not-scoped-to-caller reasoning as the
other social stream endpoints (rooms, geo-drop, soundmarks).""" other social stream endpoints (rooms, geo-drop, soundmarks)."""
...@@ -222,7 +222,7 @@ def get_nearby_listeners( ...@@ -222,7 +222,7 @@ def get_nearby_listeners(
@router.get("/live-location/{user_id}/stream") @router.get("/live-location/{user_id}/stream")
def stream_live_location_song(user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def stream_live_location_song(user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
"""Streams whatever a nearby user is currently playing, regardless of who uploaded it - """Streams whatever a nearby user is currently playing, regardless of who uploaded it -
same not-scoped-to-caller reasoning as the other social stream endpoints.""" same not-scoped-to-caller reasoning as the other social stream endpoints."""
loc = db.query(LiveLocation).filter(LiveLocation.user_id == user_id).first() loc = db.query(LiveLocation).filter(LiveLocation.user_id == user_id).first()
...@@ -251,7 +251,7 @@ def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends ...@@ -251,7 +251,7 @@ def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends
@router.get("/rooms/{room_id}/stream") @router.get("/rooms/{room_id}/stream")
def stream_room_song(room_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def stream_room_song(room_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
"""Streams whatever's currently playing in a room, regardless of who uploaded the """Streams whatever's currently playing in a room, regardless of who uploaded the
underlying LibrarySong - shared social content by design (see the top-of-file note), underlying LibrarySong - shared social content by design (see the top-of-file note),
mirroring /soundmarks/{id}/stream's same not-scoped-to-caller reasoning.""" mirroring /soundmarks/{id}/stream's same not-scoped-to-caller reasoning."""
......
...@@ -20,7 +20,7 @@ from src.core.database import ( ...@@ -20,7 +20,7 @@ from src.core.database import (
SoundmarkSuggestion, SoundmarkSuggestion,
User, User,
) )
from src.core.security import get_current_business_admin, get_current_super_admin, get_current_user, is_super_admin from src.core.security import get_current_business_admin, get_current_super_admin, get_current_user, get_current_user_for_stream, is_super_admin
router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"]) router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"])
...@@ -618,7 +618,7 @@ def delete_soundmark( ...@@ -618,7 +618,7 @@ def delete_soundmark(
@router.get("/{soundmark_id}/stream") @router.get("/{soundmark_id}/stream")
def stream_soundmark_anthem( def stream_soundmark_anthem(
soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)
): ):
"""Streams a soundmark's current anthem regardless of which user originally uploaded the """Streams a soundmark's current anthem regardless of which user originally uploaded the
underlying LibrarySong - unlike /library/stream/{id}, this is deliberately not scoped to underlying LibrarySong - unlike /library/stream/{id}, this is deliberately not scoped to
......
...@@ -2,6 +2,7 @@ import hashlib ...@@ -2,6 +2,7 @@ import hashlib
import hmac import hmac
import os import os
import uuid import uuid
from typing import Optional
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
import jwt import jwt
...@@ -89,6 +90,30 @@ def get_current_user( ...@@ -89,6 +90,30 @@ def get_current_user(
return user return user
def get_current_user_for_stream(
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
token: Optional[str] = None,
db: Session = Depends(get_db),
) -> User:
"""Same identity check as get_current_user, but also accepts the access token as a `token`
query param - a plain <audio src="..."> can't send a custom Authorization header (browsers
don't attach one to media element requests), so it has to travel in the URL instead for
direct streaming to work at all. Same reasoning as the Rooms websocket's ?token= (see
room_websocket in social.py) - browsers just can't set headers on these requests. Only use
this on GET endpoints that serve media directly to an <audio>/<img> tag, not on anything
that also accepts a request body or does a mutation - a token in a URL can end up in
server access logs or browser history, an acceptable tradeoff for read-only streaming but
not for anything else."""
raw_token = credentials.credentials if credentials else token
if not raw_token:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
payload = decode_token(raw_token, expected_type="access")
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")
return user
def is_super_admin(user: User) -> bool: def is_super_admin(user: User) -> bool:
return user.role == "super_admin" return user.role == "super_admin"
......
...@@ -83,6 +83,30 @@ def test_library_stream_success(client, db_session, auth_as): ...@@ -83,6 +83,30 @@ def test_library_stream_success(client, db_session, auth_as):
os.remove(path) os.remove(path)
def test_library_stream_accepts_token_query_param(client, db_session, auth_as):
# <audio src="..."> can't send a custom Authorization header, so streaming endpoints
# also accept the access token as a query param instead.
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id)
try:
raw_token = headers["Authorization"].split(" ", 1)[1]
response = client.get(f"/library/stream/{song.id}?token={raw_token}")
assert response.status_code == 200
assert response.content == b"fake mp3 bytes for stream test"
finally:
os.remove(path)
def test_library_stream_requires_auth(client, db_session, auth_as):
_, user = auth_as()
song, path = _make_library_song(db_session, user.id)
try:
response = client.get(f"/library/stream/{song.id}")
assert response.status_code == 401
finally:
os.remove(path)
def test_library_stream_not_found_for_other_users_song(client, db_session, auth_as): def test_library_stream_not_found_for_other_users_song(client, db_session, auth_as):
headers_a, user_a = auth_as() headers_a, user_a = auth_as()
headers_b, user_b = auth_as() headers_b, user_b = auth_as()
......
...@@ -331,6 +331,17 @@ def test_stream_post_song_works_regardless_of_who_uploaded_it(client, auth_as): ...@@ -331,6 +331,17 @@ def test_stream_post_song_works_regardless_of_who_uploaded_it(client, auth_as):
assert response.content == b"fake mp3 bytes" assert response.content == b"fake mp3 bytes"
def test_stream_post_song_accepts_token_query_param(client, auth_as):
# <audio src="..."> can't send a custom Authorization header.
song_id = _make_library_song(user_id=999) # uploaded by someone else entirely
headers, _ = auth_as()
post_id = client.post("/social/posts", json={"song_id": song_id, "caption": "x"}, headers=headers).json()["id"]
raw_token = headers["Authorization"].split(" ", 1)[1]
response = client.get(f"/social/posts/{post_id}/stream?token={raw_token}")
assert response.status_code == 200
def test_stream_post_song_404s_for_unknown_post(client, auth_as): def test_stream_post_song_404s_for_unknown_post(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
response = client.get("/social/posts/999999/stream", headers=headers) response = client.get("/social/posts/999999/stream", headers=headers)
......
...@@ -538,6 +538,21 @@ def test_stream_soundmark_anthem_works_regardless_of_song_owner(client, db_sessi ...@@ -538,6 +538,21 @@ def test_stream_soundmark_anthem_works_regardless_of_song_owner(client, db_sessi
os.remove(path) os.remove(path)
def test_stream_soundmark_anthem_accepts_token_query_param(client, db_session, auth_as):
# <audio src="..."> can't send a custom Authorization header.
listener_headers, _ = auth_as()
_, uploader = auth_as()
song, path = _make_library_song(db_session, uploader.id)
sm = _make_soundmark(db_session, tier="major", song_id=song.id)
try:
raw_token = listener_headers["Authorization"].split(" ", 1)[1]
response = client.get(f"/soundmarks/{sm.id}/stream?token={raw_token}")
assert response.status_code == 200
finally:
os.remove(path)
def test_stream_soundmark_with_no_anthem_404s(client, db_session, auth_as): def test_stream_soundmark_with_no_anthem_404s(client, db_session, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
sm = _make_soundmark(db_session, tier="major", song_id=None) sm = _make_soundmark(db_session, tier="major", song_id=None)
......
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