Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(session-replay): team-scoped JWT authZ for recording-api (#67476)

Tom Piccirellocda4a76fe7fc
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 5ecd4477779e..fb31c1849a65 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -290,6 +290,13 @@ services:
DATABASE_URL: postgres://posthog:posthog@db:5432/${POSTHOG_DB_NAME:-posthog}
CLICKHOUSE_DATABASE: ${CLICKHOUSE_DATABASE:-posthog}
ENCRYPTION_SALT_KEYS: '00beef0000beef0000beef0000beef00'
+ # The image runs as production, so the in-code dev defaults do not apply. Set both
+ # secrets to the values Django uses under DEBUG so local calls authenticate and exercise
+ # the JWT path. These live here rather than in docker-compose.base.yml because hobby
+ # extends that file, and hobby's Django resolves both secrets to empty, so inheriting
+ # them there would make recording-api reject every hobby call.
+ INTERNAL_API_SECRET: 'posthog123'
+ RECORDING_API_JWT_SECRET: 'dev-recording-api-jwt-secret'
depends_on:
redis7:
condition: service_healthy
diff --git a/docker-compose.hobby.yml b/docker-compose.hobby.yml
index e52f5a42598b..d9f79dcffc7a 100644
--- a/docker-compose.hobby.yml
+++ b/docker-compose.hobby.yml
@@ -100,6 +100,7 @@ services:
SESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY: 'any'
OBJECT_STORAGE_ENABLED: true
RECORDING_API_URL: http://recording-api:6738
+ INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-$POSTHOG_SECRET}
ENCRYPTION_SALT_KEYS: $ENCRYPTION_SALT_KEYS
POSTHOG_SKIP_MIGRATION_CHECKS: '1'
PERSONHOG_ADDR: 'personhog-router:50052'
@@ -159,6 +160,7 @@ services:
SESSION_RECORDING_V2_S3_ENDPOINT: http://seaweedfs:8333
OBJECT_STORAGE_ENABLED: true
RECORDING_API_URL: http://recording-api:6738
+ INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-$POSTHOG_SECRET}
ENCRYPTION_SALT_KEYS: $ENCRYPTION_SALT_KEYS
OTEL_SERVICE_NAME: 'posthog'
OTEL_EXPORTER_OTLP_ENDPOINT: ''
@@ -272,6 +274,10 @@ services:
logging: *default-logging
environment:
ENCRYPTION_SALT_KEYS: $ENCRYPTION_SALT_KEYS
+ # Must resolve to the same value as the web and worker services, which send it as
+ # X-Internal-Api-Secret. The JWT signing secret is deliberately left unset here, so hobby
+ # stays on the legacy shared secret until that scheme is rolled out.
+ INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-$POSTHOG_SECRET}
depends_on:
- db
- redis7
diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.ts
index 8227be7ca5f5..de6fcb5e42a8 100644
--- a/nodejs/src/cdp/utils/jwt-utils.ts
+++ b/nodejs/src/cdp/utils/jwt-utils.ts
@@ -1,6 +1,7 @@
import jwt from 'jsonwebtoken'
export enum PosthogJwtAudience {
+ RECORDING_API = 'posthog:recording_api',
SUBSCRIPTION_PREFERENCES = 'posthog:messaging:subscription_preferences',
WORKFLOWS_RESCHEDULE_PARKED = 'posthog:workflows:reschedule_parked',
}
@@ -9,7 +10,7 @@ export class JWT {
private secrets: string[] = []
constructor(commaSeparatedSaltKeys: string) {
- const saltKeys = commaSeparatedSaltKeys.split(',').filter((key) => key)
+ const saltKeys = parseJwtKeys(commaSeparatedSaltKeys)
if (!saltKeys.length) {
throw new Error('Encryption keys are not set')
}
@@ -40,3 +41,23 @@ export class JWT {
throw error
}
}
+
+/** Split a comma-separated key string into usable keys (newest first), trimming each and dropping
+ * empty segments. Trimming keeps this in lockstep with the Python minter's recording_api_signing_keys. */
+export function parseJwtKeys(commaSeparatedSaltKeys: string): string[] {
+ return commaSeparatedSaltKeys
+ .split(',')
+ .map((key) => key.trim())
+ .filter((key) => key)
+}
+
+/** Whether a comma-separated key string yields at least one usable key. */
+export function hasJwtKeys(commaSeparatedSaltKeys: string): boolean {
+ return parseJwtKeys(commaSeparatedSaltKeys).length > 0
+}
+
+/** Build a verifier, or null when no usable key is configured, so a malformed-but-truthy value like
+ * ',' disables JWT instead of throwing at construction. */
+export function makeOptionalJwt(commaSeparatedSaltKeys: string): JWT | null {
+ return hasJwtKeys(commaSeparatedSaltKeys) ? new JWT(commaSeparatedSaltKeys) : null
+}
diff --git a/nodejs/src/common/api/router.ts b/nodejs/src/common/api/router.ts
index b59314feaaf6..b4786e17ef60 100644
--- a/nodejs/src/common/api/router.ts
+++ b/nodejs/src/common/api/router.ts
@@ -26,6 +26,9 @@ export function initializePrometheusLabels(
}
export interface SetupExpressAppOptions {
+ // Path prefixes exempt from the shared-secret middleware. Used by servers that own auth on those
+ // paths themselves, such as recording-api verifying a team-scoped JWT across the whole prefix.
+ internalApiAuthExcludedPathPrefixes?: string[]
internalApiSecret?: string
// Comma-separated previous secrets still accepted for verification during rotation.
internalApiSecretFallbacks?: string
@@ -63,6 +66,7 @@ export function setupExpressApp(options: SetupExpressAppOptions = {}): express.A
.split(',')
.map((s) => s.trim())
.filter(Boolean),
+ excludedPathPrefixes: options.internalApiAuthExcludedPathPrefixes,
})
)
diff --git a/nodejs/src/servers/base-server.ts b/nodejs/src/servers/base-server.ts
index 5010ddd5039d..df45489e9d6b 100644
--- a/nodejs/src/servers/base-server.ts
+++ b/nodejs/src/servers/base-server.ts
@@ -4,7 +4,7 @@ import * as schedule from 'node-schedule'
import { Counter } from 'prom-client'
import express from 'ultimate-express'
-import { setupCommonRoutes, setupExpressApp } from '~/common/api/router'
+import { SetupExpressAppOptions, setupCommonRoutes, setupExpressApp } from '~/common/api/router'
import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { isTestEnv } from '~/common/utils/env-utils'
@@ -69,10 +69,14 @@ export class ServerLifecycle {
private podTerminationTimer?: NodeJS.Timeout
private processListeners: Map<string, (...args: any[]) => void> = new Map()
- constructor(private config: BaseServerConfig) {
+ constructor(
+ private config: BaseServerConfig,
+ expressAppOptions: Omit<SetupExpressAppOptions, 'internalApiSecret' | 'internalApiSecretFallbacks'> = {}
+ ) {
this.expressApp = setupExpressApp({
internalApiSecret: this.config.INTERNAL_API_SECRET,
internalApiSecretFallbacks: this.config.INTERNAL_API_SECRET_FALLBACKS,
+ ...expressAppOptions,
})
this.nodeInstrumentation = new NodeInstrumentation(this.config.INSTRUMENT_THREAD_PERFORMANCE)
configureEventLoopYield(this.config.EVENT_LOOP_YIELD_THRESHOLD_MS)
diff --git a/nodejs/src/servers/recording-api-server.ts b/nodejs/src/servers/recording-api-server.ts
index dee9cdebab85..1c5cc4113beb 100644
--- a/nodejs/src/servers/recording-api-server.ts
+++ b/nodejs/src/servers/recording-api-server.ts
@@ -1,6 +1,7 @@
import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
import { PostgresRouter, PostgresRouterConfig } from '~/common/utils/db/postgres'
+import { isProdEnv } from '~/common/utils/env-utils'
import { logger } from '~/common/utils/logger'
import {
getDefaultSessionRecordingApiConfig,
@@ -10,6 +11,7 @@ import {
KafkaSessionreplayProducerEnvConfig,
getDefaultKafkaSessionreplayProducerEnvConfig,
} from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
+import { assertRecordingApiAuthConfigured } from '~/session-replay/recording-api/auth'
import { createProducerRegistry } from '~/session-replay/recording-api/outputs/producer-registry'
import { createOutputsRegistry } from '~/session-replay/recording-api/outputs/registry'
import { RecordingApi } from '~/session-replay/recording-api/recording-api'
@@ -17,6 +19,7 @@ import {
RecordingApiConfig,
RecordingApiOutputsConfig,
type RecordingApiProducerName,
+ getDefaultRecordingApiAuthConfig,
getDefaultRecordingApiOutputsConfig,
} from '~/session-replay/recording-api/types'
@@ -49,9 +52,14 @@ export class RecordingApiServer implements NodeServer {
...overrideConfigWithEnv(getDefaultSessionRecordingApiConfig()),
...overrideConfigWithEnv(getDefaultKafkaSessionreplayProducerEnvConfig()),
...overrideConfigWithEnv(getDefaultRecordingApiOutputsConfig()),
+ ...overrideConfigWithEnv(getDefaultRecordingApiAuthConfig()),
...config,
}
- this.lifecycle = new ServerLifecycle(this.config)
+ // recording-api verifies a team-scoped JWT per route, so exempt its routes from the
+ // shared-secret middleware (callers send a Bearer token, not X-Internal-Api-Secret).
+ this.lifecycle = new ServerLifecycle(this.config, {
+ internalApiAuthExcludedPathPrefixes: ['/api/projects/'],
+ })
}
async start(): Promise<void> {
@@ -66,6 +74,13 @@ export class RecordingApiServer implements NodeServer {
}
private async startServices(): Promise<void> {
+ assertRecordingApiAuthConfigured({
+ isProd: isProdEnv(),
+ jwtSecret: this.config.RECORDING_API_JWT_SECRET,
+ allowLegacySecret: this.config.RECORDING_API_ALLOW_LEGACY_SECRET,
+ legacySecret: this.config.INTERNAL_API_SECRET,
+ })
+
this.postgres = new PostgresRouter(this.config, this.config.PLUGIN_SERVER_MODE ?? undefined)
logger.info('👍', 'Postgres Router ready')
diff --git a/nodejs/src/session-replay/recording-api/auth.test.ts b/nodejs/src/session-replay/recording-api/auth.test.ts
new file mode 100644
index 000000000000..db105dca2b83
--- /dev/null
+++ b/nodejs/src/session-replay/recording-api/auth.test.ts
@@ -0,0 +1,286 @@
+import { NextFunction, Request, Response } from 'ultimate-express'
+
+import { JWT, PosthogJwtAudience } from '~/cdp/utils/jwt-utils'
+
+import { RecordingApiAuthOptions, assertRecordingApiAuthConfigured, createRecordingApiAuthMiddleware } from './auth'
+
+describe('createRecordingApiAuthMiddleware', () => {
+ const JWT_SECRET = 'recording-api-secret-key'
+ const LEGACY_SECRET = 'legacy-internal-secret'
+
+ const mintToken = (
+ claims: { team_id: number; op: string },
+ secret = JWT_SECRET,
+ expiresIn: string | number = '5m'
+ ) => new JWT(secret).sign(claims, PosthogJwtAudience.RECORDING_API, { expiresIn })
+
+ const mockResponse = () => {
+ const res = {} as Response
+ res.status = jest.fn().mockReturnValue(res)
+ res.json = jest.fn().mockReturnValue(res)
+ return res
+ }
+
+ // Mirrors what the middleware actually receives: it is mounted on the '/api/projects' prefix, so
+ // ultimate-express strips the mount from req.path and exposes no req.params, leaving originalUrl
+ // as the only source of team_id.
+ const mockRequest = (teamIdSegment: string, headers: Record<string, string> = {}) =>
+ ({
+ headers,
+ originalUrl: `/api/projects/${teamIdSegment}/recordings/abc/block`,
+ path: `/${teamIdSegment}/recordings/abc/block`,
+ method: 'GET',
+ }) as unknown as Request
+
+ const run = (opts: Partial<RecordingApiAuthOptions>, req: Request) => {
+ const middleware = createRecordingApiAuthMiddleware({
+ jwtSecret: JWT_SECRET,
+ legacySecret: LEGACY_SECRET,
+ allowLegacySecret: false,
+ op: 'read',
+ ...opts,
+ })
+ const res = mockResponse()
+ const next = jest.fn() as NextFunction
+ middleware(req, res, next)
+ return { res, next }
+ }
+
+ const bearer = (token: string) => ({ authorization: `Bearer ${token}` })
+
+ it('skips authorization when no jwt secret configured (local dev)', () => {
+ const { res, next } = run({ jwtSecret: '' }, mockRequest('123'))
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('allows a valid read token whose team matches the path', () => {
+ const { res, next } = run({ op: 'read' }, mockRequest('123', bearer(mintToken({ team_id: 123, op: 'read' }))))
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('allows a valid delete token on the delete route', () => {
+ const { res, next } = run(
+ { op: 'delete' },
+ mockRequest('123', bearer(mintToken({ team_id: 123, op: 'delete' })))
+ )
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('rejects a token scoped to a different team (IDOR guard)', () => {
+ const { res, next } = run({ op: 'read' }, mockRequest('123', bearer(mintToken({ team_id: 456, op: 'read' }))))
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(403)
+ })
+
+ // A non-canonical segment must never authorize, because the route handler is free to parse it
+ // differently than this middleware does. Each case is paired with the team_id it would coerce to,
+ // so a lenient Number() parse here would wrongly match the token and let the request through.
+ it.each([
+ ['0123', 123],
+ ['1e3', 1000],
+ ['0x10', 16],
+ ['+123', 123],
+ ['123.0', 123],
+ ])('rejects non-canonical team segment %p even though it coerces to %p', (segment, coercedTeamId) => {
+ const { res, next } = run(
+ { op: 'read' },
+ mockRequest(segment, bearer(mintToken({ team_id: coercedTeamId as number, op: 'read' })))
+ )
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(403)
+ })
+
+ it('rejects a read token on the delete route', () => {
+ const { res, next } = run({ op: 'delete' }, mockRequest('123', bearer(mintToken({ team_id: 123, op: 'read' }))))
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(403)
+ })
+
+ it('rejects a delete token on a read route', () => {
+ const { res, next } = run({ op: 'read' }, mockRequest('123', bearer(mintToken({ team_id: 123, op: 'delete' }))))
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(403)
+ })
+
+ it.each([
+ ['no token', {}],
+ ['garbage token', bearer('not-a-jwt')],
+ ['token signed with an unknown key', bearer(mintToken({ team_id: 123, op: 'read' }, 'attacker-key'))],
+ ['expired token', bearer(mintToken({ team_id: 123, op: 'read' }, JWT_SECRET, -60))],
+ ])('rejects request with %s (401)', (_, headers) => {
+ const { res, next } = run({ op: 'read' }, mockRequest('123', headers))
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(401)
+ })
+
+ it('rejects a token for the wrong audience', () => {
+ const wrongAud = new JWT(JWT_SECRET).sign(
+ { team_id: 123, op: 'read' },
+ PosthogJwtAudience.SUBSCRIPTION_PREFERENCES,
+ { expiresIn: '5m' }
+ )
+ const { res, next } = run({ op: 'read' }, mockRequest('123', bearer(wrongAud)))
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(401)
+ })
+
+ describe('legacy secret fallback (transition)', () => {
+ it('accepts a valid X-Internal-Api-Secret when allowLegacySecret is true', () => {
+ const { res, next } = run(
+ { allowLegacySecret: true },
+ mockRequest('123', { 'x-internal-api-secret': LEGACY_SECRET })
+ )
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('rejects the same legacy secret once allowLegacySecret is false', () => {
+ const { res, next } = run(
+ { allowLegacySecret: false },
+ mockRequest('123', { 'x-internal-api-secret': LEGACY_SECRET })
+ )
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(401)
+ })
+
+ it('still accepts a valid JWT when legacy is disabled', () => {
+ const { res, next } = run(
+ { allowLegacySecret: false },
+ mockRequest('123', bearer(mintToken({ team_id: 123, op: 'read' })))
+ )
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('rejects an invalid legacy secret', () => {
+ const { res, next } = run(
+ { allowLegacySecret: true },
+ mockRequest('123', { 'x-internal-api-secret': 'wrong' })
+ )
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(401)
+ })
+ })
+
+ describe('key rotation (new_key,old_key)', () => {
+ it('verifies a token minted under the new (signing) key while both keys are configured', () => {
+ const newToken = mintToken({ team_id: 123, op: 'read' }, 'new-key')
+ const { res, next } = run(
+ { jwtSecret: 'new-key,old-key', op: 'read' },
+ mockRequest('123', bearer(newToken))
+ )
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('verifies a token minted under the old key while both keys are configured', () => {
+ const oldToken = mintToken({ team_id: 123, op: 'read' }, 'old-key')
+ const { res, next } = run(
+ { jwtSecret: 'new-key,old-key', op: 'read' },
+ mockRequest('123', bearer(oldToken))
+ )
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('rejects a token signed by a key outside the configured set', () => {
+ const rogue = mintToken({ team_id: 123, op: 'read' }, 'rogue-key')
+ const { res, next } = run({ jwtSecret: 'new-key,old-key', op: 'read' }, mockRequest('123', bearer(rogue)))
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(401)
+ })
+
+ it('rejects a token minted under a retired key once it is dropped', () => {
+ const oldToken = mintToken({ team_id: 123, op: 'read' }, 'old-key')
+ const { res, next } = run({ jwtSecret: 'new-key', op: 'read' }, mockRequest('123', bearer(oldToken)))
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(401)
+ })
+ })
+
+ describe('progressive rollout (legacy secret before JWT is enabled)', () => {
+ it('requires the legacy secret when no JWT secret is configured', () => {
+ const req = mockRequest('123', { 'x-internal-api-secret': LEGACY_SECRET })
+ const { res, next } = run({ jwtSecret: '', allowLegacySecret: true }, req)
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('rejects a request with no legacy secret when JWT is not yet configured', () => {
+ const { res, next } = run({ jwtSecret: '', allowLegacySecret: true }, mockRequest('123'))
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(401)
+ })
+
+ it('skips entirely only when neither JWT nor legacy secret is configured (local dev)', () => {
+ const { res, next } = run({ jwtSecret: '', legacySecret: '', allowLegacySecret: true }, mockRequest('123'))
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('treats a malformed-but-truthy secret (comma only) as JWT-disabled without crashing', () => {
+ // ',' yields zero keys after split/filter; the middleware must not construct a JWT verifier
+ // (which throws on empty keys) and should fall back to the legacy secret instead.
+ const req = mockRequest('123', { 'x-internal-api-secret': LEGACY_SECRET })
+ expect(() => run({ jwtSecret: ',', allowLegacySecret: true }, req)).not.toThrow()
+ const { res, next } = run({ jwtSecret: ',', allowLegacySecret: true }, req)
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('cross-language contract (must match the Python minter)', () => {
+ it('audience enum value is the shared literal', () => {
+ // Pinned to the same string as posthog/jwt.py PosthogJwtAudience.RECORDING_API.
+ expect(PosthogJwtAudience.RECORDING_API).toBe('posthog:recording_api')
+ })
+
+ it('accepts a token built with the raw audience literal and the claim names Python emits', () => {
+ // Sign with the literal audience (not the enum) and the exact claim names the Python helper
+ // produces, so a drift in the Node enum value or the claims the middleware reads breaks this.
+ const token = new JWT(JWT_SECRET).sign(
+ { team_id: 123, op: 'read' },
+ 'posthog:recording_api' as PosthogJwtAudience,
+ {
+ expiresIn: '5m',
+ }
+ )
+ const { res, next } = run({ op: 'read' }, mockRequest('123', bearer(token)))
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+ })
+})
+
+describe('assertRecordingApiAuthConfigured', () => {
+ const base = { isProd: true, jwtSecret: '', allowLegacySecret: true, legacySecret: '' }
+
+ it('throws in production when neither a JWT nor a legacy secret is configured', () => {
+ expect(() => assertRecordingApiAuthConfigured(base)).toThrow(/no auth configured in production/)
+ })
+
+ it('throws in production when the only key is a malformed comma-only value', () => {
+ expect(() => assertRecordingApiAuthConfigured({ ...base, jwtSecret: ',' })).toThrow()
+ })
+
+ it('throws in production when legacy is disabled and there is no JWT secret', () => {
+ expect(() =>
+ assertRecordingApiAuthConfigured({ ...base, allowLegacySecret: false, legacySecret: 'legacy' })
+ ).toThrow()
+ })
+
+ it('passes in production with a JWT secret', () => {
+ expect(() => assertRecordingApiAuthConfigured({ ...base, jwtSecret: 'k' })).not.toThrow()
+ })
+
+ it('passes in production with only the legacy secret (pre-rollout)', () => {
+ expect(() => assertRecordingApiAuthConfigured({ ...base, legacySecret: 'legacy' })).not.toThrow()
+ })
+
+ it('passes outside production even with nothing configured (local dev)', () => {
+ expect(() => assertRecordingApiAuthConfigured({ ...base, isProd: false })).not.toThrow()
+ })
+})
diff --git a/nodejs/src/session-replay/recording-api/auth.ts b/nodejs/src/session-replay/recording-api/auth.ts
new file mode 100644
index 000000000000..95ba814f013c
--- /dev/null
+++ b/nodejs/src/session-replay/recording-api/auth.ts
@@ -0,0 +1,149 @@
+import crypto from 'crypto'
+import { NextFunction, Request, Response } from 'ultimate-express'
+
+import { JWT, PosthogJwtAudience, hasJwtKeys, makeOptionalJwt } from '~/cdp/utils/jwt-utils'
+import { INTERNAL_SERVICE_CALL_HEADER_NAME } from '~/common/api/middleware/internal-api-auth'
+import { logger } from '~/common/utils/logger'
+
+/**
+ * Authorization for recording-api routes.
+ *
+ * Each route requires a team + operation scoped JWT (audience `posthog:recording_api`) minted by
+ * an authorized service: the token's `team_id` must match the `:team_id` in the path and its `op`
+ * must match the route (read vs delete). During migration the legacy `X-Internal-Api-Secret` is
+ * accepted as a fallback while `allowLegacySecret` is true; the final cutover flips that flag off.
+ */
+
+export type RecordingApiOp = 'read' | 'delete'
+
+// jsonwebtoken tolerates up to this many seconds of clock skew between minter and verifier.
+const CLOCK_TOLERANCE_SECONDS = 30
+
+export interface RecordingApiAuthOptions {
+ // Comma-separated keys (newest first) for zero-downtime rotation. Empty disables JWT auth (dev only).
+ jwtSecret: string
+ legacySecret: string
+ allowLegacySecret: boolean
+ op: RecordingApiOp
+}
+
+function getHeader(req: Request, name: string): string | undefined {
+ // Node lowercases all incoming header field names, so a single lowercased lookup is sufficient.
+ const value = req.headers[name.toLowerCase()]
+ return typeof value === 'string' ? value : undefined
+}
+
+function getBearerToken(req: Request): string | undefined {
+ const header = getHeader(req, 'authorization')
+ return header && /^Bearer /i.test(header) ? header.slice('Bearer '.length) : undefined
+}
+
+// The team_id from the request URL. This middleware is mounted on a path prefix, where
+// ultimate-express does not surface req.params, so the segment is read from the URL directly;
+// originalUrl preserves the full path across the mount. Only canonical digits are accepted, so a
+// segment like '0123', '1e3' or '0x10' yields NaN and fails the team check instead of depending on
+// the route handler coercing it to the same number this does. Leading zeros are rejected too, so
+// there is exactly one URL spelling of any given team.
+function pathTeamId(req: Request): number {
+ const match = /\/api\/projects\/([^/?]+)/.exec(req.originalUrl ?? req.path ?? '')
+ return match && /^(0|[1-9]\d*)$/.test(match[1]) ? parseInt(match[1], 10) : NaN
+}
+
+function timingSafeEqual(a: string, b: string): boolean {
+ // Trim so a secret mounted from a file with a trailing newline still matches a sender that
+ // trimmed it (mirrors the shared internal-api-auth middleware's newline handling).
+ const ab = Buffer.from(a.trim())
+ const bb = Buffer.from(b.trim())
+ return ab.length === bb.length && crypto.timingSafeEqual(ab, bb)
+}
+
+/**
+ * Fail closed in production: recording routes must have at least one auth mechanism active. Before the
+ * JWT scheme is rolled out the legacy X-Internal-Api-Secret protects prod; once RECORDING_API_JWT_SECRET
+ * is set, the JWT does. Only refuse to boot if neither is configured. Uses the same key parsing as the
+ * verifier so a malformed-but-truthy value (e.g. ',') counts as "no JWT configured".
+ */
+export function assertRecordingApiAuthConfigured(opts: {
+ isProd: boolean
+ jwtSecret: string
+ allowLegacySecret: boolean
+ legacySecret: string
+}): void {
+ const hasJwtSecret = hasJwtKeys(opts.jwtSecret || '')
+ const hasLegacySecret = opts.allowLegacySecret && !!opts.legacySecret
+ if (opts.isProd && !hasJwtSecret && !hasLegacySecret) {
+ throw new Error(
+ 'recording-api has no auth configured in production: set RECORDING_API_JWT_SECRET, ' +
+ 'or keep RECORDING_API_ALLOW_LEGACY_SECRET enabled with INTERNAL_API_SECRET set'
+ )
+ }
+}
+
+export function createRecordingApiAuthMiddleware(options: RecordingApiAuthOptions) {
+ const { jwtSecret, legacySecret, allowLegacySecret, op } = options
+ // Build the verifier once. Comma-separated keys give zero-downtime rotation (verify against all);
+ // a malformed/empty value yields no keys and disables JWT (null) rather than throwing. `|| ''`
+ // guards against a partial runtime config where the field is absent.
+ const jwt = makeOptionalJwt(jwtSecret || '')
+ const legacyEnabled = allowLegacySecret && !!legacySecret
+
+ return (req: Request, res: Response, next: NextFunction): void => {
+ // Nothing configured at all (local dev): allow. In every other case some auth is required —
+ // before the JWT scheme is enabled in an environment, the legacy secret still protects it.
+ if (!jwt && !legacyEnabled) {
+ next()
+ return
+ }
+
+ if (jwt) {
+ const bearer = getBearerToken(req)
+ if (bearer) {
+ let payload: ReturnType<JWT['verify']>
+ try {
+ payload = jwt.verify(bearer, PosthogJwtAudience.RECORDING_API, {
+ // Pin HS256 to match the Python minter (encode/decode pin JWT_ALGORITHM);
+ // don't accept other HMAC variants the library would otherwise allow.
+ algorithms: ['HS256'],
+ clockTolerance: CLOCK_TOLERANCE_SECONDS,
+ })
+ } catch (err) {
+ // Log the failure class (e.g. TokenExpiredError, JsonWebTokenError) — never the token —
+ // so rollout/rotation 401s are diagnosable. Then fall through to the legacy secret or 401.
+ logger.warn('Recording API JWT verification failed', {
+ reason: err instanceof Error ? err.name : 'unknown',
+ path: req.path,
+ })
+ payload = undefined
+ }
+ if (payload && typeof payload === 'object') {
+ const claims = payload as { team_id?: unknown; op?: unknown }
+ const tokenTeamId = Number(claims.team_id)
+ const requestTeamId = pathTeamId(req)
+ if (!Number.isInteger(tokenTeamId) || tokenTeamId !== requestTeamId) {
+ logger.warn('Recording API token team mismatch', { path: req.path })
+ res.status(403).json({ error: 'Forbidden: token not scoped to this team' })
+ return
+ }
+ if (claims.op !== op) {
+ logger.warn('Recording API token operation mismatch', { path: req.path, expected: op })
+ res.status(403).json({ error: 'Forbidden: token not valid for this operation' })
+ return
+ }
+ next()
+ return
+ }
+ // Bearer present but invalid — fall through to the legacy secret (transition) or reject.
+ }
+ }
+
+ if (legacyEnabled) {
+ const provided = getHeader(req, INTERNAL_SERVICE_CALL_HEADER_NAME)
+ if (provided && timingSafeEqual(provided, legacySecret)) {
+ next()
+ return
+ }
+ }
+
+ res.status(401).json({ error: 'Unauthorized' })
+ }
+}
diff --git a/nodejs/src/session-replay/recording-api/recording-api.ts b/nodejs/src/session-replay/recording-api/recording-api.ts
index a147cf27e144..5dee568b4ef3 100644
--- a/nodejs/src/session-replay/recording-api/recording-api.ts
+++ b/nodejs/src/session-replay/recording-api/recording-api.ts
@@ -16,6 +16,7 @@ import { SessionMetadataStore } from '~/ingestion/pipelines/sessionreplay/shared
import { ReplayEventsOutput, SessionFeaturesOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginServerService, RedisPool } from '~/types'
+import { createRecordingApiAuthMiddleware } from './auth'
import { RecordingService } from './recording-service'
import { DeleteRecordingsBodySchema, GetBlockQuerySchema, RecordingParamsSchema, TeamParamsSchema } from './schemas'
import { KeyStore, RecordingApiConfig, RecordingDecryptor } from './types'
@@ -186,6 +187,23 @@ export class RecordingApi {
const blocksPath = '/api/projects/:team_id/recordings/:session_id/blocks'
+ const auth = (op: 'read' | 'delete') =>
+ createRecordingApiAuthMiddleware({
+ jwtSecret: this.config.RECORDING_API_JWT_SECRET,
+ legacySecret: this.config.INTERNAL_API_SECRET,
+ allowLegacySecret: this.config.RECORDING_API_ALLOW_LEGACY_SECRET,
+ op,
+ })
+ const readAuth = auth('read')
+ const deleteAuth = auth('delete')
+
+ // Mounted on the whole '/api/projects' prefix, matching what the shared-secret middleware
+ // exempts, rather than on the recording routes alone. Anything under the prefix that this
+ // router does not handle then still needs a valid token and gets a 401, so a route added
+ // later cannot ship unauthenticated. op comes from the method: GET reads, anything mutating
+ // gets the stricter delete scope. Registered before the routes so it runs first.
+ router.use('/api/projects', (req, res, next) => (req.method === 'GET' ? readAuth : deleteAuth)(req, res, next))
+
router.get(blockPath, asyncHandler(this.getBlock))
router.get(blocksPath, asyncHandler(this.listBlocks))
router.post('/api/projects/:team_id/recordings/delete', asyncHandler(this.deleteRecordings))
diff --git a/nodejs/src/session-replay/recording-api/types.ts b/nodejs/src/session-replay/recording-api/types.ts
index 73125f8ce383..e2c00b917f01 100644
--- a/nodejs/src/session-replay/recording-api/types.ts
+++ b/nodejs/src/session-replay/recording-api/types.ts
@@ -9,6 +9,7 @@ import {
KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS,
KAFKA_CLICKHOUSE_SESSION_REPLAY_FEATURES,
} from '~/common/config/kafka-topics'
+import { isProdEnv } from '~/common/utils/env-utils'
import { SessionRecordingApiConfig, SessionRecordingConfig } from '~/ingestion/pipelines/sessionreplay/config'
import {
INGESTION_SESSIONREPLAY_PRODUCER,
@@ -35,13 +36,34 @@ export {
type SessionState,
} from '~/ingestion/pipelines/sessionreplay/shared/types'
+/**
+ * Recording-api authorization config.
+ *
+ * `RECORDING_API_JWT_SECRET` is a dedicated signing secret (comma-separated `new_key,old_key` for
+ * rotation), kept off the fleet-wide `JWT_SIGNING_KEY` so only the designated minters can produce
+ * valid tokens. `RECORDING_API_ALLOW_LEGACY_SECRET` keeps the old `X-Internal-Api-Secret` accepted
+ * during migration; flip it off at cutover.
+ */
+export type RecordingApiAuthConfig = {
+ RECORDING_API_JWT_SECRET: string
+ RECORDING_API_ALLOW_LEGACY_SECRET: boolean
+}
+
+export function getDefaultRecordingApiAuthConfig(): RecordingApiAuthConfig {
+ return {
+ // Dev/test default matches the Django/Temporal minters so local end-to-end calls validate.
+ RECORDING_API_JWT_SECRET: isProdEnv() ? '' : 'dev-recording-api-jwt-secret',
+ RECORDING_API_ALLOW_LEGACY_SECRET: true,
+ }
+}
+
/**
* Configuration for the Recording API.
* Postgres is passed as an explicit constructor param, not included here.
*/
export type RecordingApiConfig = Pick<
CommonConfig,
- 'KAFKA_CLIENT_RACK' | 'REDIS_POOL_MIN_SIZE' | 'REDIS_POOL_MAX_SIZE'
+ 'KAFKA_CLIENT_RACK' | 'REDIS_POOL_MIN_SIZE' | 'REDIS_POOL_MAX_SIZE' | 'INTERNAL_API_SECRET'
> &
Pick<
SessionRecordingApiConfig,
@@ -63,7 +85,8 @@ export type RecordingApiConfig = Pick<
| 'SESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY'
| 'SESSION_RECORDING_V2_S3_BUCKET'
| 'SESSION_RECORDING_V2_S3_PREFIX'
- >
+ > &
+ RecordingApiAuthConfig
/**
* Recording API outputs — topic and producer routing per output. All keys
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/block-proxy.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/block-proxy.test.ts
index 9bf4ed760119..89681abfd2b0 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/block-proxy.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/block-proxy.test.ts
@@ -59,6 +59,21 @@ describe('BlockProxy', () => {
)
})
+ it('relays the recording_api_token as a bearer token when present', async () => {
+ mockInternalFetch.mockResolvedValue({
+ status: 200,
+ json: jest.fn().mockResolvedValue({ blocks: [] }),
+ })
+
+ const proxy = new BlockProxy(testCfg, mockLog)
+ await proxy.fetchBlocks(baseInput({ recording_api_token: 'minted-token' }))
+
+ expect(mockInternalFetch).toHaveBeenCalledWith(
+ 'http://localhost:6738/api/projects/1/recordings/test-session-123/blocks',
+ { headers: { 'X-Internal-Api-Secret': 'test-secret', Authorization: 'Bearer minted-token' } }
+ )
+ })
+
it('throws RasterizationError on non-ok response', async () => {
mockInternalFetch.mockResolvedValue({
status: 404,
@@ -111,13 +126,13 @@ describe('BlockProxy', () => {
}
}
- async function createProxyWithBlocks(): Promise<BlockProxy> {
+ async function createProxyWithBlocks(input: RasterizeRecordingInput = baseInput()): Promise<BlockProxy> {
mockInternalFetch.mockResolvedValueOnce({
status: 200,
json: jest.fn().mockResolvedValue({ blocks }),
})
const proxy = new BlockProxy(testCfg, mockLog)
- await proxy.fetchBlocks(baseInput())
+ await proxy.fetchBlocks(input)
mockInternalFetch.mockReset()
return proxy
}
@@ -148,6 +163,22 @@ describe('BlockProxy', () => {
)
})
+ it('relays the recording_api_token as a bearer token when present', async () => {
+ const proxy = await createProxyWithBlocks(baseInput({ recording_api_token: 'minted-token' }))
+
+ mockInternalFetch.mockResolvedValue({
+ status: 200,
+ headers: { 'content-type': 'application/jsonl' },
+ text: jest.fn().mockResolvedValue('{"data":"test"}'),
+ })
+
+ await proxy.handleRequest(mockBlockRequest('/__blocks/0') as any, '/__blocks/0')
+
+ expect(mockInternalFetch).toHaveBeenCalledWith(expect.stringContaining('/block?'), {
+ headers: { 'X-Internal-Api-Secret': 'test-secret', Authorization: 'Bearer minted-token' },
+ })
+ })
+
it('returns 404 for out-of-range index', async () => {
const proxy = await createProxyWithBlocks()
const blockRequest = mockBlockRequest('/__blocks/5')
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts b/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
index 727b142f3024..4bcd9681ffe9 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
@@ -16,6 +16,7 @@ export class BlockProxy {
private blocks: RecordingBlock[] = []
private teamId = 0
private sessionId = ''
+ private recordingApiToken = ''
constructor(
private cfg: { recordingApiBaseUrl: string; recordingApiSecret: string },
@@ -26,13 +27,27 @@ export class BlockProxy {
return this.blocks.length
}
+ // Send both the legacy shared secret (when configured) and the relayed team-scoped JWT (when one
+ // was minted upstream), so recording-api accepts either and rollout stays order-independent.
+ private authHeaders(): Record<string, string> {
+ const headers: Record<string, string> = {}
+ if (this.cfg.recordingApiSecret) {
+ headers['X-Internal-Api-Secret'] = this.cfg.recordingApiSecret
+ }
+ if (this.recordingApiToken) {
+ headers['Authorization'] = `Bearer ${this.recordingApiToken}`
+ }
+ return headers
+ }
+
async fetchBlocks(input: RasterizeRecordingInput): Promise<number> {
this.teamId = input.team_id
this.sessionId = input.session_id
+ this.recordingApiToken = input.recording_api_token ?? ''
const url = `${this.cfg.recordingApiBaseUrl}/api/projects/${input.team_id}/recordings/${input.session_id}/blocks`
const resp = await internalFetch(url, {
- headers: { 'X-Internal-Api-Secret': this.cfg.recordingApiSecret },
+ headers: this.authHeaders(),
})
if (resp.status < 200 || resp.status >= 300) {
const body = await resp.text()
@@ -72,7 +87,7 @@ export class BlockProxy {
const apiBase = `${this.cfg.recordingApiBaseUrl}/api/projects`
const url = `${apiBase}/${this.teamId}/recordings/${this.sessionId}/block?${params}`
const resp = await internalFetch(url, {
- headers: { 'X-Internal-Api-Secret': this.cfg.recordingApiSecret },
+ headers: this.authHeaders(),
})
if (resp.status < 200 || resp.status >= 300) {
const text = await resp.text()
diff --git a/nodejs/src/session-replay/recording-rasterizer/types.ts b/nodejs/src/session-replay/recording-rasterizer/types.ts
index 3dd9aaa1e428..793a76955b3f 100644
--- a/nodejs/src/session-replay/recording-rasterizer/types.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/types.ts
@@ -3,6 +3,10 @@ import type { InactivityPeriod as BaseInactivityPeriod } from '@posthog/replay-h
export interface RasterizeRecordingInput {
session_id: string
team_id: number
+ // Team-scoped read token minted by the Python build_rasterization_input activity and relayed to
+ // recording-api (the rasterizer cannot mint its own). Optional only during migration, before the
+ // minting side has shipped.
+ recording_api_token?: string
max_virtual_time?: number // max virtual-time seconds before stopping capture (default: unlimited)
playback_speed?: number // 1-360, defaults to 4
start_offset_s?: number // seconds from session start to begin playback
diff --git a/nodejs/tests/session-replay/recording-api/recording-api.integration.test.ts b/nodejs/tests/session-replay/recording-api/recording-api.integration.test.ts
index 8e641fec592e..e7958627188f 100644
--- a/nodejs/tests/session-replay/recording-api/recording-api.integration.test.ts
+++ b/nodejs/tests/session-replay/recording-api/recording-api.integration.test.ts
@@ -44,6 +44,8 @@ import snappy from 'snappy'
import supertest from 'supertest'
import express from 'ultimate-express'
+import { JWT, PosthogJwtAudience } from '~/cdp/utils/jwt-utils'
+import { setupExpressApp } from '~/common/api/router'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
@@ -755,6 +757,189 @@ describe('Recording API encryption integration', () => {
})
})
+ // Auth matrix exercised through the real router chain (no Localstack needed — rejections happen
+ // in the middleware before the handler touches S3; the few pass-through cases use MemoryKeyStore).
+ describe('HTTP auth (team + operation scoped JWT)', () => {
+ const JWT_SECRET = 'itest-jwt-secret'
+ const LEGACY_SECRET = 'itest-legacy-secret'
+ const TEAM = 1
+ const SESSION = 'auth-session-1'
+ const BLOCK_KEY = 'session_recordings/30d/1764634738680-3cca0f5d3c7cc7ee'
+
+ let keyStore: MemoryKeyStore
+ let encryptor: SodiumRecordingEncryptor
+ let decryptor: SodiumRecordingDecryptor
+ let mockS3Send: jest.Mock
+ let recordingService: RecordingService
+ let servers: Server[]
+
+ beforeEach(async () => {
+ keyStore = new MemoryKeyStore()
+ await keyStore.start()
+ decryptor = new SodiumRecordingDecryptor(keyStore)
+ await decryptor.start()
+ encryptor = new SodiumRecordingEncryptor(keyStore)
+ await encryptor.start()
+ mockS3Send = jest.fn()
+ const mockS3Client = { send: mockS3Send, destroy: jest.fn() } as unknown as S3Client
+ recordingService = new RecordingService(
+ mockS3Client,
+ 'test-bucket',
+ 'session_recordings',
+ keyStore,
+ decryptor
+ )
+ servers = []
+ })
+
+ afterEach(() => {
+ servers.forEach((s) => s.close())
+ })
+
+ const defaultConfig: Partial<RecordingApiConfig> = {
+ RECORDING_API_JWT_SECRET: JWT_SECRET,
+ INTERNAL_API_SECRET: LEGACY_SECRET,
+ RECORDING_API_ALLOW_LEGACY_SECRET: true,
+ }
+
+ const makeApp = async (config: Partial<RecordingApiConfig> = defaultConfig): Promise<express.Application> => {
+ const api = new RecordingApi(config as RecordingApiConfig, {} as PostgresRouter, mockOutputs)
+ await api.start(recordingService)
+ // Mirror RecordingApiServer's real wiring: the shared-secret middleware fronts the app but
+ // exempts the recording-api namespace, which then owns auth per-route. Exercises that
+ // interaction (and the JSON body parser) instead of mounting the router on a bare app.
+ const app = setupExpressApp({
+ internalApiSecret: config.INTERNAL_API_SECRET ?? '',
+ internalApiAuthExcludedPathPrefixes: ['/api/projects/'],
+ })
+ app.use('/', api.router())
+ servers.push(app.listen(0, () => {}))
+ return app
+ }
+
+ const token = (
+ claims: { team_id: number; op: string },
+ secret = JWT_SECRET,
+ expiresIn: string | number = '5m'
+ ) => new JWT(secret).sign(claims, PosthogJwtAudience.RECORDING_API, { expiresIn })
+
+ const bearer = (t: string) => ({ Authorization: `Bearer ${t}` })
+
+ // Set up a real fetchable block so a request that PASSES auth returns 200 (not just "not 401").
+ const setupBlock = async (): Promise<{ key: string; startByte: string; endByte: string }> => {
+ const sessionKey = await keyStore.generateKey(SESSION, TEAM, 30)
+ const blockData = await createBlockData([{ type: 2, data: { content: 'hi' } }])
+ const { data: encrypted } = encryptor.encryptBlockWithKey(SESSION, TEAM, blockData, sessionKey)
+ mockS3Send.mockResolvedValue({ Body: { transformToByteArray: () => Promise.resolve(encrypted) } })
+ return { key: BLOCK_KEY, startByte: '0', endByte: String(encrypted.length - 1) }
+ }
+
+ const getBlock = (app: express.Application, headers: Record<string, string>, team: number = TEAM) =>
+ supertest(app)
+ .get(`/api/projects/${team}/recordings/${SESSION}/block`)
+ .query({ key: BLOCK_KEY, start_byte: '0', end_byte: '100' })
+ .set(headers)
+
+ const postDelete = (app: express.Application, headers: Record<string, string>, team: number = TEAM) =>
+ supertest(app)
+ .post(`/api/projects/${team}/recordings/delete`)
+ .send({ session_ids: [SESSION], deleted_by: '[email protected]' })
+ .set(headers)
+
+ it('valid read token (matching team) reaches the handler and returns the block', async () => {
+ const app = await makeApp()
+ const block = await setupBlock()
+ const res = await supertest(app)
+ .get(`/api/projects/${TEAM}/recordings/${SESSION}/block`)
+ .query({ key: block.key, start_byte: block.startByte, end_byte: block.endByte })
+ .set(bearer(token({ team_id: TEAM, op: 'read' })))
+ expect(res.status).toBe(200)
+ })
+
+ it('accepts a valid delete token on the delete route', async () => {
+ const app = await makeApp()
+ const res = await postDelete(app, bearer(token({ team_id: TEAM, op: 'delete' })))
+ expect(res.status).not.toBe(401)
+ expect(res.status).not.toBe(403)
+ })
+
+ it('rejects a token scoped to a different team (403)', async () => {
+ const app = await makeApp()
+ const res = await getBlock(app, bearer(token({ team_id: 999, op: 'read' })))
+ expect(res.status).toBe(403)
+ })
+
+ it('rejects a read token on the delete route (403)', async () => {
+ const app = await makeApp()
+ const res = await postDelete(app, bearer(token({ team_id: TEAM, op: 'read' })))
+ expect(res.status).toBe(403)
+ })
+
+ it('rejects a delete token on a read route (403)', async () => {
+ const app = await makeApp()
+ const res = await getBlock(app, bearer(token({ team_id: TEAM, op: 'delete' })))
+ expect(res.status).toBe(403)
+ })
+
+ it.each([
+ ['no token', undefined],
+ ['garbage token', 'not-a-jwt'],
+ ['expired token', token({ team_id: TEAM, op: 'read' }, JWT_SECRET, -60)],
+ ['token signed by an unknown key', token({ team_id: TEAM, op: 'read' }, 'rogue-key')],
+ ])('rejects %s with 401', async (_name, t) => {
+ const app = await makeApp()
+ const res = await getBlock(app, t ? bearer(t) : {})
+ expect(res.status).toBe(401)
+ })
+
+ // The shared-secret middleware exempts the whole '/api/projects/' prefix, so recording-api's
+ // own auth has to cover that prefix entirely. A path this router does not handle must still
+ // be rejected with a 401 rather than falling through to an unauthenticated 404, otherwise a
+ // route added under the prefix later would ship with no auth at all.
+ it.each([
+ ['GET', `/api/projects/${TEAM}/not-a-real-route`],
+ ['POST', `/api/projects/${TEAM}/recordings/not-a-real-route`],
+ ])('requires auth for an unhandled %s path under the exempt prefix', async (method, path) => {
+ const app = await makeApp()
+ const res = await (method === 'GET' ? supertest(app).get(path) : supertest(app).post(path).send({}))
+ expect(res.status).toBe(401)
+ })
+
+ it('accepts the legacy secret while allowLegacySecret is true', async () => {
+ const app = await makeApp()
+ const block = await setupBlock()
+ const res = await supertest(app)
+ .get(`/api/projects/${TEAM}/recordings/${SESSION}/block`)
+ .query({ key: block.key, start_byte: block.startByte, end_byte: block.endByte })
+ .set({ 'X-Internal-Api-Secret': LEGACY_SECRET })
+ expect(res.status).toBe(200)
+ })
+
+ it('rejects the legacy secret once allowLegacySecret is false', async () => {
+ const app = await makeApp({ ...defaultConfig, RECORDING_API_ALLOW_LEGACY_SECRET: false })
+ const res = await getBlock(app, { 'X-Internal-Api-Secret': LEGACY_SECRET })
+ expect(res.status).toBe(401)
+ })
+
+ describe('key rotation', () => {
+ it('accepts a token signed by the retiring key while both keys are configured', async () => {
+ const app = await makeApp({ ...defaultConfig, RECORDING_API_JWT_SECRET: 'new-key,old-key' })
+ const block = await setupBlock()
+ const res = await supertest(app)
+ .get(`/api/projects/${TEAM}/recordings/${SESSION}/block`)
+ .query({ key: block.key, start_byte: block.startByte, end_byte: block.endByte })
+ .set(bearer(token({ team_id: TEAM, op: 'read' }, 'old-key')))
+ expect(res.status).toBe(200)
+ })
+
+ it('rejects a token signed by a retired key once it is dropped', async () => {
+ const app = await makeApp({ ...defaultConfig, RECORDING_API_JWT_SECRET: 'new-key' })
+ const res = await getBlock(app, bearer(token({ team_id: TEAM, op: 'read' }, 'old-key')))
+ expect(res.status).toBe(401)
+ })
+ })
+ })
+
// HTTP integration tests (always run, uses MemoryKeyStore)
describe('HTTP endpoints', () => {
let keyStore: MemoryKeyStore
diff --git a/posthog/jwt.py b/posthog/jwt.py
index 291ca41b4d7c..0f7e8a557b90 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -18,6 +18,7 @@ class PosthogJwtAudience(Enum):
EXPORT_RENDERER = "posthog:export_renderer"
LIVESTREAM = "posthog:livestream"
SHARING_PASSWORD_PROTECTED = "posthog:sharing_password_protected"
+ RECORDING_API = "posthog:recording_api"
INTEGRATION_SERVICE = "posthog:integration_service"
@@ -57,9 +58,9 @@ def encode_jwt(
)
-def decode_jwt(token: str, audience: PosthogJwtAudience) -> dict[str, Any]:
+def decode_jwt(token: str, audience: PosthogJwtAudience, verification_keys: list[str] | None = None) -> dict[str, Any]:
last_error: jwt.InvalidSignatureError | None = None
- for key in _verification_keys():
+ for key in verification_keys if verification_keys is not None else _verification_keys():
try:
return jwt.decode(token, key, audience=audience.value, algorithms=[JWT_ALGORITHM])
except jwt.InvalidSignatureError as error:
diff --git a/posthog/session_recordings/recordings/recording_api_client.py b/posthog/session_recordings/recordings/recording_api_client.py
index 5f0212029bd2..c27826c11c99 100644
--- a/posthog/session_recordings/recordings/recording_api_client.py
+++ b/posthog/session_recordings/recordings/recording_api_client.py
@@ -7,6 +7,7 @@ import aiohttp
import structlog
from posthog.session_recordings.recordings.errors import BlockFetchError, RecordingDeletedError
+from posthog.session_recordings.recordings.recording_api_jwt import recording_api_auth_headers
logger = structlog.get_logger(__name__)
@@ -32,7 +33,9 @@ class RecordingApiClient:
params["decompress"] = "true"
try:
- async with self.session.get(url, params=params) as response:
+ async with self.session.get(
+ url, params=params, headers=recording_api_auth_headers(team_id, "read")
+ ) as response:
if response.status == 404:
raise BlockFetchError("Block not found")
if response.status == 410:
@@ -68,7 +71,7 @@ class RecordingApiClient:
url = f"{self.base_url}/api/projects/{team_id}/recordings/{session_id}/blocks"
try:
- async with self.session.get(url) as response:
+ async with self.session.get(url, headers=recording_api_auth_headers(team_id, "read")) as response:
if response.status == 404:
return []
response.raise_for_status()
@@ -94,7 +97,11 @@ class RecordingApiClient:
url = f"{self.base_url}/api/projects/{team_id}/recordings/delete"
try:
- async with self.session.post(url, json={"session_ids": session_ids, "deleted_by": deleted_by}) as response:
+ async with self.session.post(
+ url,
+ json={"session_ids": session_ids, "deleted_by": deleted_by},
+ headers=recording_api_auth_headers(team_id, "delete"),
+ ) as response:
response.raise_for_status()
data = await response.json()
return [r["sessionId"] for r in data if not r.get("ok")]
@@ -122,13 +129,8 @@ async def recording_api_client() -> AsyncIterator[RecordingApiClient]:
if not settings.RECORDING_API_URL:
raise RuntimeError("RECORDING_API_URL is not configured")
- headers: dict[str, str] = {}
- if settings.INTERNAL_API_SECRET:
- headers["X-Internal-Api-Secret"] = settings.INTERNAL_API_SECRET
- elif not settings.DEBUG:
- logger.warning("recording_api_client.missing_internal_api_secret")
-
timeout = aiohttp.ClientTimeout(total=30, connect=5)
+ # Authorization is per-request (a team + operation scoped JWT), so no session-level auth header.
# nosemgrep: aiohttp-missing-trust-env -- internal service call to recording API
- async with aiohttp.ClientSession(timeout=timeout, headers=headers, trust_env=False) as session:
+ async with aiohttp.ClientSession(timeout=timeout, trust_env=False) as session:
yield RecordingApiClient(session, settings.RECORDING_API_URL)
diff --git a/posthog/session_recordings/recordings/recording_api_jwt.py b/posthog/session_recordings/recordings/recording_api_jwt.py
new file mode 100644
index 000000000000..48f7317d4b31
--- /dev/null
+++ b/posthog/session_recordings/recordings/recording_api_jwt.py
@@ -0,0 +1,56 @@
+from datetime import timedelta
+from typing import Literal
+
+from django.conf import settings
+
+import structlog
+
+from posthog.jwt import PosthogJwtAudience, encode_jwt
+from posthog.settings.utils import get_list
+
+logger = structlog.get_logger(__name__)
+
+RecordingApiOp = Literal["read", "delete"]
+
+# Direct callers mint a fresh token per request, so a short lifetime suffices. The rasterizer
+# can't re-mint mid-render and reuses one relayed token across a whole render, so it passes a
+# longer ttl explicitly.
+DEFAULT_RECORDING_API_TOKEN_TTL = timedelta(minutes=5)
+
+
+def recording_api_signing_keys() -> list[str]:
+ """The comma-separated `new_key,old_key` set, newest first. Whitespace-trimmed (matching the
+ Node verifier's parseJwtKeys) and empty entries dropped."""
+ return [key for key in get_list(settings.RECORDING_API_JWT_SECRET or "") if key]
+
+
+def recording_api_jwt_enabled() -> bool:
+ """True once a dedicated signing secret is configured. Until then callers fall back to the
+ legacy X-Internal-Api-Secret, so the JWT scheme can be rolled out per environment (dev, then
+ prod) without leaving any environment unauthenticated in the meantime."""
+ return bool(recording_api_signing_keys())
+
+
+def recording_api_auth_headers(team_id: int, op: RecordingApiOp) -> dict[str, str]:
+ """Auth headers for a recording-api request. Sends the legacy shared secret (when configured)
+ and a freshly minted team + operation scoped Bearer token (when the signing secret is
+ configured), so recording-api accepts either and rollout stays order-independent."""
+ headers: dict[str, str] = {}
+ if settings.INTERNAL_API_SECRET:
+ headers["X-Internal-Api-Secret"] = settings.INTERNAL_API_SECRET
+ if recording_api_jwt_enabled():
+ headers["Authorization"] = f"Bearer {mint_recording_api_token(team_id, op)}"
+ if not headers:
+ # Neither secret configured: the request will be sent unauthenticated and recording-api will
+ # reject it. Surface the misconfiguration here (the caller otherwise only sees an opaque 401).
+ logger.warning("recording_api.no_auth_configured")
+ return headers
+
+
+def mint_recording_api_token(team_id: int, op: RecordingApiOp, ttl: timedelta = DEFAULT_RECORDING_API_TOKEN_TTL) -> str:
+ """Mint a team + operation scoped token for recording-api. Signs with the newest key;
+ recording-api verifies against the full key set, so rotation works without breaking callers."""
+ keys = recording_api_signing_keys()
+ if not keys:
+ raise RuntimeError("RECORDING_API_JWT_SECRET is not configured")
+ return encode_jwt({"team_id": team_id, "op": op}, ttl, PosthogJwtAudience.RECORDING_API, signing_key=keys[0])
diff --git a/posthog/session_recordings/test/recordings/test_recording_api_client.py b/posthog/session_recordings/test/recordings/test_recording_api_client.py
index 68cd9e150742..85d9d75218db 100644
--- a/posthog/session_recordings/test/recordings/test_recording_api_client.py
+++ b/posthog/session_recordings/test/recordings/test_recording_api_client.py
@@ -1,10 +1,29 @@
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.test import override_settings
+
import aiohttp
from posthog.session_recordings.recordings.errors import BlockFetchError, RecordingDeletedError
from posthog.session_recordings.recordings.recording_api_client import RecordingApiClient, recording_api_client
+from posthog.session_recordings.recordings.recording_api_jwt import recording_api_auth_headers
+
+AUTH_HEADERS = {"Authorization": "Bearer test-token"}
+
+
[email protected](autouse=True)
+def fixed_recording_api_token():
+ # Default to no legacy secret so the header assertions below see only the Bearer token; the
+ # rollout tests set INTERNAL_API_SECRET explicitly to exercise dual-send.
+ with (
+ override_settings(INTERNAL_API_SECRET=""),
+ patch(
+ "posthog.session_recordings.recordings.recording_api_jwt.mint_recording_api_token",
+ return_value="test-token",
+ ) as mint,
+ ):
+ yield mint
class TestRecordingApiClient:
@@ -56,6 +75,7 @@ class TestFetchBlock:
mock_session.get.assert_called_once_with(
"http://localhost:6740/api/projects/1/recordings/session-123/block",
params={"key": "key", "start_byte": 0, "end_byte": 100},
+ headers=AUTH_HEADERS,
)
@pytest.mark.asyncio
@@ -82,6 +102,7 @@ class TestFetchBlock:
mock_session.get.assert_called_once_with(
"http://localhost:6740/api/projects/1/recordings/session-123/block",
params={"key": "key", "start_byte": 0, "end_byte": 100, "decompress": "true"},
+ headers=AUTH_HEADERS,
)
@pytest.mark.asyncio
@@ -194,6 +215,7 @@ class TestListBlocks:
]
mock_session.get.assert_called_once_with(
"http://localhost:6740/api/projects/1/recordings/session-123/blocks",
+ headers=AUTH_HEADERS,
)
@pytest.mark.asyncio
@@ -275,6 +297,7 @@ class TestDeleteRecordings:
mock_session.post.assert_called_once_with(
"http://localhost:6740/api/projects/1/recordings/delete",
json={"session_ids": ["s1", "s2"], "deleted_by": "[email protected]"},
+ headers=AUTH_HEADERS,
)
@pytest.mark.asyncio
@@ -360,47 +383,68 @@ class TestRecordingApiClientContextManager:
call_kwargs = mock_client_session.call_args[1]
assert call_kwargs["timeout"].total == 30
assert call_kwargs["timeout"].connect == 5
- assert call_kwargs["headers"] == {}
+ # Auth is per-request (Bearer), so the session carries no auth header.
+ assert "headers" not in call_kwargs
- @pytest.mark.asyncio
- async def test_warns_when_secret_missing_in_production(self):
- with (
- patch("posthog.session_recordings.recordings.recording_api_client.settings") as mock_settings,
- patch("posthog.session_recordings.recordings.recording_api_client.logger") as mock_logger,
- patch(
- "posthog.session_recordings.recordings.recording_api_client.aiohttp.ClientSession"
- ) as mock_client_session,
- ):
- mock_settings.RECORDING_API_URL = "http://test-api:8080"
- mock_settings.INTERNAL_API_SECRET = ""
- mock_settings.DEBUG = False
- mock_session = AsyncMock()
- mock_session.__aenter__ = AsyncMock(return_value=mock_session)
- mock_session.__aexit__ = AsyncMock(return_value=None)
- mock_client_session.return_value = mock_session
+class TestPerRequestAuthScoping:
+ @pytest.fixture
+ def mock_session(self):
+ return MagicMock(spec=aiohttp.ClientSession)
- async with recording_api_client():
- pass
+ @pytest.fixture
+ def client(self, mock_session):
+ return RecordingApiClient(mock_session, "http://localhost:6740")
- mock_logger.warning.assert_called_once_with("recording_api_client.missing_internal_api_secret")
+ def _ok_get(self, mock_session, payload):
+ mock_response = AsyncMock()
+ mock_response.status = 200
+ mock_response.raise_for_status = MagicMock()
+ mock_response.read = AsyncMock(return_value=b"x")
+ mock_response.json = AsyncMock(return_value=payload)
+ mock_response.__aenter__ = AsyncMock(return_value=mock_response)
+ mock_response.__aexit__ = AsyncMock(return_value=None)
+ mock_session.get = MagicMock(return_value=mock_response)
+ mock_session.post = MagicMock(return_value=mock_response)
@pytest.mark.asyncio
- async def test_passes_internal_api_secret_header(self):
- with patch("posthog.session_recordings.recordings.recording_api_client.settings") as mock_settings:
- mock_settings.RECORDING_API_URL = "http://test-api:8080"
- mock_settings.INTERNAL_API_SECRET = "test-secret"
-
- with patch(
- "posthog.session_recordings.recordings.recording_api_client.aiohttp.ClientSession"
- ) as mock_client_session:
- mock_session = AsyncMock()
- mock_session.__aenter__ = AsyncMock(return_value=mock_session)
- mock_session.__aexit__ = AsyncMock(return_value=None)
- mock_client_session.return_value = mock_session
+ async def test_fetch_block_mints_read_token_for_team(self, client, mock_session, fixed_recording_api_token):
+ self._ok_get(mock_session, {})
+ await client.fetch_block("key", 0, 1, "session-1", 42)
+ fixed_recording_api_token.assert_called_once_with(42, "read")
- async with recording_api_client() as client:
- assert client.session == mock_session
+ @pytest.mark.asyncio
+ async def test_list_blocks_mints_read_token_for_team(self, client, mock_session, fixed_recording_api_token):
+ self._ok_get(mock_session, {"blocks": []})
+ await client.list_blocks("session-1", 42)
+ fixed_recording_api_token.assert_called_once_with(42, "read")
- call_kwargs = mock_client_session.call_args[1]
- assert call_kwargs["headers"] == {"X-Internal-Api-Secret": "test-secret"}
+ @pytest.mark.asyncio
+ async def test_delete_mints_delete_token_for_team(self, client, mock_session, fixed_recording_api_token):
+ self._ok_get(mock_session, [])
+ await client.delete_recordings(["s1"], 42, deleted_by="[email protected]")
+ fixed_recording_api_token.assert_called_once_with(42, "delete")
+
+
+class TestAuthHeaderRollout:
+ @override_settings(RECORDING_API_JWT_SECRET="dev-secret", INTERNAL_API_SECRET="legacy")
+ def test_sends_both_when_jwt_and_legacy_configured(self):
+ # mint is patched to "test-token" by the autouse fixture.
+ assert recording_api_auth_headers(7, "read") == {
+ "X-Internal-Api-Secret": "legacy",
+ "Authorization": "Bearer test-token",
+ }
+
+ @override_settings(RECORDING_API_JWT_SECRET="dev-secret", INTERNAL_API_SECRET="")
+ def test_sends_only_bearer_when_no_legacy_secret(self):
+ assert recording_api_auth_headers(7, "read") == {"Authorization": "Bearer test-token"}
+
+ @override_settings(RECORDING_API_JWT_SECRET="", INTERNAL_API_SECRET="legacy")
+ def test_sends_only_legacy_when_jwt_disabled(self):
+ assert recording_api_auth_headers(7, "read") == {"X-Internal-Api-Secret": "legacy"}
+
+ @override_settings(RECORDING_API_JWT_SECRET="", INTERNAL_API_SECRET="")
+ def test_no_auth_header_and_warns_when_nothing_configured(self):
+ with patch("posthog.session_recordings.recordings.recording_api_jwt.logger") as mock_logger:
+ assert recording_api_auth_headers(7, "read") == {}
+ mock_logger.warning.assert_called_once_with("recording_api.no_auth_configured")
diff --git a/posthog/session_recordings/test/test_recording_api_jwt.py b/posthog/session_recordings/test/test_recording_api_jwt.py
new file mode 100644
index 000000000000..dcd382cf4db1
--- /dev/null
+++ b/posthog/session_recordings/test/test_recording_api_jwt.py
@@ -0,0 +1,133 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+
+from django.test import override_settings
+
+import jwt
+
+from posthog.jwt import PosthogJwtAudience, decode_jwt
+from posthog.session_recordings.recordings.recording_api_jwt import (
+ mint_recording_api_token,
+ recording_api_jwt_enabled,
+ recording_api_signing_keys,
+)
+
+
+def _sign_with(key: str, claims: dict | None = None) -> str:
+ payload = {
+ "team_id": 1,
+ "op": "read",
+ "aud": PosthogJwtAudience.RECORDING_API.value,
+ "exp": datetime.now(tz=UTC) + timedelta(minutes=5),
+ **(claims or {}),
+ }
+ return jwt.encode(payload, key, algorithm="HS256")
+
+
+class TestMintRecordingApiToken:
+ @override_settings(RECORDING_API_JWT_SECRET="primary-key")
+ def test_mints_team_and_op_scoped_token(self):
+ token = mint_recording_api_token(123, "read")
+
+ decoded = decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=["primary-key"])
+
+ assert decoded["team_id"] == 123
+ assert decoded["op"] == "read"
+ assert decoded["aud"] == "posthog:recording_api"
+ assert "exp" in decoded
+
+ @override_settings(RECORDING_API_JWT_SECRET="primary-key")
+ def test_custom_ttl_is_honored(self):
+ before = datetime.now(tz=UTC)
+ token = mint_recording_api_token(1, "read", ttl=timedelta(minutes=70))
+ decoded = decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=["primary-key"])
+ # exp should land ~70 minutes out — pinned to the passed ttl, not the 5-minute default or any
+ # other value, so a drift in the custom ttl is caught.
+ assert 69 * 60 < decoded["exp"] - before.timestamp() < 71 * 60
+
+ @override_settings(RECORDING_API_JWT_SECRET="")
+ def test_mint_without_secret_raises(self):
+ with pytest.raises(RuntimeError):
+ mint_recording_api_token(1, "read")
+
+ @override_settings(RECORDING_API_JWT_SECRET="primary-key")
+ def test_wrong_audience_rejected(self):
+ token = mint_recording_api_token(1, "read")
+ with pytest.raises(jwt.InvalidAudienceError):
+ decode_jwt(token, PosthogJwtAudience.EXPORT_RENDERER, verification_keys=["primary-key"])
+
+
+class TestSigningKeySelection:
+ @override_settings(RECORDING_API_JWT_SECRET="new-key,old-key")
+ def test_signs_with_newest_key_only(self):
+ token = mint_recording_api_token(1, "delete")
+
+ # Verifies under the newest (first) key...
+ assert decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=["new-key"])["op"] == "delete"
+ # ...and NOT under the old key, proving we never sign with anything but the newest key.
+ with pytest.raises(jwt.InvalidSignatureError):
+ decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=["old-key"])
+
+ @override_settings(RECORDING_API_JWT_SECRET="new-key,old-key,")
+ def test_signing_keys_drop_empty_segments_and_preserve_order(self):
+ assert recording_api_signing_keys() == ["new-key", "old-key"]
+
+ @override_settings(RECORDING_API_JWT_SECRET="only-key")
+ def test_single_key_signs_and_verifies(self):
+ token = mint_recording_api_token(5, "read")
+ assert decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=["only-key"])["team_id"] == 5
+
+
+class TestRotationVerification:
+ @override_settings(RECORDING_API_JWT_SECRET="new-key,old-key")
+ def test_verifies_token_signed_by_newest_key(self):
+ keys = recording_api_signing_keys()
+ token = _sign_with("new-key")
+ assert decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=keys)["team_id"] == 1
+
+ @override_settings(RECORDING_API_JWT_SECRET="new-key,old-key")
+ def test_verifies_token_signed_by_retiring_key_during_window(self):
+ keys = recording_api_signing_keys()
+ token = _sign_with("old-key")
+ assert decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=keys)["team_id"] == 1
+
+ @override_settings(RECORDING_API_JWT_SECRET="new-key,old-key")
+ def test_rejects_token_signed_by_key_outside_the_set(self):
+ keys = recording_api_signing_keys()
+ token = _sign_with("attacker-key")
+ with pytest.raises(jwt.InvalidSignatureError):
+ decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=keys)
+
+ @override_settings(RECORDING_API_JWT_SECRET="new-key")
+ def test_rejects_retired_key_after_cleanup(self):
+ # Once the old key is dropped from the set, tokens signed by it no longer verify.
+ keys = recording_api_signing_keys()
+ token = _sign_with("old-key")
+ with pytest.raises(jwt.InvalidSignatureError):
+ decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=keys)
+
+
+class TestRecordingApiJwtEnabled:
+ @pytest.mark.parametrize(
+ "secret,expected",
+ [("", False), ("a-key", True), ("new,old", True), (None, False)],
+ )
+ def test_enabled_reflects_configured_secret(self, secret, expected):
+ with override_settings(RECORDING_API_JWT_SECRET=secret):
+ assert recording_api_jwt_enabled() is expected
+
+
+class TestCrossLanguageContract:
+ def test_audience_literal(self):
+ assert PosthogJwtAudience.RECORDING_API.value == "posthog:recording_api"
+
+ @override_settings(RECORDING_API_JWT_SECRET="contract-key")
+ def test_minted_claim_shape(self):
+ decoded = decode_jwt(
+ mint_recording_api_token(7, "read"), PosthogJwtAudience.RECORDING_API, verification_keys=["contract-key"]
+ )
+ assert decoded["team_id"] == 7
+ assert decoded["op"] == "read"
+ # Exactly the claims the Node verifier expects — nothing extra leaks in.
+ assert set(decoded.keys()) == {"team_id", "op", "aud", "exp"}
diff --git a/posthog/settings/session_replay_v2.py b/posthog/settings/session_replay_v2.py
index e0469b95e98e..1eb54be9c34f 100644
--- a/posthog/settings/session_replay_v2.py
+++ b/posthog/settings/session_replay_v2.py
@@ -30,3 +30,12 @@ if TEST or DEBUG:
RECORDING_API_URL = os.getenv("RECORDING_API_URL", "http://localhost:6741")
else:
RECORDING_API_URL = os.getenv("RECORDING_API_URL", "")
+
+# Dedicated signing secret for the team-scoped JWTs that authorize recording-api calls.
+# Kept off SECRET_KEY/JWT_SIGNING_KEY (which are fleet-wide) so only the designated minters
+# — Django web and the Python Temporal workers — can mint recording-api tokens. Comma-separated
+# `new_key,old_key` for rotation: callers sign with the first key, recording-api verifies against
+# all. Dev/test default matches the recording-api Node default so local end-to-end calls validate.
+RECORDING_API_JWT_SECRET = os.getenv(
+ "RECORDING_API_JWT_SECRET", "dev-recording-api-jwt-secret" if (TEST or DEBUG) else ""
+)
diff --git a/posthog/temporal/session_replay/delete_recordings/activities.py b/posthog/temporal/session_replay/delete_recordings/activities.py
index f586b21fb574..b42b3deb970c 100644
--- a/posthog/temporal/session_replay/delete_recordings/activities.py
+++ b/posthog/temporal/session_replay/delete_recordings/activities.py
@@ -13,6 +13,7 @@ from posthog.models import Team
from posthog.security.outbound_proxy import internal_httpx_async_client
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
+from posthog.session_recordings.recordings.recording_api_jwt import recording_api_auth_headers
from posthog.session_recordings.utils import filter_from_params_to_query
from posthog.sync import database_sync_to_async
from posthog.temporal.common.clickhouse import get_client
@@ -207,9 +208,7 @@ async def delete_recordings(input: DeleteRecordingsInput) -> DeleteRecordingsRes
url = f"{recording_api_url}/api/projects/{input.team_id}/recordings/delete"
- headers: dict[str, str] = {}
- if settings.INTERNAL_API_SECRET:
- headers["X-Internal-Api-Secret"] = settings.INTERNAL_API_SECRET
+ headers = recording_api_auth_headers(input.team_id, "delete")
async with internal_httpx_async_client(timeout=60.0, headers=headers) as client:
response = await client.post(url, json={"session_ids": input.session_ids, "deleted_by": input.deleted_by})
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
index 223cd12dc71d..d1bc0677506a 100644
--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
@@ -1,14 +1,19 @@
+from datetime import timedelta
+
from django.conf import settings
from django.db import close_old_connections, transaction
import structlog
from temporalio import activity
+from posthog.session_recordings.recordings.recording_api_jwt import mint_recording_api_token, recording_api_jwt_enabled
from posthog.storage import object_storage
from products.exports.backend.models.exported_asset import ExportedAsset
from ..types import (
+ RASTERIZE_RENDER_MAX_ATTEMPTS,
+ RASTERIZE_RENDER_TIMEOUT,
BuildRasterizationResult,
FinalizeRasterizationInput,
InactivityPeriod,
@@ -19,6 +24,13 @@ from ..types import (
logger = structlog.get_logger(__name__)
+# The rasterizer relays one token across an entire render and cannot re-mint, so it must outlive the
+# whole Node activity envelope. Derive the lifetime from the activity's actual retry envelope (shared
+# constants in ..types) plus a 1h buffer for queue wait/backoff, so bumping the retry policy can't
+# silently leave the token expiring mid-render. Still a read-only, single-team token (a big
+# improvement over the unscoped shared secret it replaces).
+_RASTERIZE_TOKEN_TTL = RASTERIZE_RENDER_TIMEOUT * RASTERIZE_RENDER_MAX_ATTEMPTS + timedelta(hours=1)
+
_RENDER_FINGERPRINT_KEY = "render_fingerprint"
_PERSISTED_OUTPUT_FIELDS: frozenset[str] = frozenset(
{"video_duration_s", "playback_speed", "truncated", "file_size_bytes", "inactivity_periods"}
@@ -67,9 +79,16 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResul
if recording_fps is not None:
recording_fps = min(60, int(recording_fps))
+ # Empty until the signing secret is configured; the rasterizer then relays the legacy shared
+ # secret instead, so rollout can happen per environment without breaking rendering.
+ recording_api_token = (
+ mint_recording_api_token(asset.team_id, "read", ttl=_RASTERIZE_TOKEN_TTL) if recording_api_jwt_enabled() else ""
+ )
+
activity_input = RasterizationActivityInput(
team_id=asset.team_id,
session_id=session_id,
+ recording_api_token=recording_api_token,
s3_bucket=settings.OBJECT_STORAGE_BUCKET,
s3_key_prefix=s3_key_prefix,
playback_speed=playback_speed,
diff --git a/posthog/temporal/session_replay/rasterize_recording/types.py b/posthog/temporal/session_replay/rasterize_recording/types.py
index 3cbb402ed407..ab2bc3eda35d 100644
--- a/posthog/temporal/session_replay/rasterize_recording/types.py
+++ b/posthog/temporal/session_replay/rasterize_recording/types.py
@@ -1,8 +1,14 @@
import hashlib
+from datetime import timedelta
from typing import Literal
from pydantic import BaseModel, model_validator
+# Retry envelope for the Node rasterize activity (scheduled in workflow._run). Shared so the relayed
+# recording-api token's TTL (rasterize.py) is derived from the same numbers and can't silently drift.
+RASTERIZE_RENDER_TIMEOUT = timedelta(minutes=30)
+RASTERIZE_RENDER_MAX_ATTEMPTS = 2
+
class RasterizeRecordingInputs(BaseModel, frozen=True):
"""Input to the RasterizeRecordingWorkflow."""
@@ -20,6 +26,10 @@ class RasterizationActivityInput(BaseModel, frozen=True):
session_id: str
team_id: int
+ # Team-scoped read token the rasterizer relays to recording-api (it cannot mint its own).
+ # Defaults to "" so a workflow that recorded build_rasterization_input's result under an older
+ # release (before this field existed) still deserializes on replay instead of failing validation.
+ recording_api_token: str = ""
s3_bucket: str
s3_key_prefix: str
playback_speed: float = 4
@@ -74,7 +84,8 @@ class FinalizeRasterizationInput(BaseModel, frozen=True):
# Output destination fields — excluded so bucket/prefix changes don't invalidate caches.
-_FINGERPRINT_EXCLUDE: set[str] = {"team_id", "session_id", "s3_bucket", "s3_key_prefix"}
+# recording_api_token is per-run and ephemeral, so it must never participate in the cache key.
+_FINGERPRINT_EXCLUDE: set[str] = {"team_id", "session_id", "s3_bucket", "s3_key_prefix", "recording_api_token"}
def compute_params_fingerprint(activity_input: "RasterizationActivityInput") -> str:
diff --git a/posthog/temporal/session_replay/rasterize_recording/workflow.py b/posthog/temporal/session_replay/rasterize_recording/workflow.py
index 04d68d2bd157..5974c31ccd13 100644
--- a/posthog/temporal/session_replay/rasterize_recording/workflow.py
+++ b/posthog/temporal/session_replay/rasterize_recording/workflow.py
@@ -32,6 +32,8 @@ from .activities import (
finalize_rasterization,
)
from .types import (
+ RASTERIZE_RENDER_MAX_ATTEMPTS,
+ RASTERIZE_RENDER_TIMEOUT,
BuildRasterizationResult,
FinalizeRasterizationInput,
RasterizationActivityOutput,
@@ -144,9 +146,9 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):
"rasterize-recording",
prep.activity_input.model_dump(exclude_none=True),
task_queue=settings.RASTERIZATION_TASK_QUEUE,
- start_to_close_timeout=dt.timedelta(minutes=30),
+ start_to_close_timeout=RASTERIZE_RENDER_TIMEOUT,
heartbeat_timeout=dt.timedelta(seconds=30),
- retry_policy=common.RetryPolicy(maximum_attempts=2),
+ retry_policy=common.RetryPolicy(maximum_attempts=RASTERIZE_RENDER_MAX_ATTEMPTS),
)
result = RasterizationActivityOutput.model_validate(raw_result)
diff --git a/posthog/temporal/tests/session_replay/delete_recordings/test_activities.py b/posthog/temporal/tests/session_replay/delete_recordings/test_activities.py
index 7079f8b673ca..8e79edea90d0 100644
--- a/posthog/temporal/tests/session_replay/delete_recordings/test_activities.py
+++ b/posthog/temporal/tests/session_replay/delete_recordings/test_activities.py
@@ -3,8 +3,11 @@ import json
import pytest
from unittest.mock import AsyncMock, patch
+from django.test import override_settings
+
import httpx
+from posthog.jwt import PosthogJwtAudience, decode_jwt
from posthog.temporal.session_replay.delete_recordings.activities import (
_parse_session_recording_list_response,
delete_recordings,
@@ -104,63 +107,71 @@ async def test_delete_recordings_url_construction():
)
-async def test_delete_recordings_sends_auth_header():
- mock_response = httpx.Response(
- 200,
- json=[],
- request=httpx.Request("POST", "http://test"),
- )
+def _mock_delete_response_client(mock_client_cls):
+ mock_client = AsyncMock()
+ mock_client.post.return_value = httpx.Response(200, json=[], request=httpx.Request("POST", "http://test"))
+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)
+ mock_client.__aexit__ = AsyncMock(return_value=False)
+ mock_client_cls.return_value = mock_client
+
+ "internal_secret, jwt_secret, expected_headers",
+ [
+ pytest.param("my-secret-key", "", {"X-Internal-Api-Secret"}, id="legacy_secret_only"),
+ pytest.param("", "signing-key", {"Authorization"}, id="jwt_only"),
+ pytest.param(
+ "my-secret-key",
+ "signing-key",
+ {"X-Internal-Api-Secret", "Authorization"},
+ id="both_during_rollout",
+ ),
+ pytest.param("", "", set(), id="nothing_configured"),
+ ],
+)
+async def test_delete_recordings_auth_headers(internal_secret, jwt_secret, expected_headers):
with (
- patch("posthog.temporal.session_replay.delete_recordings.activities.settings") as mock_settings,
+ override_settings(
+ RECORDING_API_URL="http://recording-api:8000",
+ INTERNAL_API_SECRET=internal_secret,
+ RECORDING_API_JWT_SECRET=jwt_secret,
+ ),
patch(
"posthog.temporal.session_replay.delete_recordings.activities.internal_httpx_async_client"
) as mock_client_cls,
):
- mock_settings.RECORDING_API_URL = "http://recording-api:8000"
- mock_settings.INTERNAL_API_SECRET = "my-secret-key"
-
- mock_client = AsyncMock()
- mock_client.post.return_value = mock_response
- mock_client.__aenter__ = AsyncMock(return_value=mock_client)
- mock_client.__aexit__ = AsyncMock(return_value=False)
- mock_client_cls.return_value = mock_client
+ _mock_delete_response_client(mock_client_cls)
await delete_recordings(DeleteRecordingsInput(team_id=1, session_ids=["s1"], deleted_by="[email protected]"))
- mock_client_cls.assert_called_once_with(
- timeout=60.0,
- headers={"X-Internal-Api-Secret": "my-secret-key"},
- )
+ mock_client_cls.assert_called_once()
+ headers = mock_client_cls.call_args.kwargs["headers"]
+ assert set(headers) == expected_headers
+ if "X-Internal-Api-Secret" in expected_headers:
+ assert headers["X-Internal-Api-Secret"] == internal_secret
@pytest.mark.asyncio
-async def test_delete_recordings_no_auth_header_when_secret_empty():
- mock_response = httpx.Response(
- 200,
- json=[],
- request=httpx.Request("POST", "http://test"),
- )
-
+async def test_delete_recordings_token_is_scoped_to_team_and_delete_op():
with (
- patch("posthog.temporal.session_replay.delete_recordings.activities.settings") as mock_settings,
+ override_settings(
+ RECORDING_API_URL="http://recording-api:8000",
+ INTERNAL_API_SECRET="",
+ RECORDING_API_JWT_SECRET="signing-key",
+ ),
patch(
"posthog.temporal.session_replay.delete_recordings.activities.internal_httpx_async_client"
) as mock_client_cls,
):
- mock_settings.RECORDING_API_URL = "http://recording-api:8000"
- mock_settings.INTERNAL_API_SECRET = ""
+ _mock_delete_response_client(mock_client_cls)
- mock_client = AsyncMock()
- mock_client.post.return_value = mock_response
- mock_client.__aenter__ = AsyncMock(return_value=mock_client)
- mock_client.__aexit__ = AsyncMock(return_value=False)
- mock_client_cls.return_value = mock_client
-
- await delete_recordings(DeleteRecordingsInput(team_id=1, session_ids=["s1"], deleted_by="[email protected]"))
+ await delete_recordings(DeleteRecordingsInput(team_id=456, session_ids=["s1"], deleted_by="[email protected]"))
- mock_client_cls.assert_called_once_with(timeout=60.0, headers={})
+ token = mock_client_cls.call_args.kwargs["headers"]["Authorization"].removeprefix("Bearer ")
+ claims = decode_jwt(token, PosthogJwtAudience.RECORDING_API, verification_keys=["signing-key"])
+ assert claims["team_id"] == 456
+ assert claims["op"] == "delete"
@pytest.mark.asyncio
diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
index 731c127c94a1..61b70a324a5b 100644
--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
@@ -1,8 +1,12 @@
import pytest
from unittest.mock import MagicMock, patch
+from django.test import override_settings
+
from parameterized import parameterized
+from posthog.jwt import PosthogJwtAudience, decode_jwt
+from posthog.session_recordings.recordings.recording_api_jwt import recording_api_signing_keys
from posthog.temporal.session_replay.rasterize_recording.activities import (
build_rasterization_input,
finalize_rasterization,
@@ -117,6 +121,32 @@ class TestBuildRasterizationInput:
assert ai.mouse_tail is False
assert ai.max_virtual_time == 300.0
+ def test_mints_team_scoped_read_token(self):
+ asset = _make_asset(pk=42, team_id=7, export_context={"session_recording_id": "abc123"})
+ patches, _ = _patches(asset)
+ with patches[0], patches[1], patches[2], patches[3], patches[4]:
+ result = build_rasterization_input(42)
+
+ ai = result.activity_input
+ assert ai is not None
+ decoded = decode_jwt(
+ ai.recording_api_token, PosthogJwtAudience.RECORDING_API, verification_keys=recording_api_signing_keys()
+ )
+ assert decoded["team_id"] == 7
+ assert decoded["op"] == "read"
+
+ @override_settings(RECORDING_API_JWT_SECRET="")
+ def test_no_token_when_jwt_disabled(self):
+ # Before the JWT scheme is rolled out, the token is empty and the rasterizer relays the
+ # legacy shared secret instead.
+ asset = _make_asset(pk=42, team_id=7, export_context={"session_recording_id": "abc123"})
+ patches, _ = _patches(asset)
+ with patches[0], patches[1], patches[2], patches[3], patches[4]:
+ result = build_rasterization_input(42)
+
+ assert result.activity_input is not None
+ assert result.activity_input.recording_api_token == ""
+
def test_defaults(self):
asset = _make_asset(pk=10, team_id=3, export_context={"session_recording_id": "sess-1"})
patches, _ = _patches(asset)
@@ -405,6 +435,7 @@ class TestFingerprint:
defaults = {
"team_id": 1,
"session_id": "s1",
+ "recording_api_token": "tok",
"s3_bucket": "posthog",
"s3_key_prefix": "exports/mp4/team-1/task-1",
"playback_speed": 4,
@@ -432,6 +463,12 @@ class TestFingerprint:
b = self._make_input(team_id=2, session_id="s2")
assert compute_params_fingerprint(a) == compute_params_fingerprint(b)
+ def test_excludes_recording_api_token(self):
+ # The per-run token must not affect the cache key, or every render would be a cache miss.
+ a = self._make_input(recording_api_token="token-a")
+ b = self._make_input(recording_api_token="token-b")
+ assert compute_params_fingerprint(a) == compute_params_fingerprint(b)
+
@parameterized.expand(
[
("playback_speed", {"playback_speed": 8}),