Commit 7baf7ba5 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add real invite code, PIN, and location discovery to Rooms

Rooms were open-join-by-id only with no geo features, despite that being the
intended design. Generates a unique invite code server-side on every create,
adds an optional PIN (hashed like account passwords, rate-limited on guesses
via a third reuse of AuthAttempt) gating join/stream/websocket alike, and adds
optional lat/lon with a haversine-sorted nearby lookup (haversine itself
extracted to a shared geo service once a second caller needed it).
parent f05e01b4
Pipeline #1222 failed with stage
in 3 minutes and 41 seconds
"""add invite code, PIN, and location to rooms
Revision ID: c3a7e5f91b04
Revises: b1f4a0d7e3c2
Create Date: 2026-10-12 13:05:00.000000
"""
import secrets
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'c3a7e5f91b04'
down_revision: Union[str, Sequence[str], None] = 'b1f4a0d7e3c2'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
# No 0/O or 1/I - avoids ambiguity when a code is read aloud or typed from a photo.
INVITE_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
INVITE_CODE_LENGTH = 7
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('live_rooms', sa.Column('invite_code', sa.String(), nullable=True))
op.add_column('live_rooms', sa.Column('pin_hash', sa.String(), nullable=True))
op.add_column('live_rooms', sa.Column('latitude', sa.Float(), nullable=True))
op.add_column('live_rooms', sa.Column('longitude', sa.Float(), nullable=True))
# Every pre-existing room needs a real, unique invite_code before the unique index below
# can be created - SQLite can't generate random unique strings in SQL, so this loops in
# Python instead, same spirit as any other data-backfill migration in this project.
conn = op.get_bind()
existing_ids = conn.execute(sa.text("SELECT id FROM live_rooms")).fetchall()
used = set()
for (room_id,) in existing_ids:
while True:
code = "".join(secrets.choice(INVITE_CODE_ALPHABET) for _ in range(INVITE_CODE_LENGTH))
if code not in used:
used.add(code)
break
conn.execute(sa.text("UPDATE live_rooms SET invite_code = :code WHERE id = :id"), {"code": code, "id": room_id})
op.create_index(op.f('ix_live_rooms_invite_code'), 'live_rooms', ['invite_code'], unique=True)
op.add_column('auth_attempts', sa.Column('room_id', sa.Integer(), nullable=True))
op.create_index(op.f('ix_auth_attempts_room_id'), 'auth_attempts', ['room_id'])
op.add_column('auth_attempts', sa.Column('user_id', sa.Integer(), nullable=True))
op.create_index(op.f('ix_auth_attempts_user_id'), 'auth_attempts', ['user_id'])
def downgrade() -> None:
"""Downgrade schema."""
op.drop_index(op.f('ix_auth_attempts_user_id'), table_name='auth_attempts')
op.drop_column('auth_attempts', 'user_id')
op.drop_index(op.f('ix_auth_attempts_room_id'), table_name='auth_attempts')
op.drop_column('auth_attempts', 'room_id')
op.drop_index(op.f('ix_live_rooms_invite_code'), table_name='live_rooms')
op.drop_column('live_rooms', 'longitude')
op.drop_column('live_rooms', 'latitude')
op.drop_column('live_rooms', 'pin_hash')
op.drop_column('live_rooms', 'invite_code')
import os import os
import secrets
import time import time
from typing import Optional from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Request, WebSocket, WebSocketDisconnect, status from fastapi import APIRouter, Depends, HTTPException, Request, WebSocket, WebSocketDisconnect, status
from pydantic import BaseModel from pydantic import BaseModel, Field
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, SessionLocal, User, Post, LiveLocation, LibrarySong, LiveRoom, RoomMessage, UserProfile from src.core.database import get_db, SessionLocal, User, Post, LiveLocation, LibrarySong, LiveRoom, RoomMessage, UserProfile, AuthAttempt
from src.core.security import get_current_user, get_current_user_for_stream, user_id_from_ws_token from src.core.security import get_current_user, get_current_user_for_stream, hash_password, user_id_from_ws_token, verify_password
from src.services.geo import haversine_meters
from src.services.room_manager import room_manager from src.services.room_manager import room_manager
from src.services.media_stream import stream_audio_file from src.services.media_stream import stream_audio_file
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
import math
router = APIRouter( router = APIRouter(
prefix="/social", prefix="/social",
...@@ -31,6 +32,25 @@ class LiveLocationUpdate(BaseModel): ...@@ -31,6 +32,25 @@ class LiveLocationUpdate(BaseModel):
class LiveRoomCreate(BaseModel): class LiveRoomCreate(BaseModel):
name: str name: str
pin: Optional[str] = Field(None, regex=r'^\d{4}$')
latitude: Optional[float] = None
longitude: Optional[float] = None
class LiveRoomUpdate(BaseModel):
"""Partial update - all fields optional. pin: "" clears an existing PIN, a 4-digit string
sets/replaces one, omitted leaves it untouched - same "empty clears" convention as the
admin user-management suspend_hours field (soundmarks.py)."""
name: Optional[str] = None
pin: Optional[str] = Field(None, regex=r'^\d{4}$|^$')
latitude: Optional[float] = None
longitude: Optional[float] = None
class RoomJoinRequest(BaseModel):
room_id: Optional[int] = None
invite_code: Optional[str] = None
pin: Optional[str] = None
# --- Serialization helpers --- # --- Serialization helpers ---
# Posts/drops/rooms only ever store song_id/user_id - every response enriches those into real # Posts/drops/rooms only ever store song_id/user_id - every response enriches those into real
...@@ -59,6 +79,24 @@ def _serialize_post(post: Post, db: Session, remix_count: int = None) -> dict: ...@@ -59,6 +79,24 @@ def _serialize_post(post: Post, db: Session, remix_count: int = None) -> dict:
return result return result
def _serialize_room(room: LiveRoom, viewer_id: int) -> dict:
"""invite_code is only ever handed back to the room's own creator - it's the credential
that bypasses the PIN check below, so showing it to anyone else would defeat the PIN
entirely. Everyone else just gets has_pin, enough to know a PIN step is needed."""
return {
"id": room.id,
"dj_id": room.dj_id,
"current_song_id": room.current_song_id,
"name": room.name,
"is_active": room.is_active,
"has_pin": room.pin_hash is not None,
"invite_code": room.invite_code if room.dj_id == viewer_id else None,
"latitude": room.latitude,
"longitude": room.longitude,
"created_at": room.created_at,
}
def _serialize_live_location(loc: LiveLocation, db: Session) -> dict: def _serialize_live_location(loc: LiveLocation, db: Session) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == loc.song_id).first() if loc.song_id else None song = db.query(LibrarySong).filter(LibrarySong.id == loc.song_id).first() if loc.song_id else None
author = db.query(User).filter(User.id == loc.user_id).first() author = db.query(User).filter(User.id == loc.user_id).first()
...@@ -218,19 +256,9 @@ def get_nearby_listeners( ...@@ -218,19 +256,9 @@ def get_nearby_listeners(
.all() .all()
) )
nearby = [] nearby = []
def haversine(lat1, lon1, lat2, lon2):
R = 6371.0 # Earth radius in kilometers
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
for loc in all_locations: for loc in all_locations:
if loc.latitude and loc.longitude: if loc.latitude and loc.longitude:
dist = haversine(lat, lon, loc.latitude, loc.longitude) dist = haversine_meters(lat, lon, loc.latitude, loc.longitude) / 1000.0
if dist <= radius_km: if dist <= radius_km:
nearby.append({"listener": _serialize_live_location(loc, db), "distance_km": dist}) nearby.append({"listener": _serialize_live_location(loc, db), "distance_km": dist})
...@@ -254,28 +282,173 @@ def stream_live_location_song(user_id: int, request: Request, db: Session = Depe ...@@ -254,28 +282,173 @@ def stream_live_location_song(user_id: int, request: Request, db: Session = Depe
return stream_audio_file(song.file_path, request) return stream_audio_file(song.file_path, request)
# No 0/O or 1/I - avoids ambiguity when a code is read aloud or typed from a photo.
INVITE_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
INVITE_CODE_LENGTH = 7
# A 4-digit PIN only has 10,000 possibilities - rate limiting is the only thing standing
# between that and a trivial brute force, same reasoning as login's own rate limit below.
PIN_ATTEMPTS_WINDOW = timedelta(minutes=15)
MAX_PIN_ATTEMPTS_PER_ROOM_USER = 10
MAX_PIN_ATTEMPTS_PER_ROOM_IP = 20
def _generate_invite_code(db: Session) -> str:
while True:
code = "".join(secrets.choice(INVITE_CODE_ALPHABET) for _ in range(INVITE_CODE_LENGTH))
if not db.query(LiveRoom).filter(LiveRoom.invite_code == code).first():
return code
def _check_room_pin_rate_limit(db: Session, room_id: int, user_id: int, ip: str):
now = datetime.now(timezone.utc)
user_count = (
db.query(AuthAttempt)
.filter(AuthAttempt.room_id == room_id, AuthAttempt.user_id == user_id, AuthAttempt.created_at >= now - PIN_ATTEMPTS_WINDOW)
.count()
)
if user_count >= MAX_PIN_ATTEMPTS_PER_ROOM_USER:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many PIN attempts for this room, try again later")
# Scoped to this room's rows only, same independence reasoning as every other use of this
# shared table - stops one IP from brute-forcing across several accounts against one room.
ip_count = (
db.query(AuthAttempt)
.filter(AuthAttempt.room_id == room_id, AuthAttempt.ip_address == ip, AuthAttempt.created_at >= now - PIN_ATTEMPTS_WINDOW)
.count()
)
if ip_count >= MAX_PIN_ATTEMPTS_PER_ROOM_IP:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many PIN attempts from this address, try again later")
def _verify_room_pin(db: Session, room: LiveRoom, pin: Optional[str], user_id: int, ip: str) -> None:
"""No-op if the room has no PIN set. Every attempt (right or wrong) is logged before the
check so rate limiting can't be bypassed by only counting failures."""
if room.pin_hash is None:
return
_check_room_pin_rate_limit(db, room.id, user_id, ip)
db.add(AuthAttempt(room_id=room.id, user_id=user_id, ip_address=ip))
db.commit()
if not pin or not verify_password(pin, room.pin_hash):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Incorrect PIN")
def _client_ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
@router.post("/rooms", status_code=status.HTTP_201_CREATED) @router.post("/rooms", status_code=status.HTTP_201_CREATED)
def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_room = LiveRoom(dj_id=current_user.id, **room.dict()) db_room = LiveRoom(
dj_id=current_user.id,
name=room.name,
latitude=room.latitude,
longitude=room.longitude,
invite_code=_generate_invite_code(db),
pin_hash=hash_password(room.pin) if room.pin else None,
)
db.add(db_room) db.add(db_room)
db.commit() db.commit()
db.refresh(db_room) db.refresh(db_room)
return db_room return _serialize_room(db_room, current_user.id)
@router.get("/rooms") @router.get("/rooms")
def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all() rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all()
return rooms return [_serialize_room(r, current_user.id) for r in rooms]
@router.patch("/rooms/{room_id}")
def update_live_room(
room_id: int, body: LiveRoomUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
if not room:
raise HTTPException(status_code=404, detail="Room not found")
if room.dj_id != current_user.id:
raise HTTPException(status_code=403, detail="Only the room's creator can edit it")
data = body.dict(exclude_unset=True)
if "name" in data:
room.name = data["name"]
if "latitude" in data:
room.latitude = data["latitude"]
if "longitude" in data:
room.longitude = data["longitude"]
if "pin" in data:
room.pin_hash = None if data["pin"] == "" else hash_password(data["pin"])
db.commit()
db.refresh(room)
return _serialize_room(room, current_user.id)
@router.get("/rooms/by-code/{invite_code}")
def get_room_by_code(invite_code: str, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
room = db.query(LiveRoom).filter(LiveRoom.invite_code == invite_code, LiveRoom.is_active == True).first()
if not room:
raise HTTPException(status_code=404, detail="Room not found")
return _serialize_room(room, current_user.id)
@router.post("/rooms/join")
def join_live_room(
body: RoomJoinRequest, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
"""The real gate for both the numeric-id and invite-code join paths - verifies the PIN (if
any) before handing back the room, same check GET /rooms/{id}/stream and the websocket
both also enforce, so there's no bare-id/bare-code path around a set PIN."""
if (body.room_id is None) == (body.invite_code is None):
raise HTTPException(status_code=422, detail="Provide exactly one of room_id or invite_code")
query = db.query(LiveRoom).filter(LiveRoom.is_active == True)
room = (
query.filter(LiveRoom.id == body.room_id).first()
if body.room_id is not None
else query.filter(LiveRoom.invite_code == body.invite_code).first()
)
if not room:
raise HTTPException(status_code=404, detail="Room not found")
_verify_room_pin(db, room, body.pin, current_user.id, _client_ip(request))
return _serialize_room(room, current_user.id)
@router.get("/rooms/nearby")
def get_nearby_rooms(
lat: float, lon: float, radius_km: float = 5.0, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
rooms = (
db.query(LiveRoom)
.filter(LiveRoom.is_active == True, LiveRoom.latitude.isnot(None), LiveRoom.longitude.isnot(None))
.all()
)
nearby = []
for room in rooms:
dist_km = haversine_meters(lat, lon, room.latitude, room.longitude) / 1000.0
if dist_km <= radius_km:
nearby.append({"room": _serialize_room(room, current_user.id), "distance_km": dist_km})
return sorted(nearby, key=lambda x: x["distance_km"])
@router.get("/rooms/{room_id}/stream") @router.get("/rooms/{room_id}/stream")
def stream_room_song(room_id: int, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)): def stream_room_song(
room_id: int,
request: Request,
pin: Optional[str] = None,
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. Still PIN-gated
like everything else about this room - without this, a set PIN would do nothing once
someone already has the room id, since playback never went through join()."""
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first() room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
if not room: if not room:
raise HTTPException(status_code=404, detail="Room not found") raise HTTPException(status_code=404, detail="Room not found")
_verify_room_pin(db, room, pin, current_user.id, _client_ip(request))
if not room.current_song_id: if not room.current_song_id:
raise HTTPException(status_code=404, detail="Nothing is playing in this room right now") raise HTTPException(status_code=404, detail="Nothing is playing in this room right now")
song = db.query(LibrarySong).filter(LibrarySong.id == room.current_song_id).first() song = db.query(LibrarySong).filter(LibrarySong.id == room.current_song_id).first()
...@@ -397,7 +570,7 @@ def get_room_messages( ...@@ -397,7 +570,7 @@ def get_room_messages(
@router.websocket("/rooms/{room_id}/ws") @router.websocket("/rooms/{room_id}/ws")
async def room_websocket(websocket: WebSocket, room_id: int, token: str): async def room_websocket(websocket: WebSocket, room_id: int, token: str, pin: Optional[str] = None):
user_id = user_id_from_ws_token(token) user_id = user_id_from_ws_token(token)
if user_id is None: if user_id is None:
await websocket.close(code=4401) await websocket.close(code=4401)
...@@ -411,6 +584,19 @@ async def room_websocket(websocket: WebSocket, room_id: int, token: str): ...@@ -411,6 +584,19 @@ async def room_websocket(websocket: WebSocket, room_id: int, token: str):
await websocket.close(code=4403) await websocket.close(code=4403)
return return
if room_row.pin_hash is not None:
# Same short-lived-session convention as every other helper in this file - the
# websocket handler itself has no FastAPI-injected db.
pin_db = SessionLocal()
try:
ip = websocket.client.host if websocket.client else "unknown"
_verify_room_pin(pin_db, room_row, pin, user_id, ip)
except HTTPException:
await websocket.close(code=4403)
return
finally:
pin_db.close()
await room_manager.connect(room_id, user_id, websocket) await room_manager.connect(room_id, user_id, websocket)
state = room_manager.get_room(room_id) state = room_manager.get_room(room_id)
......
import math
import os import os
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from typing import Optional from typing import Optional
...@@ -21,6 +20,7 @@ from src.core.database import ( ...@@ -21,6 +20,7 @@ from src.core.database import (
User, User,
) )
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 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
from src.services.geo import haversine_meters as _haversine_meters
router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"]) router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"])
...@@ -32,14 +32,6 @@ VALID_TIERS = {"major", "business", "community"} ...@@ -32,14 +32,6 @@ VALID_TIERS = {"major", "business", "community"}
NOMINATIM_USER_AGENT = "StaxSoundmarks/1.0 (location picker for the Stax soundmarks feature)" NOMINATIM_USER_AGENT = "StaxSoundmarks/1.0 (location picker for the Stax soundmarks feature)"
def _haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
R = 6371000.0 # Earth radius in meters
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def _validate_tier_and_owner(tier: str, business_owner_id: Optional[int]) -> None: def _validate_tier_and_owner(tier: str, business_owner_id: Optional[int]) -> None:
if tier not in VALID_TIERS: if tier not in VALID_TIERS:
raise HTTPException(status_code=422, detail=f"tier must be one of {sorted(VALID_TIERS)}") raise HTTPException(status_code=422, detail=f"tier must be one of {sorted(VALID_TIERS)}")
......
...@@ -67,14 +67,18 @@ class RefreshToken(Base): ...@@ -67,14 +67,18 @@ class RefreshToken(Base):
class AuthAttempt(Base): class AuthAttempt(Base):
"""Logged on every /auth/telegram/request_code call (phone_number set) to rate-limit our """Logged on every /auth/telegram/request_code call (phone_number set) to rate-limit our
own Telegram API usage, and on every /auth/login call (username set) to rate-limit own Telegram API usage, on every /auth/login call (username set) to rate-limit
brute-force login attempts - the two purposes share this table but stay independent of brute-force login attempts, and on every room-PIN join/websocket attempt (room_id +
each other (queries always filter on whichever column is relevant, never mix the two).""" user_id set) to rate-limit PIN brute-forcing - three purposes sharing this table, each
staying independent of the others (queries always filter on whichever columns are
relevant to that purpose, never mix them)."""
__tablename__ = "auth_attempts" __tablename__ = "auth_attempts"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
phone_number = Column(String, index=True, nullable=True) phone_number = Column(String, index=True, nullable=True)
username = Column(String, index=True, nullable=True) username = Column(String, index=True, nullable=True)
ip_address = Column(String, index=True) ip_address = Column(String, index=True)
room_id = Column(Integer, ForeignKey("live_rooms.id"), index=True, nullable=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class DiscoveryAttempt(Base): class DiscoveryAttempt(Base):
...@@ -289,14 +293,24 @@ class LiveRoom(Base): ...@@ -289,14 +293,24 @@ class LiveRoom(Base):
current_song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True) current_song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
name = Column(String) name = Column(String)
is_active = Column(Boolean, default=True) is_active = Column(Boolean, default=True)
# Alternate join key, shareable out-of-band (a link/code) instead of the bare numeric id.
# Nullable at the DB level only because the SQLite add-column migration couldn't backfill
# and add a unique index in one statement - create_live_room always sets it on every new row.
invite_code = Column(String, unique=True, index=True, nullable=True)
# PBKDF2 hash via hash_password (security.py) - same mechanism as User.password_hash, not
# new crypto. Null means no PIN required to join.
pin_hash = Column(String, nullable=True)
latitude = Column(Float, nullable=True)
longitude = Column(Float, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class RoomMessage(Base): class RoomMessage(Base):
"""Persisted room group chat - replaces what used to be an in-memory-only """Persisted room group chat - replaces what used to be an in-memory-only
deque(maxlen=50) on RoomState (room_manager.py) that was discarded entirely the instant a deque(maxlen=50) on RoomState (room_manager.py) that was discarded entirely the instant a
room's last connection dropped. Rooms are open/unscoped shared content by existing design room's last connection dropped. Rooms are open/unscoped shared content by default (any
(any authenticated user can join any active room, same as Posts) - there's no membership authenticated user can join any active room, same as Posts) unless the creator has set a
check on reading these, only on who's *connected live* right now (room_manager.py).""" PIN (social.py's _verify_room_pin) - there's no membership check on reading chat history,
only on who's *connected live* right now (room_manager.py) or streaming its audio."""
__tablename__ = "room_messages" __tablename__ = "room_messages"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
room_id = Column(Integer, ForeignKey("live_rooms.id"), index=True, nullable=False) room_id = Column(Integer, ForeignKey("live_rooms.id"), index=True, nullable=False)
......
import math
def haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Great-circle distance in meters. Shared by Soundmarks' /nearby, Rooms' /nearby, and
Radio's local-scope visibility check - originally a private copy inside soundmarks.py,
moved here once a second and third consumer needed the exact same math."""
R = 6371000.0 # Earth radius in meters
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
from src.services.geo import haversine_meters
def test_haversine_zero_distance_for_identical_points():
assert haversine_meters(40.0, -73.0, 40.0, -73.0) == 0.0
def test_haversine_known_city_pair_within_tolerance():
# New York City <-> Los Angeles, real-world great-circle distance is ~3936 km.
nyc = (40.7128, -74.0060)
la = (34.0522, -118.2437)
distance_km = haversine_meters(*nyc, *la) / 1000.0
assert 3900 <= distance_km <= 3970
def test_haversine_small_distance_is_small():
# Two points ~111m apart (0.001 degrees of latitude) should read as roughly that, not
# some wildly different value from a sign/unit error.
distance = haversine_meters(40.0, -73.0, 40.001, -73.0)
assert 100 <= distance <= 120
def test_haversine_is_symmetric():
a = (51.5074, -0.1278) # London
b = (48.8566, 2.3522) # Paris
assert haversine_meters(*a, *b) == haversine_meters(*b, *a)
def test_haversine_antipodal_points_near_earth_circumference_half():
# Roughly opposite sides of the globe - should be close to half the Earth's circumference
# (~20015 km), a sanity check that the formula doesn't blow up or wrap incorrectly.
distance_km = haversine_meters(0.0, 0.0, 0.0, 179.9) / 1000.0
assert 19900 <= distance_km <= 20020
import itertools
from src.core.database import LiveRoom, SessionLocal
from src.core.security import hash_password
def _token(headers):
return headers["Authorization"].split(" ", 1)[1]
_room_codes = itertools.count(1)
def _make_room(dj_id, name="Test Room", pin=None, latitude=None, longitude=None, invite_code=None):
db = SessionLocal()
try:
room = LiveRoom(
dj_id=dj_id,
name=name,
is_active=True,
invite_code=invite_code or f"T{next(_room_codes):06d}",
pin_hash=hash_password(pin) if pin else None,
latitude=latitude,
longitude=longitude,
)
db.add(room)
db.commit()
db.refresh(room)
return room.id
finally:
db.close()
# --- Creation / invite code ---
def test_create_room_generates_an_invite_code(client, auth_as):
headers, _ = auth_as()
response = client.post("/social/rooms", json={"name": "Late Night LoFi"}, headers=headers)
assert response.status_code == 201
assert response.json()["invite_code"]
assert len(response.json()["invite_code"]) == 7
def test_two_rooms_get_distinct_invite_codes(client, auth_as):
headers, _ = auth_as()
a = client.post("/social/rooms", json={"name": "Room A"}, headers=headers).json()
b = client.post("/social/rooms", json={"name": "Room B"}, headers=headers).json()
assert a["invite_code"] != b["invite_code"]
def test_create_room_with_pin_never_returns_the_raw_or_hashed_pin(client, auth_as):
headers, _ = auth_as()
response = client.post("/social/rooms", json={"name": "Secret Room", "pin": "1234"}, headers=headers)
body = response.json()
assert body["has_pin"] is True
assert "pin" not in body
assert "pin_hash" not in body
def test_create_room_rejects_malformed_pin(client, auth_as):
headers, _ = auth_as()
response = client.post("/social/rooms", json={"name": "Room", "pin": "12"}, headers=headers)
assert response.status_code == 422
def test_invite_code_hidden_from_non_owner_shown_to_owner(client, auth_as):
owner_headers, owner = auth_as()
other_headers, _ = auth_as()
client.post("/social/rooms", json={"name": "Owner's Room"}, headers=owner_headers)
as_owner = client.get("/social/rooms", headers=owner_headers).json()
as_other = client.get("/social/rooms", headers=other_headers).json()
owner_room = next(r for r in as_owner if r["dj_id"] == owner.id)
other_room = next(r for r in as_other if r["dj_id"] == owner.id)
assert owner_room["invite_code"] is not None
assert other_room["invite_code"] is None
# --- Update ---
def test_update_room_requires_ownership(client, auth_as):
headers, owner = auth_as()
other_headers, _ = auth_as()
room_id = _make_room(dj_id=owner.id)
response = client.patch(f"/social/rooms/{room_id}", json={"name": "Renamed"}, headers=other_headers)
assert response.status_code == 403
def test_owner_renames_room(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id)
response = client.patch(f"/social/rooms/{room_id}", json={"name": "New Name"}, headers=headers)
assert response.status_code == 200
assert response.json()["name"] == "New Name"
def test_owner_sets_a_pin_via_update(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id)
response = client.patch(f"/social/rooms/{room_id}", json={"pin": "4321"}, headers=headers)
assert response.status_code == 200
assert response.json()["has_pin"] is True
def test_owner_clears_a_pin_with_empty_string(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="4321")
response = client.patch(f"/social/rooms/{room_id}", json={"pin": ""}, headers=headers)
assert response.status_code == 200
assert response.json()["has_pin"] is False
def test_update_unknown_room_404s(client, auth_as):
headers, _ = auth_as()
response = client.patch("/social/rooms/999999", json={"name": "x"}, headers=headers)
assert response.status_code == 404
# --- by-code lookup ---
def test_get_room_by_code(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, invite_code="ABC1234")
response = client.get("/social/rooms/by-code/ABC1234", headers=headers)
assert response.status_code == 200
assert response.json()["id"] == room_id
def test_get_room_by_unknown_code_404s(client, auth_as):
headers, _ = auth_as()
response = client.get("/social/rooms/by-code/NOSUCHCODE", headers=headers)
assert response.status_code == 404
# --- join ---
def test_join_requires_exactly_one_of_room_id_or_invite_code(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id)
both = client.post("/social/rooms/join", json={"room_id": room_id, "invite_code": "X"}, headers=headers)
neither = client.post("/social/rooms/join", json={}, headers=headers)
assert both.status_code == 422
assert neither.status_code == 422
def test_join_by_room_id_with_no_pin_succeeds(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id)
response = client.post("/social/rooms/join", json={"room_id": room_id}, headers=headers)
assert response.status_code == 200
def test_join_by_invite_code_with_no_pin_succeeds(client, auth_as):
headers, owner = auth_as()
_make_room(dj_id=owner.id, invite_code="JOINME1")
response = client.post("/social/rooms/join", json={"invite_code": "JOINME1"}, headers=headers)
assert response.status_code == 200
def test_join_missing_pin_is_forbidden(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="1111")
response = client.post("/social/rooms/join", json={"room_id": room_id}, headers=headers)
assert response.status_code == 403
def test_join_wrong_pin_is_forbidden(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="1111")
response = client.post("/social/rooms/join", json={"room_id": room_id, "pin": "9999"}, headers=headers)
assert response.status_code == 403
def test_join_correct_pin_succeeds(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="1111")
response = client.post("/social/rooms/join", json={"room_id": room_id, "pin": "1111"}, headers=headers)
assert response.status_code == 200
def test_join_unknown_room_404s(client, auth_as):
headers, _ = auth_as()
response = client.post("/social/rooms/join", json={"room_id": 999999}, headers=headers)
assert response.status_code == 404
def test_join_rate_limited_per_user_after_too_many_wrong_pins(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="1111")
guesser_headers, _ = auth_as()
for _ in range(10):
resp = client.post("/social/rooms/join", json={"room_id": room_id, "pin": "0000"}, headers=guesser_headers)
assert resp.status_code == 403
response = client.post("/social/rooms/join", json={"room_id": room_id, "pin": "1111"}, headers=guesser_headers)
assert response.status_code == 429
def test_join_rate_limited_per_ip_across_different_accounts(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="1111")
# 20 distinct accounts (same test-client IP), one wrong attempt each - none individually
# crosses the per-user limit of 10, but the shared IP does cross its own limit of 20.
for _ in range(20):
guesser_headers, _ = auth_as()
client.post("/social/rooms/join", json={"room_id": room_id, "pin": "0000"}, headers=guesser_headers)
final_headers, _ = auth_as()
response = client.post("/social/rooms/join", json={"room_id": room_id, "pin": "1111"}, headers=final_headers)
assert response.status_code == 429
# --- nearby ---
def test_nearby_rooms_filters_by_radius_and_sorts_by_distance(client, auth_as):
headers, owner = auth_as()
near_id = _make_room(dj_id=owner.id, name="Near", latitude=40.001, longitude=-73.0, invite_code="NEAR001")
far_id = _make_room(dj_id=owner.id, name="Far", latitude=45.0, longitude=-73.0, invite_code="FAR0001")
response = client.get("/social/rooms/nearby", params={"lat": 40.0, "lon": -73.0, "radius_km": 1.0}, headers=headers)
assert response.status_code == 200
ids = [entry["room"]["id"] for entry in response.json()]
assert near_id in ids
assert far_id not in ids
def test_nearby_rooms_excludes_rooms_without_location(client, auth_as):
headers, owner = auth_as()
no_loc_id = _make_room(dj_id=owner.id, name="No location", invite_code="NOLOC001")
response = client.get("/social/rooms/nearby", params={"lat": 40.0, "lon": -73.0, "radius_km": 50.0}, headers=headers)
ids = [entry["room"]["id"] for entry in response.json()]
assert no_loc_id not in ids
# --- stream + websocket PIN gating ---
def test_stream_room_song_is_pin_gated(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="1111")
response = client.get(f"/social/rooms/{room_id}/stream", headers=headers)
assert response.status_code == 403
response = client.get(f"/social/rooms/{room_id}/stream", params={"pin": "1111"}, headers=headers)
# No song is currently set, so a correct PIN should get past the gate and hit the
# "nothing playing" 404 instead of the PIN's own 403.
assert response.status_code == 404
def test_websocket_closes_without_required_pin(client, auth_as):
from starlette.websockets import WebSocketDisconnect
import pytest
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="1111")
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}"):
pass
def test_websocket_closes_with_wrong_pin(client, auth_as):
from starlette.websockets import WebSocketDisconnect
import pytest
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="1111")
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}&pin=0000"):
pass
def test_websocket_connects_with_correct_pin(client, auth_as):
headers, owner = auth_as()
room_id = _make_room(dj_id=owner.id, pin="1111")
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}&pin=1111") as ws:
snapshot = ws.receive_json()
assert snapshot["type"] == "snapshot"
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