Skip to content

Commit 6a5cdee

Browse files
authored
fix(tables): re-check access on the open table event stream (#10494)
1 parent 84873a3 commit 6a5cdee

4 files changed

Lines changed: 188 additions & 15 deletions

File tree

‎apps/sim/app/api/table/[tableId]/events/stream/route.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { type NextRequest, NextResponse } from 'next/server'
22
import { tableEventStreamContract } from '@/lib/api/contracts/tables'
33
import { parseRequest } from '@/lib/api/server'
44
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
5+
import { isSessionActive } from '@/lib/auth/session-liveness'
56
import { generateRequestId } from '@/lib/core/utils/request'
67
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
78
import { createEventStreamResponse } from '@/lib/realtime/event-stream-route'
@@ -18,8 +19,9 @@ interface RouteContext {
1819
/** GET /api/table/[tableId]/events/stream?from=<lastEventId>
1920
*
2021
* SSE stream of cell-state transitions over the shared durable event log. Auth
21-
* and access are checked here; the replay/tail/poll/heartbeat/prune mechanics
22-
* come from `createEventStreamResponse`. */
22+
* and access are checked here at open and re-checked by `revalidateAccess` while
23+
* the stream runs; the replay/tail/poll/heartbeat/prune mechanics come from
24+
* `createEventStreamResponse`. */
2325
export const GET = withRouteHandler(async (req: NextRequest, context: RouteContext) => {
2426
const requestId = generateRequestId()
2527
const parsed = await parseRequest(tableEventStreamContract, req, context)
@@ -32,7 +34,17 @@ export const GET = withRouteHandler(async (req: NextRequest, context: RouteConte
3234
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
3335
}
3436

35-
const access = await checkAccess(tableId, { kind: 'user', userId: auth.userId }, 'read')
37+
const userId = auth.userId
38+
const session = auth.principal?.kind === 'session' ? auth.principal : null
39+
// The session check also runs at open: `auth` may come from the signed cookie
40+
// cache, which would let a revoked session reopen the stream after every rotate.
41+
const isSessionLive = async () => !session || (await isSessionActive(session))
42+
const checkReadAccess = () => checkAccess(tableId, { kind: 'user', userId }, 'read')
43+
44+
if (!(await isSessionLive())) {
45+
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
46+
}
47+
const access = await checkReadAccess()
3648
if (!access.ok) return accessError(access, requestId, tableId)
3749

3850
return createEventStreamResponse({
@@ -42,6 +54,7 @@ export const GET = withRouteHandler(async (req: NextRequest, context: RouteConte
4254
fromEventId,
4355
getLatestEventId: getLatestTableEventId,
4456
readEventsSince: readTableEventsSince,
57+
revalidateAccess: async () => (await isSessionLive()) && (await checkReadAccess()).ok,
4558
extraHeaders: { 'X-Table-Id': tableId },
4659
})
4760
})
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import type { SessionPrincipal } from '@sim/auth/principal'
2+
import { db } from '@sim/db'
3+
import { session } from '@sim/db/schema'
4+
import { and, eq, gt } from 'drizzle-orm'
5+
import { isAuthDisabled } from '@/lib/core/config/env-flags'
6+
7+
/**
8+
* Whether the session behind a principal still exists and has not expired. Sign-out
9+
* and every revocation path delete the row, so a long-lived connection authenticated
10+
* once at open re-reads this to learn its credential is gone. With auth disabled the
11+
* anonymous session has no row and cannot be revoked, so it is always active.
12+
*/
13+
export async function isSessionActive({ userId, sessionId }: SessionPrincipal): Promise<boolean> {
14+
if (isAuthDisabled) return true
15+
const [row] = await db
16+
.select({ id: session.id })
17+
.from(session)
18+
.where(
19+
and(eq(session.id, sessionId), eq(session.userId, userId), gt(session.expiresAt, new Date()))
20+
)
21+
.limit(1)
22+
return Boolean(row)
23+
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2+
import {
3+
getPermissionGroupConfigStore,
4+
withPermissionGroupScope,
5+
} from '@/lib/permission-groups/request-scope.server'
6+
import type { EventLogEntry, EventLogReadResult } from '@/lib/realtime/event-log'
7+
import { createEventStreamResponse } from '@/lib/realtime/event-stream-route'
8+
9+
interface TestEntry extends EventLogEntry {
10+
value: string
11+
}
12+
13+
const REVALIDATION_INTERVAL_MS = 30_000
14+
15+
function openStream(revalidateAccess: () => Promise<boolean>) {
16+
const log: TestEntry[] = []
17+
const response = createEventStreamResponse<TestEntry>({
18+
requestId: 'req-1',
19+
streamId: 'table-1',
20+
fromEventId: undefined,
21+
label: 'test',
22+
getLatestEventId: async () => 0,
23+
readEventsSince: async (_streamId, after): Promise<EventLogReadResult<TestEntry>> => ({
24+
status: 'ok',
25+
events: log.filter((entry) => entry.eventId > after),
26+
}),
27+
revalidateAccess,
28+
})
29+
const body = response.body
30+
if (!body) throw new Error('stream response has no body')
31+
const reader = body.getReader()
32+
const decoder = new TextDecoder()
33+
let received = ''
34+
let outcome: 'open' | 'closed' | 'errored' = 'open'
35+
const drained = (async () => {
36+
try {
37+
for (;;) {
38+
const { done, value } = await reader.read()
39+
if (done) break
40+
received += decoder.decode(value)
41+
}
42+
outcome = 'closed'
43+
} catch {
44+
outcome = 'errored'
45+
}
46+
})()
47+
return {
48+
append: (value: string) => log.push({ eventId: log.length + 1, value }),
49+
received: () => received,
50+
outcome: () => outcome,
51+
cancel: async () => {
52+
await reader.cancel()
53+
await drained
54+
},
55+
}
56+
}
57+
58+
describe('createEventStreamResponse access revalidation', () => {
59+
beforeEach(() => {
60+
vi.useFakeTimers()
61+
})
62+
63+
afterEach(() => {
64+
vi.useRealTimers()
65+
})
66+
67+
it('closes within one revalidation interval of the caller losing access', async () => {
68+
let allowed = true
69+
const stream = openStream(async () => allowed)
70+
71+
stream.append('before-revocation')
72+
await vi.advanceTimersByTimeAsync(1_000)
73+
expect(stream.received()).toContain('before-revocation')
74+
75+
allowed = false
76+
await vi.advanceTimersByTimeAsync(REVALIDATION_INTERVAL_MS)
77+
expect(stream.received()).toContain('event: rotate')
78+
expect(stream.outcome()).toBe('closed')
79+
})
80+
81+
it('fails closed when the access re-check throws', async () => {
82+
const stream = openStream(async () => {
83+
throw new Error('db unavailable')
84+
})
85+
86+
await vi.advanceTimersByTimeAsync(REVALIDATION_INTERVAL_MS + 1_000)
87+
expect(stream.outcome()).toBe('errored')
88+
})
89+
90+
it('re-resolves permission groups instead of reusing the opening request memo', async () => {
91+
const storesSeen: unknown[] = []
92+
let openingStore: unknown
93+
const stream = withPermissionGroupScope(() => {
94+
openingStore = getPermissionGroupConfigStore()
95+
return openStream(async () => {
96+
storesSeen.push(getPermissionGroupConfigStore())
97+
return true
98+
})
99+
})
100+
101+
await vi.advanceTimersByTimeAsync(2 * REVALIDATION_INTERVAL_MS + 1_000)
102+
103+
expect(storesSeen).toHaveLength(2)
104+
expect(storesSeen).not.toContain(openingStore)
105+
expect(storesSeen[0]).not.toBe(storesSeen[1])
106+
await stream.cancel()
107+
})
108+
})

‎apps/sim/lib/realtime/event-stream-route.ts‎

Lines changed: 41 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,19 @@ import { toError } from '@sim/utils/errors'
33
import { sleep } from '@sim/utils/helpers'
44
import { NextResponse } from 'next/server'
55
import { SSE_HEADERS } from '@/lib/core/utils/sse'
6+
import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server'
67
import type { EventLogEntry, EventLogReadResult } from '@/lib/realtime/event-log'
78

89
const logger = createLogger('EventStreamRoute')
910

11+
const ROTATE_FRAME = `event: rotate\ndata: {}\n\n`
12+
1013
const POLL_INTERVAL_MS = 500
1114
const HEARTBEAT_INTERVAL_MS = 15_000
1215
/** Defensive ceiling; the client reconnects (resuming from lastEventId) past this. */
1316
const MAX_STREAM_DURATION_MS = 4 * 60 * 60 * 1000
17+
/** Matches the realtime access-revalidation sweep, so a revoked member loses both live channels on the same cadence. */
18+
const ACCESS_REVALIDATION_INTERVAL_MS = 30_000
1419

1520
export interface EventStreamResponseOptions<E extends EventLogEntry> {
1621
requestId: string
@@ -20,6 +25,12 @@ export interface EventStreamResponseOptions<E extends EventLogEntry> {
2025
fromEventId: number | undefined
2126
getLatestEventId: (streamId: string) => Promise<number>
2227
readEventsSince: (streamId: string, afterEventId: number) => Promise<EventLogReadResult<E>>
28+
/**
29+
* Re-runs the route's authorization every {@link ACCESS_REVALIDATION_INTERVAL_MS}:
30+
* `false` closes the stream with `rotate`, a throw errors it, and either way the
31+
* client's reconnect meets the route's own check.
32+
*/
33+
revalidateAccess: () => Promise<boolean>
2334
/** Extra response headers (e.g. `{ 'X-Table-Id': id }`). */
2435
extraHeaders?: Record<string, string>
2536
/** Short label for logs (e.g. 'table'). */
@@ -39,7 +50,15 @@ export interface EventStreamResponseOptions<E extends EventLogEntry> {
3950
export function createEventStreamResponse<E extends EventLogEntry>(
4051
options: EventStreamResponseOptions<E>
4152
): NextResponse {
42-
const { requestId, streamId, fromEventId, getLatestEventId, readEventsSince, label } = options
53+
const {
54+
requestId,
55+
streamId,
56+
fromEventId,
57+
getLatestEventId,
58+
readEventsSince,
59+
revalidateAccess,
60+
label,
61+
} = options
4362

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

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

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

72-
const sendPrunedAndClose = (earliestEventId: number | undefined) => {
73-
enqueue(
74-
`event: pruned\ndata: ${JSON.stringify({ earliestEventId: earliestEventId ?? null })}\n\n`
75-
)
92+
const closeWith = (frame: string) => {
93+
enqueue(frame)
7694
if (!closed) {
7795
closed = true
7896
try {
@@ -81,6 +99,12 @@ export function createEventStreamResponse<E extends EventLogEntry>(
8199
}
82100
}
83101

102+
const sendPrunedAndClose = (earliestEventId: number | undefined) => {
103+
closeWith(
104+
`event: pruned\ndata: ${JSON.stringify({ earliestEventId: earliestEventId ?? null })}\n\n`
105+
)
106+
}
107+
84108
const sendHeartbeat = () => {
85109
// SSE comment line — keeps proxies (ALB default 60s idle) from closing
86110
// the connection during quiet periods.
@@ -109,6 +133,17 @@ export function createEventStreamResponse<E extends EventLogEntry>(
109133
await sleep(POLL_INTERVAL_MS)
110134
if (closed) return
111135

136+
if (Date.now() >= nextRevalidationAt) {
137+
// A fresh scope per check: the loop inherits the opening request's
138+
// permission-group memo, which would replay its answer for hours.
139+
if (!(await withPermissionGroupScope(revalidateAccess))) {
140+
logger.info(`${label} event stream access revoked`, { requestId, streamId })
141+
closeWith(ROTATE_FRAME)
142+
return
143+
}
144+
nextRevalidationAt = Date.now() + ACCESS_REVALIDATION_INTERVAL_MS
145+
}
146+
112147
const result = await readEventsSince(streamId, lastEventId)
113148
if (result.status === 'pruned') {
114149
sendPrunedAndClose(result.earliestEventId)
@@ -129,13 +164,7 @@ export function createEventStreamResponse<E extends EventLogEntry>(
129164

130165
// Reached the defensive duration ceiling — close cleanly so the client
131166
// reconnects with the latest lastEventId.
132-
if (!closed) {
133-
enqueue(`event: rotate\ndata: {}\n\n`)
134-
closed = true
135-
try {
136-
controller.close()
137-
} catch {}
138-
}
167+
closeWith(ROTATE_FRAME)
139168
} catch (error) {
140169
logger.error(`${label} event stream error`, {
141170
requestId,

0 commit comments

Comments
 (0)