Commit eac69cde authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Send a real access token to the Rooms websocket instead of a bare user_id

Matches the backend fix: connectToRoom() now takes the access token
(getAccessToken() from RoomView) instead of a client-known userId, since
the server verifies it before accepting the connection rather than trusting
whatever id is passed. getCurrentUserId() (api/jwt.ts) is still used for
local "is this me" UI comparisons only - never sent back as a trust claim;
updated its comment, which was stale since Channels' own auth fix.

Roadmap updated to reflect both security gaps are now fixed.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 9958e8e1
Pipeline #1084 canceled with stage
import { getAccessToken } from './client' import { getAccessToken } from './client'
/** Decodes (never verifies - that's the server's job) the access token's payload to read /** Decodes (never verifies - that's the server's job) the access token's payload to read the
* the current user id out of the `sub` claim, so screens that need it (channels endpoints * current user id out of the `sub` claim, for local-only UI comparisons like "is this my
* take user_id in the body instead of deriving it from the token server-side) don't have to * message/channel/room" (e.g. RoomView, Channels). Every endpoint that actually needs to know
* ask the user to type their own id in. */ * who's calling derives it server-side from the verified token instead - this is never sent
* back to the server as a claim of identity. */
export function getCurrentUserId(): number | null { export function getCurrentUserId(): number | null {
const token = getAccessToken() const token = getAccessToken()
if (!token) return null if (!token) return null
......
...@@ -45,11 +45,13 @@ export type RoomEvent = ...@@ -45,11 +45,13 @@ export type RoomEvent =
| { type: 'now_playing_changed'; song_id: number | null; song: RoomSong | null; dj_id: number } | { type: 'now_playing_changed'; song_id: number | null; song: RoomSong | null; dj_id: number }
| { type: 'error'; detail: string } | { type: 'error'; detail: string }
/** Raw WebSocket wrapper for /social/rooms/{id}/ws - auth here is just a user_id query param /** Raw WebSocket wrapper for /social/rooms/{id}/ws. Browsers' native WebSocket API can't set
* (matching the backend, which doesn't check the JWT on this route), not a Bearer header. */ * an Authorization header, so the access token travels as a query param instead - the server
export function connectToRoom(roomId: number, userId: number, onEvent: (e: RoomEvent) => void): WebSocket { * independently verifies it (signature, expiry, and that the user still exists) rather than
* trusting a client-supplied id. */
export function connectToRoom(roomId: number, accessToken: string, onEvent: (e: RoomEvent) => void): WebSocket {
const wsBase = resolveWsBase() const wsBase = resolveWsBase()
const ws = new WebSocket(`${wsBase}/social/rooms/${roomId}/ws?user_id=${userId}`) const ws = new WebSocket(`${wsBase}/social/rooms/${roomId}/ws?token=${encodeURIComponent(accessToken)}`)
ws.onmessage = (msg) => { ws.onmessage = (msg) => {
try { try {
onEvent(JSON.parse(msg.data) as RoomEvent) onEvent(JSON.parse(msg.data) as RoomEvent)
......
...@@ -35,7 +35,7 @@ describe('RoomView', () => { ...@@ -35,7 +35,7 @@ describe('RoomView', () => {
clearTokens() clearTokens()
setTokens(fakeJwt({ sub: '1', type: 'access' }), 'refresh-token-unused') setTokens(fakeJwt({ sub: '1', type: 'access' }), 'refresh-token-unused')
fakeWs = { close: vi.fn(), send: vi.fn() } fakeWs = { close: vi.fn(), send: vi.fn() }
vi.spyOn(roomSocketApi, 'connectToRoom').mockImplementation((_roomId, _userId, onEvent) => { vi.spyOn(roomSocketApi, 'connectToRoom').mockImplementation((_roomId, _accessToken, onEvent) => {
emit = onEvent emit = onEvent
return fakeWs as unknown as WebSocket return fakeWs as unknown as WebSocket
}) })
......
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { ArrowLeft, Flame, Hand, Music2, Pause, Play, Send, SkipForward } from 'lucide-react' import { ArrowLeft, Flame, Hand, Music2, Pause, Play, Send, SkipForward } from 'lucide-react'
import { getCurrentUserId } from '../api/jwt' import { getCurrentUserId } from '../api/jwt'
import { getAccessToken } from '../api/client'
import { fetchRoomStreamUrl } from '../api/social' import { fetchRoomStreamUrl } from '../api/social'
import { import {
connectToRoom, connectToRoom,
...@@ -53,8 +54,9 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v ...@@ -53,8 +54,9 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
} }
useEffect(() => { useEffect(() => {
if (userId === null) return const accessToken = getAccessToken()
const ws = connectToRoom(roomId, userId, (event) => { if (accessToken === null) return
const ws = connectToRoom(roomId, accessToken, (event) => {
switch (event.type) { switch (event.type) {
case 'snapshot': case 'snapshot':
setMessages(event.chat_history) setMessages(event.chat_history)
...@@ -90,7 +92,7 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v ...@@ -90,7 +92,7 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current) if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [roomId, userId]) }, [roomId])
useEffect(() => { useEffect(() => {
messagesEndRef.current?.scrollIntoView({ block: 'end', behavior: 'smooth' }) messagesEndRef.current?.scrollIntoView({ block: 'end', behavior: 'smooth' })
......
...@@ -18,7 +18,7 @@ describe('Roadmap', () => { ...@@ -18,7 +18,7 @@ describe('Roadmap', () => {
vi.restoreAllMocks() vi.restoreAllMocks()
}) })
it('renders the critical security issues and feature inventory', () => { it('renders the fixed-security history and feature inventory', () => {
render( render(
<MemoryRouter> <MemoryRouter>
<AuthProvider> <AuthProvider>
...@@ -29,8 +29,8 @@ describe('Roadmap', () => { ...@@ -29,8 +29,8 @@ describe('Roadmap', () => {
</MemoryRouter>, </MemoryRouter>,
) )
expect(screen.getByText('/remix has no authentication at all')).toBeInTheDocument() expect(screen.getByText('/remix now requires login and is scoped to its owner')).toBeInTheDocument()
expect(screen.getByText('Room WebSocket trusts an unauthenticated user_id')).toBeInTheDocument() expect(screen.getByText('Room WebSocket now verifies a real access token')).toBeInTheDocument()
// "Soundmarks"/"Remix" also appear in the page nav, so scope to feature-card-only text. // "Soundmarks"/"Remix" also appear in the page nav, so scope to feature-card-only text.
expect(screen.getByText('Location-tied anthems, three tiers')).toBeInTheDocument() expect(screen.getByText('Location-tied anthems, three tiers')).toBeInTheDocument()
expect(screen.getByText('Stems, key/BPM detect, AI arrangement')).toBeInTheDocument() expect(screen.getByText('Stems, key/BPM detect, AI arrangement')).toBeInTheDocument()
......
import { AlertTriangle } from 'lucide-react' import { ShieldCheck } from 'lucide-react'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
type Status = 'good' | 'warn' | 'bad' type Status = 'good' | 'warn' | 'bad'
...@@ -47,11 +47,10 @@ const FEATURES: Feature[] = [ ...@@ -47,11 +47,10 @@ const FEATURES: Feature[] = [
{ {
name: 'Rooms', name: 'Rooms',
sub: 'Pass-the-Aux live listening', sub: 'Pass-the-Aux live listening',
status: 'warn', status: 'good',
statusLabel: 'Needs auth fix', built: 'Chat, reactions, DJ queue/handoff, now-playing with cross-user streaming — a listener actually hears what the DJ picks. WebSocket auth fixed 2026-08-15: connects with a verified access token, not a client-supplied user_id.',
built: 'Chat, reactions, DJ queue/handoff, now-playing with cross-user streaming — a listener actually hears what the DJ picks.', gaps: 'None found.',
gaps: 'WebSocket user_id is unauthenticated — see critical issues above.', backendTests: '25+',
backendTests: '20+',
frontendTests: '19', frontendTests: '19',
}, },
{ {
...@@ -94,10 +93,10 @@ const FEATURES: Feature[] = [ ...@@ -94,10 +93,10 @@ const FEATURES: Feature[] = [
{ {
name: 'Remix', name: 'Remix',
sub: 'Stems, key/BPM detect, AI arrangement', sub: 'Stems, key/BPM detect, AI arrangement',
status: 'bad', status: 'warn',
built: 'Real pipeline, not vaporware — Demucs stem separation, BPM/key detection, a Gemini-planned arrangement, mastering. Upload/progress/poll UI works end to end.', built: 'Real pipeline, not vaporware — Demucs stem separation, BPM/key detection, a Gemini-planned arrangement, mastering. Upload/progress/poll UI works end to end. Auth gap fixed 2026-08-15: both endpoints require login, job status and library-song sourcing are scoped to the owner (was an IDOR).',
gaps: 'No auth at all — see critical issues above. Library-song linking (feeds the Posts remix-tree) is hardcoded off in the UI. Zero frontend tests.', gaps: 'Library-song linking (feeds the Posts remix-tree) is hardcoded off in the UI. Zero frontend tests.',
backendTests: '20', backendTests: '25',
frontendTests: '0', frontendTests: '0',
}, },
{ {
...@@ -124,11 +123,10 @@ const FEATURES: Feature[] = [ ...@@ -124,11 +123,10 @@ const FEATURES: Feature[] = [
const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[] }[] = [ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[] }[] = [
{ {
title: 'Now', title: 'Now',
sub: 'Security', sub: 'Nothing critical open',
dot: 'bg-red-400', dot: 'bg-emerald-400',
items: [ items: [
'Auth-gate /remix and derive user_id from the JWT instead of a form field.', 'Security: /remix auth-gated + IDOR closed, room WebSocket verifies a real token — see "Recently fixed" above.',
'Fix the room WebSocket — stop trusting a bare user_id query param.',
'Real login screen — shipped as username/password, so the app finally works for someone other than the dev account.', 'Real login screen — shipped as username/password, so the app finally works for someone other than the dev account.',
], ],
}, },
...@@ -172,13 +170,13 @@ export function Roadmap() { ...@@ -172,13 +170,13 @@ export function Roadmap() {
<div className="mb-10 flex flex-wrap gap-x-8 gap-y-4"> <div className="mb-10 flex flex-wrap gap-x-8 gap-y-4">
{[ {[
['9', 'Feature areas'], ['9', 'Feature areas'],
['2', 'Critical security gaps'], ['0', 'Critical security gaps'],
['186', 'Backend tests'], ['202', 'Backend tests'],
['137', 'Frontend tests'], ['148', 'Frontend tests'],
['4', 'Pages w/ zero tests'], ['4', 'Pages w/ zero tests'],
].map(([n, l]) => ( ].map(([n, l]) => (
<div key={l}> <div key={l}>
<p className={`text-xl font-bold tabular-nums ${l === 'Critical security gaps' ? 'text-red-400' : 'text-white'}`}>{n}</p> <p className="text-xl font-bold tabular-nums text-white">{n}</p>
<p className="text-[11px] uppercase tracking-wide text-neutral-500">{l}</p> <p className="text-[11px] uppercase tracking-wide text-neutral-500">{l}</p>
</div> </div>
))} ))}
...@@ -186,37 +184,39 @@ export function Roadmap() { ...@@ -186,37 +184,39 @@ export function Roadmap() {
<section className="mb-10"> <section className="mb-10">
<div className="mb-3 flex items-center justify-between"> <div className="mb-3 flex items-center justify-between">
<h2 className="text-xs font-bold uppercase tracking-wide text-neutral-500">Fix now — active security gaps</h2> <h2 className="text-xs font-bold uppercase tracking-wide text-neutral-500">Recently fixed — no known active security gaps</h2>
<span className="text-xs text-neutral-500">Not roadmap items — live holes in shipped code</span> <span className="text-xs text-neutral-500">Fixed 2026-08-15</span>
</div> </div>
<div className="space-y-3"> <div className="space-y-3">
<div className="rounded-xl border border-red-900/50 bg-red-950/20 p-4"> <div className="rounded-xl border border-emerald-900/50 bg-emerald-950/20 p-4">
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<AlertTriangle size={16} strokeWidth={2} className="mt-0.5 shrink-0 text-red-400" /> <ShieldCheck size={16} strokeWidth={2} className="mt-0.5 shrink-0 text-emerald-400" />
<div> <div>
<p className="mb-1 text-sm font-semibold text-white">/remix has no authentication at all</p> <p className="mb-1 text-sm font-semibold text-white">/remix now requires login and is scoped to its owner</p>
<p className="text-sm leading-relaxed text-neutral-400"> <p className="text-sm leading-relaxed text-neutral-400">
<code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">POST /remix</code> and{' '} <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">POST /remix</code> and{' '}
<code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">GET /remix/{'{job_id}'}</code>{' '} <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">GET /remix/{'{job_id}'}</code>{' '}
never call <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">get_current_user</code> — now call <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">get_current_user</code>,
every other router does. <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">user_id</code>{' '} same as every other router. The resulting library song and social post are always attributed to the real
is a raw, unvalidated form field, so a remix's resulting library song and social post can be attributed caller (no more client-supplied <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">user_id</code>{' '}
to anyone. Job status is also fetchable by guessing sequential IDs (IDOR) — no login needed to read or form field), job status is scoped to its owner (closing the IDOR), and sourcing from{' '}
claim someone else's remix. <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">library_song_ids</code> is scoped
to the caller's own library too.
</p> </p>
</div> </div>
</div> </div>
</div> </div>
<div className="rounded-xl border border-red-900/50 bg-red-950/20 p-4"> <div className="rounded-xl border border-emerald-900/50 bg-emerald-950/20 p-4">
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<AlertTriangle size={16} strokeWidth={2} className="mt-0.5 shrink-0 text-red-400" /> <ShieldCheck size={16} strokeWidth={2} className="mt-0.5 shrink-0 text-emerald-400" />
<div> <div>
<p className="mb-1 text-sm font-semibold text-white">Room WebSocket trusts an unauthenticated user_id</p> <p className="mb-1 text-sm font-semibold text-white">Room WebSocket now verifies a real access token</p>
<p className="text-sm leading-relaxed text-neutral-400"> <p className="text-sm leading-relaxed text-neutral-400">
<code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">WS /social/rooms/{'{room_id}'}/ws</code>{' '} <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">WS /social/rooms/{'{room_id}'}/ws</code>{' '}
takes <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">user_id</code> as a plain takes a JWT access token (browsers can't set headers on a WebSocket, so it travels as a query param) instead
query parameter, no token check. Anyone can connect claiming to be any user — chat as them, join the DJ of a bare <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">user_id</code>. The
queue as them, or take the aux as them. server decodes and verifies it — signature, expiry, and that the user still exists — before accepting the
connection, so nobody can chat, queue, or take the aux as someone else anymore.
</p> </p>
</div> </div>
</div> </div>
......
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