Commit f25ef119 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix channels.py accepting user_id/owner_id from the request body

Every route in this router trusted a client-supplied user_id/owner_id
instead of deriving it from the JWT like every other router in the app
(soundmarks, social, discovery, library all use get_current_user) - any
caller could create a channel as any user, follow/unfollow as any user,
or post vibe-sets/stories/showcases as any user by just changing a
number in the request body. Also none of the routes required auth at
all, including plain reads.

Adds get_current_user to every route and derives the caller's identity
from current_user.id instead, removing the now-redundant id fields from
every request schema.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 58f8389f
Pipeline #1071 passed with stage
in 4 minutes and 53 seconds
......@@ -12,10 +12,12 @@ from src.core.database import (
ChannelShowcase,
LibrarySong,
Post,
User,
VibeSet,
VibeSetTrack,
get_db,
)
from src.core.security import get_current_user
router = APIRouter(prefix="/channels", tags=["Channels"])
......@@ -23,31 +25,23 @@ STORY_LIFETIME = timedelta(hours=24)
class ChannelCreate(BaseModel):
owner_id: int
name: str
description: Optional[str] = None
avatar_url: Optional[str] = None
class FollowRequest(BaseModel):
user_id: int
class VibeSetCreate(BaseModel):
user_id: int # must match the channel's owner_id
title: str
description: Optional[str] = None
song_ids: List[int] = []
class StoryCreate(BaseModel):
user_id: int # must match the channel's owner_id
song_id: int
caption: Optional[str] = None
class ShowcaseCreate(BaseModel):
user_id: int # must match the channel's owner_id
post_id: int
......@@ -64,8 +58,8 @@ def _require_owner(channel: Channel, user_id: int):
@router.post("", status_code=status.HTTP_201_CREATED)
def create_channel(data: ChannelCreate, db: Session = Depends(get_db)):
channel = Channel(**data.dict())
def create_channel(data: ChannelCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
channel = Channel(owner_id=current_user.id, **data.dict())
db.add(channel)
db.commit()
db.refresh(channel)
......@@ -73,7 +67,7 @@ def create_channel(data: ChannelCreate, db: Session = Depends(get_db)):
@router.get("")
def list_channels(db: Session = Depends(get_db)):
def list_channels(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
return db.query(Channel).order_by(Channel.created_at.desc()).all()
......@@ -84,7 +78,7 @@ def list_channels(db: Session = Depends(get_db)):
# parse "vibe-sets" as an int, never reaching this route at all.
@router.get("/vibe-sets/{vibe_set_id}")
def get_vibe_set(vibe_set_id: int, db: Session = Depends(get_db)):
def get_vibe_set(vibe_set_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
vibe_set = db.query(VibeSet).filter(VibeSet.id == vibe_set_id).first()
if not vibe_set:
raise HTTPException(status_code=404, detail="Vibe set not found")
......@@ -98,21 +92,21 @@ def get_vibe_set(vibe_set_id: int, db: Session = Depends(get_db)):
@router.get("/{channel_id}")
def get_channel(channel_id: int, db: Session = Depends(get_db)):
def get_channel(channel_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
channel = _get_channel_or_404(channel_id, db)
follower_count = db.query(ChannelFollow).filter(ChannelFollow.channel_id == channel_id).count()
return {"channel": channel, "follower_count": follower_count}
@router.post("/{channel_id}/follow", status_code=status.HTTP_201_CREATED)
def follow_channel(channel_id: int, data: FollowRequest, db: Session = Depends(get_db)):
def follow_channel(channel_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
_get_channel_or_404(channel_id, db)
existing = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == data.user_id
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == current_user.id
).first()
if existing:
return existing
follow = ChannelFollow(channel_id=channel_id, user_id=data.user_id)
follow = ChannelFollow(channel_id=channel_id, user_id=current_user.id)
db.add(follow)
db.commit()
db.refresh(follow)
......@@ -120,9 +114,9 @@ def follow_channel(channel_id: int, data: FollowRequest, db: Session = Depends(g
@router.post("/{channel_id}/unfollow")
def unfollow_channel(channel_id: int, data: FollowRequest, db: Session = Depends(get_db)):
def unfollow_channel(channel_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
follow = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == data.user_id
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == current_user.id
).first()
if follow:
db.delete(follow)
......@@ -131,9 +125,11 @@ def unfollow_channel(channel_id: int, data: FollowRequest, db: Session = Depends
@router.post("/{channel_id}/vibe-sets", status_code=status.HTTP_201_CREATED)
def create_vibe_set(channel_id: int, data: VibeSetCreate, db: Session = Depends(get_db)):
def create_vibe_set(
channel_id: int, data: VibeSetCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
_require_owner(channel, current_user.id)
vibe_set = VibeSet(channel_id=channel_id, title=data.title, description=data.description)
db.add(vibe_set)
......@@ -157,15 +153,17 @@ def create_vibe_set(channel_id: int, data: VibeSetCreate, db: Session = Depends(
@router.get("/{channel_id}/vibe-sets")
def list_vibe_sets(channel_id: int, db: Session = Depends(get_db)):
def list_vibe_sets(channel_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
_get_channel_or_404(channel_id, db)
return db.query(VibeSet).filter(VibeSet.channel_id == channel_id).order_by(VibeSet.created_at.desc()).all()
@router.post("/{channel_id}/stories", status_code=status.HTTP_201_CREATED)
def create_story(channel_id: int, data: StoryCreate, db: Session = Depends(get_db)):
def create_story(
channel_id: int, data: StoryCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
_require_owner(channel, current_user.id)
song = db.query(LibrarySong).filter(LibrarySong.id == data.song_id).first()
if not song:
......@@ -184,7 +182,7 @@ def create_story(channel_id: int, data: StoryCreate, db: Session = Depends(get_d
@router.get("/{channel_id}/stories")
def list_active_stories(channel_id: int, db: Session = Depends(get_db)):
def list_active_stories(channel_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
_get_channel_or_404(channel_id, db)
now = datetime.now(timezone.utc)
return (
......@@ -196,9 +194,11 @@ def list_active_stories(channel_id: int, db: Session = Depends(get_db)):
@router.post("/{channel_id}/showcase", status_code=status.HTTP_201_CREATED)
def showcase_post(channel_id: int, data: ShowcaseCreate, db: Session = Depends(get_db)):
def showcase_post(
channel_id: int, data: ShowcaseCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
_require_owner(channel, current_user.id)
post = db.query(Post).filter(Post.id == data.post_id).first()
if not post:
......@@ -212,7 +212,7 @@ def showcase_post(channel_id: int, data: ShowcaseCreate, db: Session = Depends(g
@router.get("/{channel_id}/showcase")
def list_showcase(channel_id: int, db: Session = Depends(get_db)):
def list_showcase(channel_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
_get_channel_or_404(channel_id, db)
return (
db.query(ChannelShowcase)
......
......@@ -2,7 +2,7 @@ import os
import tempfile
from datetime import datetime, timedelta, timezone
from src.core.database import AudioStory, Channel, LibrarySong, Post, SessionLocal
from src.core.database import AudioStory, LibrarySong, SessionLocal
def _make_library_song(**overrides):
......@@ -22,121 +22,152 @@ def _make_library_song(**overrides):
db.close()
def _make_channel(client, owner_id=1, name="Test Channel"):
response = client.post("/channels", json={"owner_id": owner_id, "name": name})
def _make_channel(client, headers, name="Test Channel"):
response = client.post("/channels", json={"name": name}, headers=headers)
assert response.status_code == 201
return response.json()["id"]
def test_create_and_list_channels(client):
channel_id = _make_channel(client, owner_id=1, name="DJ Test's Channel")
response = client.get("/channels")
def test_channel_routes_require_auth(client):
assert client.get("/channels").status_code == 401
assert client.post("/channels", json={"name": "x"}).status_code == 401
def test_create_channel_is_owned_by_the_caller(client, auth_as):
headers, user = auth_as()
response = client.post("/channels", json={"name": "DJ Test's Channel"}, headers=headers)
assert response.status_code == 201
assert response.json()["owner_id"] == user.id
def test_create_and_list_channels(client, auth_as):
headers, _ = auth_as()
channel_id = _make_channel(client, headers, name="DJ Test's Channel")
response = client.get("/channels", headers=headers)
assert response.status_code == 200
assert any(c["id"] == channel_id for c in response.json())
def test_get_channel_detail_with_follower_count(client):
channel_id = _make_channel(client)
response = client.get(f"/channels/{channel_id}")
def test_get_channel_detail_with_follower_count(client, auth_as):
headers, _ = auth_as()
follower_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
response = client.get(f"/channels/{channel_id}", headers=headers)
assert response.status_code == 200
body = response.json()
assert body["channel"]["id"] == channel_id
assert body["follower_count"] == 0
client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
response = client.get(f"/channels/{channel_id}")
client.post(f"/channels/{channel_id}/follow", headers=follower_headers)
response = client.get(f"/channels/{channel_id}", headers=headers)
assert response.json()["follower_count"] == 1
def test_get_unknown_channel_404s(client):
response = client.get("/channels/999999")
def test_get_unknown_channel_404s(client, auth_as):
headers, _ = auth_as()
response = client.get("/channels/999999", headers=headers)
assert response.status_code == 404
def test_follow_is_idempotent(client):
channel_id = _make_channel(client)
r1 = client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
r2 = client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
def test_follow_is_idempotent(client, auth_as):
headers, _ = auth_as()
follower_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
r1 = client.post(f"/channels/{channel_id}/follow", headers=follower_headers)
r2 = client.post(f"/channels/{channel_id}/follow", headers=follower_headers)
assert r1.status_code == 201
assert r2.status_code == 201
assert r1.json()["id"] == r2.json()["id"]
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 1
assert client.get(f"/channels/{channel_id}", headers=headers).json()["follower_count"] == 1
def test_unfollow(client):
channel_id = _make_channel(client)
client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 1
def test_unfollow(client, auth_as):
headers, _ = auth_as()
follower_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
client.post(f"/channels/{channel_id}/follow", headers=follower_headers)
assert client.get(f"/channels/{channel_id}", headers=headers).json()["follower_count"] == 1
response = client.post(f"/channels/{channel_id}/unfollow", json={"user_id": 2})
response = client.post(f"/channels/{channel_id}/unfollow", headers=follower_headers)
assert response.status_code == 200
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 0
assert client.get(f"/channels/{channel_id}", headers=headers).json()["follower_count"] == 0
def test_create_vibe_set_with_tracks_owner_only(client):
channel_id = _make_channel(client, owner_id=1)
def test_create_vibe_set_with_tracks_owner_only(client, auth_as):
headers, _ = auth_as()
other_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
song_id = _make_library_song(title="Vibe Track")
forbidden = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"user_id": 999, "title": "Not mine", "song_ids": [song_id]},
json={"title": "Not mine", "song_ids": [song_id]},
headers=other_headers,
)
assert forbidden.status_code == 403
response = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"user_id": 1, "title": "Sunday Chill", "song_ids": [song_id]},
json={"title": "Sunday Chill", "song_ids": [song_id]},
headers=headers,
)
assert response.status_code == 201
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}")
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}", headers=headers)
assert detail.status_code == 200
body = detail.json()
assert body["vibe_set"]["title"] == "Sunday Chill"
assert len(body["tracks"]) == 1
assert body["tracks"][0]["song_id"] == song_id
listing = client.get(f"/channels/{channel_id}/vibe-sets")
listing = client.get(f"/channels/{channel_id}/vibe-sets", headers=headers)
assert listing.status_code == 200
assert any(v["id"] == vibe_set_id for v in listing.json())
def test_vibe_set_route_ordering_not_swallowed_by_channel_id(client):
def test_vibe_set_route_ordering_not_swallowed_by_channel_id(client, auth_as):
# /channels/vibe-sets/{id} must not be intercepted by the /{channel_id} catch-all
channel_id = _make_channel(client)
headers, _ = auth_as()
channel_id = _make_channel(client, headers)
response = client.post(
f"/channels/{channel_id}/vibe-sets", json={"user_id": 1, "title": "x", "song_ids": []}
f"/channels/{channel_id}/vibe-sets", json={"title": "x", "song_ids": []}, headers=headers
)
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}")
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}", headers=headers)
assert detail.status_code == 200
assert detail.json()["vibe_set"]["id"] == vibe_set_id
def test_unknown_vibe_set_404s(client):
response = client.get("/channels/vibe-sets/999999")
def test_unknown_vibe_set_404s(client, auth_as):
headers, _ = auth_as()
response = client.get("/channels/vibe-sets/999999", headers=headers)
assert response.status_code == 404
def test_create_story_owner_only_and_expiry(client):
channel_id = _make_channel(client, owner_id=1)
def test_create_story_owner_only_and_expiry(client, auth_as):
headers, _ = auth_as()
other_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
song_id = _make_library_song(title="Story Clip")
forbidden = client.post(f"/channels/{channel_id}/stories", json={"user_id": 999, "song_id": song_id})
forbidden = client.post(f"/channels/{channel_id}/stories", json={"song_id": song_id}, headers=other_headers)
assert forbidden.status_code == 403
response = client.post(f"/channels/{channel_id}/stories", json={"user_id": 1, "song_id": song_id, "caption": "vibes"})
response = client.post(
f"/channels/{channel_id}/stories", json={"song_id": song_id, "caption": "vibes"}, headers=headers
)
assert response.status_code == 201
story_id = response.json()["id"]
active = client.get(f"/channels/{channel_id}/stories")
active = client.get(f"/channels/{channel_id}/stories", headers=headers)
assert active.status_code == 200
assert any(s["id"] == story_id for s in active.json())
def test_expired_stories_are_filtered_from_active_listing(client):
channel_id = _make_channel(client, owner_id=1)
def test_expired_stories_are_filtered_from_active_listing(client, auth_as):
headers, _ = auth_as()
channel_id = _make_channel(client, headers)
song_id = _make_library_song(title="Old Clip")
db = SessionLocal()
......@@ -151,24 +182,25 @@ def test_expired_stories_are_filtered_from_active_listing(client):
finally:
db.close()
active = client.get(f"/channels/{channel_id}/stories")
active = client.get(f"/channels/{channel_id}/stories", headers=headers)
assert active.status_code == 200
assert not any(s["id"] == expired_id for s in active.json())
def test_showcase_owner_only(client, auth_as):
headers, user = auth_as()
channel_id = _make_channel(client, owner_id=user.id)
other_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
song_id = _make_library_song(title="Showcased")
post_response = client.post("/social/posts", json={"song_id": song_id, "caption": "check it"}, headers=headers)
post_id = post_response.json()["id"]
forbidden = client.post(f"/channels/{channel_id}/showcase", json={"user_id": 999, "post_id": post_id})
forbidden = client.post(f"/channels/{channel_id}/showcase", json={"post_id": post_id}, headers=other_headers)
assert forbidden.status_code == 403
response = client.post(f"/channels/{channel_id}/showcase", json={"user_id": user.id, "post_id": post_id})
response = client.post(f"/channels/{channel_id}/showcase", json={"post_id": post_id}, headers=headers)
assert response.status_code == 201
listing = client.get(f"/channels/{channel_id}/showcase")
listing = client.get(f"/channels/{channel_id}/showcase", headers=headers)
assert listing.status_code == 200
assert any(s["post_id"] == post_id for s in listing.json())
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