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(replay): authorize recording-api calls by jwt only (#122982)

Tom Piccirelloa58f724d3373
diff --git a/bin/temporal-recording-rasterizer-worker b/bin/temporal-recording-rasterizer-worker
index 984f6ed6c277..73269900a855 100755
--- a/bin/temporal-recording-rasterizer-worker
+++ b/bin/temporal-recording-rasterizer-worker
@@ -52,7 +52,6 @@ docker run --rm --security-opt seccomp=unconfined --security-opt apparmor=unconf
-e TEMPORAL_HOST="${TEMPORAL_HOST:-posthog-temporal-1}" \
-e TEMPORAL_PORT="${TEMPORAL_PORT:-7233}" \
-e RECORDING_API_BASE_URL="${RECORDING_API_BASE_URL:-http://host.docker.internal:6741}" \
- -e INTERNAL_API_SECRET="${INTERNAL_API_SECRET:-posthog123}" \
-e SITE_URL="${SITE_URL:-http://host.docker.internal:8000}" \
-e VIDEO_EXPORT_OBJECT_STORAGE_ENDPOINT="$video_storage_endpoint" \
-e AWS_ACCESS_KEY_ID=object_storage_root_user \
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index f7dd3742036c..1cd3f8dd228f 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -312,11 +312,10 @@ 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.
+ # The image runs as production, so the in-code dev defaults do not apply. Set
+ # RECORDING_API_JWT_SECRET to the key Django uses under DEBUG, so that local recording
+ # calls authenticate. Keep these known dev values out of docker-compose.base.yml, which
+ # hobby extends, so that a hobby install never runs with them.
INTERNAL_API_SECRET: 'posthog123'
RECORDING_API_JWT_SECRET: 'dev-recording-api-jwt-secret'
depends_on:
diff --git a/docker-compose.hobby.yml b/docker-compose.hobby.yml
index 69e69b305080..83f57e104a0e 100644
--- a/docker-compose.hobby.yml
+++ b/docker-compose.hobby.yml
@@ -319,10 +319,10 @@ services:
SESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY: 'any'
SESSION_RECORDING_V2_S3_ENDPOINT: http://seaweedfs:8333
ENCRYPTION_SALT_KEYS: $ENCRYPTION_SALT_KEYS
- # Both must resolve to the same values as on the web, worker and temporal-django-worker
- # services. Those services sign a team-scoped token with RECORDING_API_JWT_SECRET, and
- # this service verifies it. They also send INTERNAL_API_SECRET as X-Internal-Api-Secret,
- # which this service still accepts in place of a token.
+ # RECORDING_API_JWT_SECRET must resolve to the same value as on the web, worker and
+ # temporal-django-worker services. Those services sign a team-scoped token with it, and
+ # this service verifies it. The recording routes accept no other credential, so this
+ # service refuses to start without the key.
RECORDING_API_JWT_SECRET: ${RECORDING_API_JWT_SECRET:-}
INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-$POSTHOG_SECRET}
depends_on:
@@ -532,8 +532,8 @@ services:
HEATMAP_BROWSERLESS_TOKEN: ${BROWSERLESS_SECRET:-$POSTHOG_SECRET}
HEATMAP_BROWSERLESS_SCREENSHOT_COOKIES_ENABLED: ${HEATMAP_BROWSERLESS_SCREENSHOT_COOKIES_ENABLED:-false}
# This worker runs the recording deletion Temporal activities, which call
- # recording-api. Without the URL and a credential the calls go out unauthenticated
- # and recording-api rejects them with a 401.
+ # recording-api. Without the URL and RECORDING_API_JWT_SECRET, those activities fail
+ # with a configuration error.
RECORDING_API_URL: http://recording-api:6738
INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-$POSTHOG_SECRET}
RECORDING_API_JWT_SECRET: ${RECORDING_API_JWT_SECRET:-}
diff --git a/nodejs/src/servers/recording-api-server.ts b/nodejs/src/servers/recording-api-server.ts
index 588e54d4d2e2..69cf4a01280e 100644
--- a/nodejs/src/servers/recording-api-server.ts
+++ b/nodejs/src/servers/recording-api-server.ts
@@ -89,8 +89,6 @@ export class RecordingApiServer implements NodeServer {
isProd: isProdEnv(),
blocksJwtSecret: this.config.RECORDING_API_BLOCKS_JWT_SECRET,
jwtSecret: this.config.RECORDING_API_JWT_SECRET,
- allowLegacySecret: this.config.RECORDING_API_ALLOW_LEGACY_SECRET,
- legacySecret: this.config.INTERNAL_API_SECRET,
})
// A public process serves only browser block reads, so it never connects to Postgres or Kafka.
diff --git a/nodejs/src/session-replay/recording-api/auth.test.ts b/nodejs/src/session-replay/recording-api/auth.test.ts
index 2ddec0664789..fc7b3d1ef6e3 100644
--- a/nodejs/src/session-replay/recording-api/auth.test.ts
+++ b/nodejs/src/session-replay/recording-api/auth.test.ts
@@ -12,7 +12,6 @@ import {
describe('createRecordingApiAuthMiddleware', () => {
const JWT_SECRET = 'recording-api-secret-key'
- const LEGACY_SECRET = 'legacy-internal-secret'
const mintToken = (
claims: { team_id: number; op: string },
@@ -41,8 +40,6 @@ describe('createRecordingApiAuthMiddleware', () => {
const run = (opts: Partial<RecordingApiAuthOptions>, req: Request) => {
const middleware = createRecordingApiAuthMiddleware({
jwtSecret: JWT_SECRET,
- legacySecret: LEGACY_SECRET,
- allowLegacySecret: false,
op: 'read',
...opts,
})
@@ -54,8 +51,9 @@ describe('createRecordingApiAuthMiddleware', () => {
const bearer = (token: string) => ({ authorization: `Bearer ${token}` })
- it('skips authorization when no jwt secret configured (local dev)', () => {
- const { res, next } = run({ jwtSecret: '' }, mockRequest('123'))
+ // ',' is truthy but yields zero keys, so it must disable JWT rather than build a verifier that throws.
+ it.each([[''], [',']])('skips authorization when jwt secret %p has no keys (local dev)', (jwtSecret) => {
+ const { res, next } = run({ jwtSecret }, mockRequest('123'))
expect(next).toHaveBeenCalled()
expect(res.status).not.toHaveBeenCalled()
})
@@ -133,44 +131,6 @@ describe('createRecordingApiAuthMiddleware', () => {
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')
@@ -207,37 +167,6 @@ describe('createRecordingApiAuthMiddleware', () => {
})
})
- 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.
@@ -262,9 +191,9 @@ describe('createRecordingApiAuthMiddleware', () => {
})
describe('assertRecordingApiAuthConfigured', () => {
- const base = { isProd: true, jwtSecret: '', allowLegacySecret: true, legacySecret: '' }
+ const base = { isProd: true, jwtSecret: '' }
- it('throws in production when neither a JWT nor a legacy secret is configured', () => {
+ it('throws in production when no JWT secret is configured', () => {
expect(() => assertRecordingApiAuthConfigured(base)).toThrow(/no auth configured in production/)
})
@@ -272,20 +201,10 @@ describe('assertRecordingApiAuthConfigured', () => {
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
index f79494f5946c..a721bb13ff10 100644
--- a/nodejs/src/session-replay/recording-api/auth.ts
+++ b/nodejs/src/session-replay/recording-api/auth.ts
@@ -1,8 +1,6 @@
-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'
import { RecordingApiRole } from './types'
@@ -12,8 +10,7 @@ import { RecordingApiRole } from './types'
*
* 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, delete or write). During migration the legacy `X-Internal-Api-Secret` is
- * accepted as a fallback while `allowLegacySecret` is true; the final cutover flips that flag off.
+ * must match the route (read, delete or write).
*/
export type RecordingApiOp = 'read' | 'delete' | 'write'
@@ -24,8 +21,6 @@ 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
}
@@ -74,34 +69,22 @@ function verifyBearer(
}
}
-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".
+ * Fail closed in production: recording routes must have a JWT secret, because without one the
+ * middleware below lets every request through. 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) {
+export function assertRecordingApiAuthConfigured(opts: { isProd: boolean; jwtSecret: string }): void {
+ if (hasJwtKeys(opts.jwtSecret || '')) {
+ return
+ }
+ if (opts.isProd) {
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'
+ 'recording-api has no auth configured in production: set RECORDING_API_JWT_SECRET ' +
+ '(hobby installs: run bin/upgrade-hobby)'
)
}
+ logger.warn('recording-api has no RECORDING_API_JWT_SECRET: recording routes accept every request')
}
/**
@@ -114,8 +97,6 @@ export function assertRecordingApiRoleAuthConfigured(opts: {
isProd: boolean
blocksJwtSecret: string
jwtSecret: string
- allowLegacySecret: boolean
- legacySecret: string
}): void {
if (opts.role !== 'internal' && opts.isProd && !hasJwtKeys(opts.blocksJwtSecret || '')) {
throw new Error('recording-api serving browser blocks needs RECORDING_API_BLOCKS_JWT_SECRET in production')
@@ -131,49 +112,36 @@ export function internalApiAuthExcludedPathPrefixes(role: RecordingApiRole): str
}
export function createRecordingApiAuthMiddleware(options: RecordingApiAuthOptions) {
- const { jwtSecret, legacySecret, allowLegacySecret, op } = options
+ const { jwtSecret, 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) {
+ // No JWT secret configured (local dev): allow. Production refuses to boot in this state, see
+ // assertRecordingApiAuthConfigured.
+ if (!jwt) {
next()
return
}
- if (jwt) {
- const bearer = getBearerToken(req)
- if (bearer) {
- // An invalid token falls through to the legacy secret (transition) or a 401.
- const claims = verifyBearer(jwt, bearer, PosthogJwtAudience.RECORDING_API)
- if (claims) {
- 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()
+ const bearer = getBearerToken(req)
+ if (bearer) {
+ const claims = verifyBearer(jwt, bearer, PosthogJwtAudience.RECORDING_API)
+ if (claims) {
+ 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
}
- // 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
}
@@ -187,7 +155,7 @@ export function createRecordingApiAuthMiddleware(options: RecordingApiAuthOption
const REPLAY_BLOCKS_TOKEN_MAX_AGE = '2h'
// The browser block route accepts only browser tokens, a separate audience from the service tokens above.
-// There is no legacy fallback and no dev bypass: without a secret, every request is refused.
+// There is no dev bypass: without a secret, every request is refused.
export function createReplayBlocksAuthMiddleware(jwtSecret: string) {
const jwt = makeOptionalJwt(jwtSecret)
diff --git a/nodejs/src/session-replay/recording-api/recording-api.test.ts b/nodejs/src/session-replay/recording-api/recording-api.test.ts
index c98e12e8fb91..d8eecc7cd17e 100644
--- a/nodejs/src/session-replay/recording-api/recording-api.test.ts
+++ b/nodejs/src/session-replay/recording-api/recording-api.test.ts
@@ -728,7 +728,6 @@ describe('RecordingApi', () => {
const recordingApi = new RecordingApi(
{
RECORDING_API_JWT_SECRET: JWT_SECRET,
- RECORDING_API_ALLOW_LEGACY_SECRET: false,
} as RecordingApiConfig,
mockPostgres,
mockOutputs
@@ -764,34 +763,6 @@ describe('RecordingApi', () => {
expect(res.status).toBe(expectedStatus)
})
- it('accepts the legacy secret while JWT auth is not configured', async () => {
- const legacyApi = new RecordingApi(
- {
- RECORDING_API_JWT_SECRET: '',
- RECORDING_API_ALLOW_LEGACY_SECRET: true,
- INTERNAL_API_SECRET: 'legacy-secret',
- } as RecordingApiConfig,
- mockPostgres,
- mockOutputs
- )
- await legacyApi.start(mockService)
- const legacyApp = express()
- legacyApp.use(express.json())
- legacyApp.use('/', legacyApi.router())
- const legacyServer = legacyApp.listen(0, () => {})
-
- try {
- const res = await supertest(legacyApp)
- .post('/api/projects/1/recordings/session-1/encrypt')
- .set('X-Internal-Api-Secret', 'legacy-secret')
- .send(body)
-
- expect(res.status).toBe(200)
- } finally {
- legacyServer.close()
- }
- })
-
it.each([
[
{ ok: true, blocks: [Buffer.from('sealed')] },
@@ -843,7 +814,6 @@ describe('RecordingApi', () => {
{
RECORDING_API_JWT_SECRET: JWT_SECRET,
RECORDING_API_BLOCKS_JWT_SECRET: BLOCKS_JWT_SECRET,
- RECORDING_API_ALLOW_LEGACY_SECRET: false,
RECORDING_API_ROLE: role,
RECORDING_API_BLOCK_RATE_LIMIT_ENFORCED: enforced,
} as RecordingApiConfig,
diff --git a/nodejs/src/session-replay/recording-api/recording-api.ts b/nodejs/src/session-replay/recording-api/recording-api.ts
index fcaa833c0593..2fbdd22008ff 100644
--- a/nodejs/src/session-replay/recording-api/recording-api.ts
+++ b/nodejs/src/session-replay/recording-api/recording-api.ts
@@ -302,8 +302,6 @@ export class RecordingApi {
const auth = (op: RecordingApiOp) =>
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')
diff --git a/nodejs/src/session-replay/recording-api/types.ts b/nodejs/src/session-replay/recording-api/types.ts
index 39b91dfa91e8..feb4eb593b43 100644
--- a/nodejs/src/session-replay/recording-api/types.ts
+++ b/nodejs/src/session-replay/recording-api/types.ts
@@ -42,19 +42,16 @@ export {
*
* `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.
+ * valid tokens.
*/
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,
}
}
@@ -142,7 +139,7 @@ export function parseRecordingApiRole(role: string): RecordingApiRole {
*/
export type RecordingApiConfig = Pick<
CommonConfig,
- 'KAFKA_CLIENT_RACK' | 'REDIS_POOL_MIN_SIZE' | 'REDIS_POOL_MAX_SIZE' | 'INTERNAL_API_SECRET'
+ 'KAFKA_CLIENT_RACK' | 'REDIS_POOL_MIN_SIZE' | 'REDIS_POOL_MAX_SIZE'
> &
Pick<
SessionRecordingApiConfig,
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 4799d1703a85..7f6dc85842d9 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
@@ -19,7 +19,6 @@ function baseInput(overrides: Partial<RasterizeRecordingInput> = {}): RasterizeR
const testCfg = {
recordingApiBaseUrl: 'http://localhost:6738',
- recordingApiSecret: 'test-secret',
blockListingTimeoutMs: 30_000,
}
@@ -59,7 +58,7 @@ describe('BlockProxy', () => {
expect(proxy.totalCompressedBytes).toBe(3002)
expect(mockInternalFetch).toHaveBeenCalledWith(
'http://localhost:6738/api/projects/1/recordings/test-session-123/blocks',
- { headers: { 'X-Internal-Api-Secret': 'test-secret' }, timeoutMs: 30_000 }
+ { headers: {}, timeoutMs: 30_000 }
)
})
@@ -75,7 +74,7 @@ describe('BlockProxy', () => {
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' },
+ headers: { Authorization: 'Bearer minted-token' },
timeoutMs: 30_000,
}
)
@@ -178,7 +177,7 @@ describe('BlockProxy', () => {
expect(mockInternalFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/projects/1/recordings/test-session-123/block?'),
- { headers: { 'X-Internal-Api-Secret': 'test-secret' } }
+ { headers: {} }
)
const fetchUrl = mockInternalFetch.mock.calls[0][0] as string
expect(fetchUrl).toContain('key=recordings%2Fblock-0')
@@ -202,7 +201,7 @@ describe('BlockProxy', () => {
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' },
+ headers: { Authorization: 'Bearer minted-token' },
})
})
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
index bb5935701e02..e31e0fdafa26 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
@@ -336,10 +336,5 @@ describe('config', () => {
const result = buildPlayerConfig(baseInput({ viewport_events: events }), 4, 5)
expect(result.viewportEvents).toEqual(events)
})
-
- it('does not include recording API secret in player config', () => {
- const result = buildPlayerConfig(baseInput(), 4, 5)
- expect(result).not.toHaveProperty('recordingApiSecret')
- })
})
})
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts
index 121e7df8cffc..4f639503054f 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts
@@ -54,7 +54,6 @@ const cfg = {
siteUrl: 'http://localhost:8000',
captureBrowserLogs: false,
recordingApiBaseUrl: 'http://localhost:6738',
- recordingApiSecret: 'secret',
screenshotFormat: 'jpeg' as const,
screenshotJpegQuality: 80,
maxRecordingCompressedBytes: 512 * 1024 * 1024,
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 96ae5b38ae30..d2512a65bc8b 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
@@ -28,7 +28,6 @@ export class BlockProxy implements BlockSource {
constructor(
private cfg: {
recordingApiBaseUrl: string
- recordingApiSecret: string
blockListingTimeoutMs: number
},
private log: Logger = createLogger()
@@ -44,17 +43,10 @@ export class BlockProxy implements BlockSource {
return this.blocks.reduce((sum, block) => sum + (block.end_byte - block.start_byte + 1), 0)
}
- // 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.
+ // The rasterizer holds no recording-api credential of its own. It relays the team-scoped token
+ // that the Temporal activity minted for this render.
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
+ return this.recordingApiToken ? { Authorization: `Bearer ${this.recordingApiToken}` } : {}
}
async fetchBlocks(input: RasterizeRecordingInput): Promise<number> {
diff --git a/nodejs/src/session-replay/recording-rasterizer/config.ts b/nodejs/src/session-replay/recording-rasterizer/config.ts
index bcd6f5cab4b9..2be1fbe19233 100644
--- a/nodejs/src/session-replay/recording-rasterizer/config.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/config.ts
@@ -66,7 +66,6 @@ export const config = {
// Recording API. The dev recording-api listens on 6741 (bin/temporal-recording-rasterizer-worker).
recordingApiBaseUrl: process.env.RECORDING_API_BASE_URL || 'http://localhost:6741',
- recordingApiSecret: process.env.INTERNAL_API_SECRET || '',
// The listing hits ClickHouse through recording-api, so internalFetch's 3s default aborts it under load.
blockListingTimeoutMs: parsePositiveInt(process.env.BLOCK_LISTING_TIMEOUT_MS, 30_000),
// Renders above this many compressed bytes fail permanently instead of loading the pod into its
diff --git a/nodejs/tests/session-replay/recording-api/recording-api.integration.serial.test.ts b/nodejs/tests/session-replay/recording-api/recording-api.integration.serial.test.ts
index 1c4adde120ef..8368cddcd26e 100644
--- a/nodejs/tests/session-replay/recording-api/recording-api.integration.serial.test.ts
+++ b/nodejs/tests/session-replay/recording-api/recording-api.integration.serial.test.ts
@@ -744,7 +744,7 @@ describe('Recording API encryption integration', () => {
// 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 INTERNAL_SECRET = 'itest-internal-secret'
const TEAM = 1
const SESSION = 'auth-session-1'
const BLOCK_KEY = 'session_recordings/30d/1764634738680-3cca0f5d3c7cc7ee'
@@ -781,8 +781,6 @@ describe('Recording API encryption integration', () => {
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> => {
@@ -792,7 +790,7 @@ describe('Recording API encryption integration', () => {
// 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 ?? '',
+ internalApiSecret: INTERNAL_SECRET,
internalApiAuthExcludedPathPrefixes: ['/api/projects/'],
})
app.use('/', api.router())
@@ -888,19 +886,9 @@ describe('Recording API encryption integration', () => {
expect(res.status).toBe(401)
})
- it('accepts the legacy secret while allowLegacySecret is true', async () => {
+ it('rejects the shared internal secret that the rest of the app accepts', 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 })
+ const res = await getBlock(app, { 'X-Internal-Api-Secret': INTERNAL_SECRET })
expect(res.status).toBe(401)
})
diff --git a/posthog/session_recordings/recordings/recording_api_client.py b/posthog/session_recordings/recordings/recording_api_client.py
index 1059caeefb1a..7f633d45a13e 100644
--- a/posthog/session_recordings/recordings/recording_api_client.py
+++ b/posthog/session_recordings/recordings/recording_api_client.py
@@ -167,11 +167,11 @@ async def recording_api_client() -> AsyncIterator[RecordingApiClient]:
if not settings.RECORDING_API_URL:
raise RecordingApiConfigurationError("RECORDING_API_URL is not configured")
- # Without a credential every request is sent unauthenticated and comes back 401, which the tolerant
- # handlers flatten into an empty listing exactly as a missing URL used to. The delete-recordings
- # activity already treats both settings as the same permanent fault.
- if not settings.INTERNAL_API_SECRET and not recording_api_jwt_enabled():
- raise RecordingApiConfigurationError("Neither INTERNAL_API_SECRET nor RECORDING_API_JWT_SECRET is configured")
+ # Every request mints a token with this secret. Check it once here, so a missing secret raises the
+ # same configuration error as a missing URL. The delete-recordings activity treats both settings
+ # as the same permanent fault.
+ if not recording_api_jwt_enabled():
+ raise RecordingApiConfigurationError("RECORDING_API_JWT_SECRET is not configured")
timeout = aiohttp.ClientTimeout(total=30, connect=5)
# Authorization is per-request (a team + operation scoped JWT), so no session-level auth header.
diff --git a/posthog/session_recordings/recordings/recording_api_jwt.py b/posthog/session_recordings/recordings/recording_api_jwt.py
index 5e6dcd437d97..7eed1e51872c 100644
--- a/posthog/session_recordings/recordings/recording_api_jwt.py
+++ b/posthog/session_recordings/recordings/recording_api_jwt.py
@@ -1,15 +1,9 @@
from datetime import timedelta
from typing import Literal
-from django.conf import settings
-
-import structlog
-
from posthog.jwt import PosthogJwtAudience
from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
-logger = structlog.get_logger(__name__)
-
RecordingApiOp = Literal["read", "delete", "write"]
# Direct callers mint a fresh token per request, so a short lifetime suffices. The rasterizer
@@ -31,26 +25,15 @@ def recording_api_signing_keys() -> list[str]:
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."""
+ """True once a dedicated signing secret is configured. recording-api accepts no other credential,
+ so callers check this first and raise RecordingApiConfigurationError when it is False."""
return RECORDING_API_JWT_PURPOSE.enabled()
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
+ """Auth headers for a recording-api request: a freshly minted team + operation scoped Bearer
+ token. Raises RuntimeError when the signing secret is not configured."""
+ return {"Authorization": f"Bearer {mint_recording_api_token(team_id, op)}"}
def mint_recording_api_token(team_id: int, op: RecordingApiOp, ttl: timedelta = DEFAULT_RECORDING_API_TOKEN_TTL) -> str:
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 3de3ff183a18..b18c995eeda8 100644
--- a/posthog/session_recordings/test/recordings/test_recording_api_client.py
+++ b/posthog/session_recordings/test/recordings/test_recording_api_client.py
@@ -437,36 +437,19 @@ class TestPerRequestAuthScoping:
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):
+class TestAuthHeaders:
+ @override_settings(RECORDING_API_JWT_SECRET="dev-secret", INTERNAL_API_SECRET="internal")
+ def test_sends_only_the_bearer_token_when_internal_secret_is_set(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")
-
class TestClientPreconditions:
@pytest.mark.asyncio
@override_settings(
- RECORDING_API_URL="http://recording-api:6738", RECORDING_API_JWT_SECRET="", INTERNAL_API_SECRET=""
+ RECORDING_API_URL="http://recording-api:6738", RECORDING_API_JWT_SECRET="", INTERNAL_API_SECRET="internal"
)
- async def test_no_credential_is_a_configuration_error_not_a_401(self):
+ async def test_no_signing_secret_is_a_configuration_error_not_a_401(self):
# Without a credential the request goes out unauthenticated and comes back 401, which the
# tolerant listing handlers flatten into "this recording has no blocks".
with pytest.raises(RecordingApiConfigurationError):
diff --git a/posthog/temporal/session_replay/delete_recordings/activities.py b/posthog/temporal/session_replay/delete_recordings/activities.py
index 98a3f27624c1..14670ee5e68e 100644
--- a/posthog/temporal/session_replay/delete_recordings/activities.py
+++ b/posthog/temporal/session_replay/delete_recordings/activities.py
@@ -14,7 +14,10 @@ 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.errors import RecordingApiConfigurationError
-from posthog.session_recordings.recordings.recording_api_jwt import recording_api_auth_headers
+from posthog.session_recordings.recordings.recording_api_jwt import (
+ recording_api_auth_headers,
+ recording_api_jwt_enabled,
+)
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
@@ -209,9 +212,9 @@ async def delete_recordings(input: DeleteRecordingsInput) -> DeleteRecordingsRes
url = f"{recording_api_url}/api/projects/{input.team_id}/recordings/delete"
+ if not recording_api_jwt_enabled():
+ raise RecordingApiConfigurationError("RECORDING_API_JWT_SECRET is not configured")
headers = recording_api_auth_headers(input.team_id, "delete")
- if not headers:
- raise RecordingApiConfigurationError("Neither INTERNAL_API_SECRET nor RECORDING_API_JWT_SECRET is configured")
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 a4d2d409df05..8d7b625e2e4b 100644
--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
@@ -147,11 +147,11 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResul
s3_key_prefix = f"{settings.OBJECT_STORAGE_EXPORTS_FOLDER}/{output_format}/team-{asset.team_id}/task-{asset.id}"
- # 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 ""
- )
+ # The rasterizer relays this token on every block request and has no other recording-api
+ # credential, so a render without one cannot fetch a single block.
+ if not recording_api_jwt_enabled():
+ raise ApplicationError("RECORDING_API_JWT_SECRET is not configured", non_retryable=True)
+ recording_api_token = mint_recording_api_token(asset.team_id, "read", ttl=_RASTERIZE_TOKEN_TTL)
activity_input = rasterization_input_from_context(
ctx,
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 fc0da44e6d94..5eb9b965c5e8 100644
--- a/posthog/temporal/tests/session_replay/delete_recordings/test_activities.py
+++ b/posthog/temporal/tests/session_replay/delete_recordings/test_activities.py
@@ -117,25 +117,12 @@ def _mock_delete_response_client(mock_client_cls):
@pytest.mark.asyncio
- "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",
- ),
- ],
-)
-async def test_delete_recordings_auth_headers(internal_secret, jwt_secret, expected_headers):
+async def test_delete_recordings_sends_only_the_bearer_token():
with (
override_settings(
RECORDING_API_URL="http://recording-api:8000",
- INTERNAL_API_SECRET=internal_secret,
- RECORDING_API_JWT_SECRET=jwt_secret,
+ INTERNAL_API_SECRET="my-secret-key",
+ RECORDING_API_JWT_SECRET="signing-key",
),
patch(
"posthog.temporal.session_replay.delete_recordings.activities.internal_httpx_async_client"
@@ -147,9 +134,7 @@ async def test_delete_recordings_auth_headers(internal_secret, jwt_secret, expec
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
+ assert set(headers) == {"Authorization"}
@pytest.mark.asyncio
@@ -184,11 +169,11 @@ async def test_delete_recordings_raises_when_no_recording_api_url():
@pytest.mark.asyncio
-async def test_delete_recordings_raises_when_no_credential_configured():
+async def test_delete_recordings_raises_when_no_signing_secret_configured():
with (
override_settings(
RECORDING_API_URL="http://recording-api:8000",
- INTERNAL_API_SECRET="",
+ INTERNAL_API_SECRET="internal",
RECORDING_API_JWT_SECRET="",
),
patch(
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 0be622893fb8..51b5e9df9c2c 100644
--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
@@ -153,16 +153,13 @@ class TestBuildRasterizationInput:
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.
+ def test_fails_without_signing_secret(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)
-
- assert result.activity_input is not None
- assert result.activity_input.recording_api_token == ""
+ with pytest.raises(ApplicationError, match="RECORDING_API_JWT_SECRET") as excinfo:
+ build_rasterization_input(42)
+ assert excinfo.value.non_retryable
def test_defaults(self):
asset = _make_asset(pk=10, team_id=3, export_context={"session_recording_id": "sess-1"})