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
19 changes: 16 additions & 3 deletions apps/sim/app/api/table/[tableId]/events/stream/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { type NextRequest, NextResponse } from 'next/server'
import { tableEventStreamContract } from '@/lib/api/contracts/tables'
import { parseRequest } from '@/lib/api/server'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { isSessionActive } from '@/lib/auth/session-liveness'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { createEventStreamResponse } from '@/lib/realtime/event-stream-route'
Expand All @@ -18,8 +19,9 @@ interface RouteContext {
/** GET /api/table/[tableId]/events/stream?from=<lastEventId>
*
* SSE stream of cell-state transitions over the shared durable event log. Auth
* and access are checked here; the replay/tail/poll/heartbeat/prune mechanics
* come from `createEventStreamResponse`. */
* and access are checked here at open and re-checked by `revalidateAccess` while
* the stream runs; the replay/tail/poll/heartbeat/prune mechanics come from
* `createEventStreamResponse`. */
export const GET = withRouteHandler(async (req: NextRequest, context: RouteContext) => {
const requestId = generateRequestId()
const parsed = await parseRequest(tableEventStreamContract, req, context)
Expand All @@ -32,7 +34,17 @@ export const GET = withRouteHandler(async (req: NextRequest, context: RouteConte
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
}

const access = await checkAccess(tableId, { kind: 'user', userId: auth.userId }, 'read')
const userId = auth.userId
const session = auth.principal?.kind === 'session' ? auth.principal : null
// The session check also runs at open: `auth` may come from the signed cookie
// cache, which would let a revoked session reopen the stream after every rotate.
const isSessionLive = async () => !session || (await isSessionActive(session))
const checkReadAccess = () => checkAccess(tableId, { kind: 'user', userId }, 'read')

if (!(await isSessionLive())) {
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
}
const access = await checkReadAccess()
if (!access.ok) return accessError(access, requestId, tableId)

return createEventStreamResponse({
Expand All @@ -42,6 +54,7 @@ export const GET = withRouteHandler(async (req: NextRequest, context: RouteConte
fromEventId,
getLatestEventId: getLatestTableEventId,
readEventsSince: readTableEventsSince,
revalidateAccess: async () => (await isSessionLive()) && (await checkReadAccess()).ok,
extraHeaders: { 'X-Table-Id': tableId },
})
})
23 changes: 23 additions & 0 deletions apps/sim/lib/auth/session-liveness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { SessionPrincipal } from '@sim/auth/principal'
import { db } from '@sim/db'
import { session } from '@sim/db/schema'
import { and, eq, gt } from 'drizzle-orm'
import { isAuthDisabled } from '@/lib/core/config/env-flags'

/**
* Whether the session behind a principal still exists and has not expired. Sign-out
* and every revocation path delete the row, so a long-lived connection authenticated
* once at open re-reads this to learn its credential is gone. With auth disabled the
* anonymous session has no row and cannot be revoked, so it is always active.
*/
export async function isSessionActive({ userId, sessionId }: SessionPrincipal): Promise<boolean> {
if (isAuthDisabled) return true
const [row] = await db
.select({ id: session.id })
.from(session)
.where(
and(eq(session.id, sessionId), eq(session.userId, userId), gt(session.expiresAt, new Date()))
)
.limit(1)
return Boolean(row)
}
108 changes: 108 additions & 0 deletions apps/sim/lib/realtime/event-stream-route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
getPermissionGroupConfigStore,
withPermissionGroupScope,
} from '@/lib/permission-groups/request-scope.server'
import type { EventLogEntry, EventLogReadResult } from '@/lib/realtime/event-log'
import { createEventStreamResponse } from '@/lib/realtime/event-stream-route'

interface TestEntry extends EventLogEntry {
value: string
}

const REVALIDATION_INTERVAL_MS = 30_000

function openStream(revalidateAccess: () => Promise<boolean>) {
const log: TestEntry[] = []
const response = createEventStreamResponse<TestEntry>({
requestId: 'req-1',
streamId: 'table-1',
fromEventId: undefined,
label: 'test',
getLatestEventId: async () => 0,
readEventsSince: async (_streamId, after): Promise<EventLogReadResult<TestEntry>> => ({
status: 'ok',
events: log.filter((entry) => entry.eventId > after),
}),
revalidateAccess,
})
const body = response.body
if (!body) throw new Error('stream response has no body')
const reader = body.getReader()
const decoder = new TextDecoder()
let received = ''
let outcome: 'open' | 'closed' | 'errored' = 'open'
const drained = (async () => {
try {
for (;;) {
const { done, value } = await reader.read()
if (done) break
received += decoder.decode(value)
}
outcome = 'closed'
} catch {
outcome = 'errored'
}
})()
return {
append: (value: string) => log.push({ eventId: log.length + 1, value }),
received: () => received,
outcome: () => outcome,
cancel: async () => {
await reader.cancel()
await drained
},
}
}

describe('createEventStreamResponse access revalidation', () => {
beforeEach(() => {
vi.useFakeTimers()
})

afterEach(() => {
vi.useRealTimers()
})

it('closes within one revalidation interval of the caller losing access', async () => {
let allowed = true
const stream = openStream(async () => allowed)

stream.append('before-revocation')
await vi.advanceTimersByTimeAsync(1_000)
expect(stream.received()).toContain('before-revocation')

allowed = false
await vi.advanceTimersByTimeAsync(REVALIDATION_INTERVAL_MS)
expect(stream.received()).toContain('event: rotate')
expect(stream.outcome()).toBe('closed')
})

it('fails closed when the access re-check throws', async () => {
const stream = openStream(async () => {
throw new Error('db unavailable')
})

await vi.advanceTimersByTimeAsync(REVALIDATION_INTERVAL_MS + 1_000)
expect(stream.outcome()).toBe('errored')
})

it('re-resolves permission groups instead of reusing the opening request memo', async () => {
const storesSeen: unknown[] = []
let openingStore: unknown
const stream = withPermissionGroupScope(() => {
openingStore = getPermissionGroupConfigStore()
return openStream(async () => {
storesSeen.push(getPermissionGroupConfigStore())
return true
})
})

await vi.advanceTimersByTimeAsync(2 * REVALIDATION_INTERVAL_MS + 1_000)

expect(storesSeen).toHaveLength(2)
expect(storesSeen).not.toContain(openingStore)
expect(storesSeen[0]).not.toBe(storesSeen[1])
await stream.cancel()
})
})
53 changes: 41 additions & 12 deletions apps/sim/lib/realtime/event-stream-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@ import { toError } from '@sim/utils/errors'
import { sleep } from '@sim/utils/helpers'
import { NextResponse } from 'next/server'
import { SSE_HEADERS } from '@/lib/core/utils/sse'
import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server'
import type { EventLogEntry, EventLogReadResult } from '@/lib/realtime/event-log'

const logger = createLogger('EventStreamRoute')

const ROTATE_FRAME = `event: rotate\ndata: {}\n\n`

const POLL_INTERVAL_MS = 500
const HEARTBEAT_INTERVAL_MS = 15_000
/** Defensive ceiling; the client reconnects (resuming from lastEventId) past this. */
const MAX_STREAM_DURATION_MS = 4 * 60 * 60 * 1000
/** Matches the realtime access-revalidation sweep, so a revoked member loses both live channels on the same cadence. */
const ACCESS_REVALIDATION_INTERVAL_MS = 30_000

export interface EventStreamResponseOptions<E extends EventLogEntry> {
requestId: string
Expand All @@ -20,6 +25,12 @@ export interface EventStreamResponseOptions<E extends EventLogEntry> {
fromEventId: number | undefined
getLatestEventId: (streamId: string) => Promise<number>
readEventsSince: (streamId: string, afterEventId: number) => Promise<EventLogReadResult<E>>
/**
* Re-runs the route's authorization every {@link ACCESS_REVALIDATION_INTERVAL_MS}:
* `false` closes the stream with `rotate`, a throw errors it, and either way the
* client's reconnect meets the route's own check.
*/
revalidateAccess: () => Promise<boolean>
/** Extra response headers (e.g. `{ 'X-Table-Id': id }`). */
extraHeaders?: Record<string, string>
/** Short label for logs (e.g. 'table'). */
Expand All @@ -39,7 +50,15 @@ export interface EventStreamResponseOptions<E extends EventLogEntry> {
export function createEventStreamResponse<E extends EventLogEntry>(
options: EventStreamResponseOptions<E>
): NextResponse {
const { requestId, streamId, fromEventId, getLatestEventId, readEventsSince, label } = options
const {
requestId,
streamId,
fromEventId,
getLatestEventId,
readEventsSince,
revalidateAccess,
label,
} = options

logger.info(`${label} event stream opened`, { requestId, streamId, fromEventId })

Expand All @@ -51,6 +70,7 @@ export function createEventStreamResponse<E extends EventLogEntry>(
let lastEventId = fromEventId ?? 0
const deadline = Date.now() + MAX_STREAM_DURATION_MS
let nextHeartbeatAt = Date.now() + HEARTBEAT_INTERVAL_MS
let nextRevalidationAt = Date.now() + ACCESS_REVALIDATION_INTERVAL_MS

const enqueue = (text: string) => {
if (closed) return
Expand All @@ -69,10 +89,8 @@ export function createEventStreamResponse<E extends EventLogEntry>(
}
}

const sendPrunedAndClose = (earliestEventId: number | undefined) => {
enqueue(
`event: pruned\ndata: ${JSON.stringify({ earliestEventId: earliestEventId ?? null })}\n\n`
)
const closeWith = (frame: string) => {
enqueue(frame)
if (!closed) {
closed = true
try {
Expand All @@ -81,6 +99,12 @@ export function createEventStreamResponse<E extends EventLogEntry>(
}
}

const sendPrunedAndClose = (earliestEventId: number | undefined) => {
closeWith(
`event: pruned\ndata: ${JSON.stringify({ earliestEventId: earliestEventId ?? null })}\n\n`
)
}

const sendHeartbeat = () => {
// SSE comment line — keeps proxies (ALB default 60s idle) from closing
// the connection during quiet periods.
Expand Down Expand Up @@ -109,6 +133,17 @@ export function createEventStreamResponse<E extends EventLogEntry>(
await sleep(POLL_INTERVAL_MS)
if (closed) return

if (Date.now() >= nextRevalidationAt) {
// A fresh scope per check: the loop inherits the opening request's
// permission-group memo, which would replay its answer for hours.
if (!(await withPermissionGroupScope(revalidateAccess))) {
logger.info(`${label} event stream access revoked`, { requestId, streamId })
closeWith(ROTATE_FRAME)
return
}
nextRevalidationAt = Date.now() + ACCESS_REVALIDATION_INTERVAL_MS
}

const result = await readEventsSince(streamId, lastEventId)
if (result.status === 'pruned') {
sendPrunedAndClose(result.earliestEventId)
Expand All @@ -129,13 +164,7 @@ export function createEventStreamResponse<E extends EventLogEntry>(

// Reached the defensive duration ceiling — close cleanly so the client
// reconnects with the latest lastEventId.
if (!closed) {
enqueue(`event: rotate\ndata: {}\n\n`)
closed = true
try {
controller.close()
} catch {}
}
closeWith(ROTATE_FRAME)
} catch (error) {
logger.error(`${label} event stream error`, {
requestId,
Expand Down
Loading