diff --git a/apps/sim/app/api/table/[tableId]/events/stream/route.ts b/apps/sim/app/api/table/[tableId]/events/stream/route.ts index 3ccc9c39261..124b7d66fb7 100644 --- a/apps/sim/app/api/table/[tableId]/events/stream/route.ts +++ b/apps/sim/app/api/table/[tableId]/events/stream/route.ts @@ -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' @@ -18,8 +19,9 @@ interface RouteContext { /** GET /api/table/[tableId]/events/stream?from= * * 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) @@ -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({ @@ -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 }, }) }) diff --git a/apps/sim/lib/auth/session-liveness.ts b/apps/sim/lib/auth/session-liveness.ts new file mode 100644 index 00000000000..fae53465a97 --- /dev/null +++ b/apps/sim/lib/auth/session-liveness.ts @@ -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 { + 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) +} diff --git a/apps/sim/lib/realtime/event-stream-route.test.ts b/apps/sim/lib/realtime/event-stream-route.test.ts new file mode 100644 index 00000000000..ff6895a431b --- /dev/null +++ b/apps/sim/lib/realtime/event-stream-route.test.ts @@ -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) { + const log: TestEntry[] = [] + const response = createEventStreamResponse({ + requestId: 'req-1', + streamId: 'table-1', + fromEventId: undefined, + label: 'test', + getLatestEventId: async () => 0, + readEventsSince: async (_streamId, after): Promise> => ({ + 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() + }) +}) diff --git a/apps/sim/lib/realtime/event-stream-route.ts b/apps/sim/lib/realtime/event-stream-route.ts index 72fa358bc83..339736d6811 100644 --- a/apps/sim/lib/realtime/event-stream-route.ts +++ b/apps/sim/lib/realtime/event-stream-route.ts @@ -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 { requestId: string @@ -20,6 +25,12 @@ export interface EventStreamResponseOptions { fromEventId: number | undefined getLatestEventId: (streamId: string) => Promise readEventsSince: (streamId: string, afterEventId: number) => Promise> + /** + * 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 /** Extra response headers (e.g. `{ 'X-Table-Id': id }`). */ extraHeaders?: Record /** Short label for logs (e.g. 'table'). */ @@ -39,7 +50,15 @@ export interface EventStreamResponseOptions { export function createEventStreamResponse( options: EventStreamResponseOptions ): 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 }) @@ -51,6 +70,7 @@ export function createEventStreamResponse( 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 @@ -69,10 +89,8 @@ export function createEventStreamResponse( } } - 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 { @@ -81,6 +99,12 @@ export function createEventStreamResponse( } } + 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. @@ -109,6 +133,17 @@ export function createEventStreamResponse( 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) @@ -129,13 +164,7 @@ export function createEventStreamResponse( // 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,