Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 78 additions & 2 deletions apps/realtime/src/access-revalidation.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { db } from '@sim/db'
import { session } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { ROOM_MEMBERSHIP_ACTIONS, satisfiesRoomMembership } from '@sim/platform-authz/room-policy'
import type { AccessRevokedBroadcast } from '@sim/realtime-protocol/events'
Expand All @@ -9,7 +11,8 @@ import {
type RoomType,
roomName,
} from '@sim/realtime-protocol/rooms'
import { sleep } from '@sim/utils/helpers'
import { chunkArray, sleep } from '@sim/utils/helpers'
import { and, gt, inArray } from 'drizzle-orm'
import {
evictSocketFromRoom,
runRoomEvictionHandler,
Expand Down Expand Up @@ -73,6 +76,23 @@ const SCAN_PASS_BUDGET_MS = 20_000

const SCAN_TIMED_OUT = Symbol('scan-timed-out')

/** Keeps each session-liveness query's `IN` list well below Postgres' bind-parameter limit. */
const SESSION_LOOKUP_BATCH_SIZE = 1_000

/** Returns the subset of `sessionIds` that still name an unexpired session row. */
async function findLiveSessionIds(sessionIds: string[]): Promise<Set<string>> {
const live = new Set<string>()
const now = new Date()
for (const batch of chunkArray(sessionIds, SESSION_LOOKUP_BATCH_SIZE)) {
const rows = await db
.select({ id: session.id })
.from(session)
.where(and(inArray(session.id, batch), gt(session.expiresAt, now)))
for (const row of rows) live.add(row.id)
}
return live
}

export interface AccessRevalidationSweep {
/** Stop the periodic sweep (clears the interval). */
stop: () => void
Expand Down Expand Up @@ -125,7 +145,9 @@ function collectScanTargets(io: IRoomManager['io']): ScanTarget[] {
* no longer satisfies the room, closing the gap left by the join-only access
* check. Without it, a member removed or downgraded mid-session keeps live
* collaborative access (including durable document writes) for the whole lifetime
* of an already-open socket.
* of an already-open socket. Each pass first disconnects sockets whose Better Auth
* session has ended (signed out, revoked, or expired), since the handshake is the
* only other place the credential is checked.
*
* Blip-safety: eviction fires *only* when {@link resolveCurrentRoomPermission}
* resolves to a permission that does not satisfy the room's membership level,
Expand Down Expand Up @@ -290,7 +312,61 @@ export function startAccessRevalidationSweep(roomManager: IRoomManager): AccessR
}
}

/** Set while a session lookup is outstanding, so a timed-out query is never stacked with another. */
let sessionLookupRunning = false

/**
* Disconnects every socket whose handshake session no longer exists or has
* expired. Like the permission scan, only a successful query result acts: a
* failed or timed-out lookup leaves every socket connected until the next pass.
*/
async function disconnectEndedSessions(): Promise<void> {
if (sessionLookupRunning) {
logger.warn('Skipping session liveness check; previous lookup still running')
return
}
const sockets = [...io.sockets.sockets.values()].filter(
(socket): socket is AuthenticatedSocket & { sessionId: string } =>
Boolean((socket as AuthenticatedSocket).sessionId)
)
if (sockets.length === 0) return

sessionLookupRunning = true
const lookup = findLiveSessionIds([...new Set(sockets.map((socket) => socket.sessionId))])
lookup
.catch(() => {})
.finally(() => {
sessionLookupRunning = false
})

let live: Set<string> | typeof SCAN_TIMED_OUT
try {
live = await Promise.race([
lookup,
sleep(SCAN_SOCKET_TIMEOUT_MS).then((): typeof SCAN_TIMED_OUT => SCAN_TIMED_OUT),
])
} catch (error) {
logger.warn('Session liveness check failed; leaving sockets connected', error)
return
}
if (live === SCAN_TIMED_OUT) {
logger.warn('Session liveness check timed out; leaving sockets connected')
return
}

for (const socket of sockets) {
if (live.has(socket.sessionId)) continue
logger.info('Disconnecting socket whose session ended', {
socketId: socket.id,
userId: socket.userId,
})
socket.disconnect(true)
}
}

async function scanMemberships(): Promise<void> {
await disconnectEndedSessions()

const targets = collectScanTargets(io)
if (targets.length === 0) return

Expand Down
3 changes: 3 additions & 0 deletions apps/realtime/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const logger = createLogger('SocketAuth')
export interface AuthenticatedSocket extends Socket {
data: { fileDocPresence?: { roomName: string; user: FileDocPresenceUser } }
userId?: string
/** Better Auth session the handshake token was minted from; the access sweep disconnects the socket once it ends. */
sessionId?: string
userName?: string
userEmail?: string
activeOrganizationId?: string
Expand Down Expand Up @@ -71,6 +73,7 @@ export async function authenticateSocket(socket: AuthenticatedSocket, next: (err

// Store user info in socket for later use
socket.userId = session.user.id
socket.sessionId = session.session.id
socket.userName = session.user.name || session.user.email || 'Unknown User'
socket.userEmail = session.user.email ?? undefined
socket.userImage = session.user.image || null
Expand Down
141 changes: 141 additions & 0 deletions apps/realtime/src/session-liveness.integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { mkdir, writeFile } from 'node:fs/promises'
import { createServer, type Server as HttpServer } from 'node:http'
import { dirname, resolve } from 'node:path'
import { db } from '@sim/db'
import { session, user, verification } from '@sim/db/schema'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { eq } from 'drizzle-orm'
import { Server } from 'socket.io'
import { io as connect, type Socket } from 'socket.io-client'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { type AccessRevalidationSweep, startAccessRevalidationSweep } from '@/access-revalidation'
import { env } from '@/env'
import { authenticateSocket } from '@/middleware/auth'
import { RedisRoomManager } from '@/rooms'

const userId = generateId()
const checks: { name: string; status: string; durationMs: number; error?: string }[] = []
const clients: Socket[] = []
let http: HttpServer
let io: Server
let manager: RedisRoomManager
let sweep: AccessRevalidationSweep
let socketUrl: string

/** Inserts a session row and returns it with a one-time socket token minted from it. */
async function createSession() {
const id = generateId()
const token = generateId()
const oneTimeToken = generateId()
const now = new Date()
const expiresAt = new Date(Date.now() + 60 * 60 * 1000)
await db.insert(session).values({ id, token, userId, expiresAt, createdAt: now, updatedAt: now })
await db.insert(verification).values({
id: generateId(),
identifier: `one-time-token:${oneTimeToken}`,
value: token,
expiresAt: new Date(Date.now() + 60_000),
createdAt: now,
updatedAt: now,
})
return { id, oneTimeToken }
}

/** Opens a socket through the real handshake middleware and records how it later disconnects. */
async function openSocket(oneTimeToken: string) {
const socket = connect(socketUrl, {
auth: { token: oneTimeToken },
reconnection: false,
transports: ['websocket'],
})
clients.push(socket)
const disconnected = new Promise<string>((done) => socket.on('disconnect', done))
await new Promise<void>((done, fail) => {
socket.on('connect', done)
socket.on('connect_error', fail)
})
return { socket, disconnected }
}

function check(name: string, run: () => Promise<void>) {
it(name, async () => {
const start = performance.now()
try {
await run()
checks.push({ name, status: 'passed', durationMs: performance.now() - start })
} catch (error) {
checks.push({
name,
status: 'failed',
durationMs: performance.now() - start,
error: getErrorMessage(error),
})
throw error
}
})
}

beforeAll(async () => {
await db.insert(user).values({
id: userId,
name: 'Fixture',
email: `${userId}@example.invalid`,
emailVerified: true,
createdAt: new Date(),
updatedAt: new Date(),
})
http = createServer()
io = new Server(http)
io.use(authenticateSocket)
manager = new RedisRoomManager(io, env.REDIS_URL)
await manager.initialize()
sweep = startAccessRevalidationSweep(manager)
await new Promise<void>((done) => http.listen(0, '127.0.0.1', done))
const address = http.address()
if (!address || typeof address === 'string') throw new Error('Missing fixture port')
socketUrl = `http://127.0.0.1:${address.port}`
})

describe('session liveness over Socket.IO and Postgres', () => {
check('a socket whose session is deleted is disconnected; a live session stays', async () => {
const revoked = await createSession()
const kept = await createSession()
const revokedSocket = await openSocket(revoked.oneTimeToken)
const keptSocket = await openSocket(kept.oneTimeToken)

await sweep.runOnce()
expect([...io.sockets.sockets.keys()]).toContain(revokedSocket.socket.id)

await db.delete(session).where(eq(session.id, revoked.id))
await sweep.runOnce()

expect(await revokedSocket.disconnected).toBe('io server disconnect')
expect([...io.sockets.sockets.keys()]).toContain(keptSocket.socket.id)
})

check('a socket whose session expired is disconnected', async () => {
const expiring = await createSession()
const { disconnected } = await openSocket(expiring.oneTimeToken)

await db
.update(session)
.set({ expiresAt: new Date(Date.now() - 1000) })
.where(eq(session.id, expiring.id))
await sweep.runOnce()

expect(await disconnected).toBe('io server disconnect')
})
})

afterAll(async () => {
sweep?.stop()
for (const socket of clients) socket.disconnect()
if (io) await new Promise<void>((done) => io.close(() => done()))
await manager?.shutdown()
await db.delete(user).where(eq(user.id, userId))
const report =
process.env.SESSION_LIVENESS_REPORT_PATH ?? resolve('test-results/session-liveness.json')
await mkdir(dirname(report), { recursive: true })
await writeFile(report, JSON.stringify({ checks }, null, 2))
})
2 changes: 2 additions & 0 deletions packages/auth/src/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ interface VerifiedOneTimeTokenSession {
image?: string | null
}
session: {
id: string
activeOrganizationId?: string | null
}
}
Expand Down Expand Up @@ -83,6 +84,7 @@ export function createVerifyAuth(options: VerifyAuthOptions): VerifyAuth {
image: result.user.image ?? null,
},
session: {
id: result.session.id,
activeOrganizationId:
typeof result.session.activeOrganizationId === 'string'
? result.session.activeOrganizationId
Expand Down
Loading