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.

refactor(session-replay): harden ffmpeg input handling in rasterizer (#63876)

Tom Piccirello9ea23d5cd3d0
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 cb557c412c54..7caa94325418 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
@@ -215,6 +215,38 @@ describe('config', () => {
expect(config.trimFrameLimit).toBe(24)
})
})
+
+ describe('ffmpeg argument safety', () => {
+ it.each([
+ { field: 'trim', value: Infinity },
+ { field: 'trim', value: '10 -i /etc/passwd' },
+ { field: 'trim', value: 'not-a-number' },
+ { field: 'playback_speed', value: Infinity },
+ { field: 'playback_speed', value: '8 -vf evil' },
+ { field: 'playback_speed', value: 'NaN' },
+ { field: 'recording_fps', value: Infinity },
+ { field: 'recording_fps', value: '24; rm -rf /' },
+ { field: 'recording_fps', value: 'abc' },
+ ])('throws on non-finite $field=$value before it reaches an ffmpeg arg', ({ field, value }) => {
+ expect(() => buildCaptureConfig(baseInput({ [field]: value as any }))).toThrow(
+ 'must be a finite number'
+ )
+ })
+
+ it('emits the -t value as a single numeric token (no embedded flags)', () => {
+ const config = buildCaptureConfig(baseInput({ trim: 60 }))
+ const tOpt = config.ffmpegOutputOpts.find((o) => o.startsWith('-t'))
+ // Exactly two space-separated tokens → fluent-ffmpeg passes ['-t', '60'],
+ // so an attacker can never split the value into extra ffmpeg arguments.
+ expect(tOpt!.split(' ')).toEqual(['-t', '60'])
+ })
+
+ it('interpolates speed/fps as bare numbers into the filtergraph', () => {
+ const config = buildCaptureConfig(baseInput({ playback_speed: 8, recording_fps: 24 }))
+ expect(config.ffmpegVideoFilters).toContain('setpts=8*PTS')
+ expect(config.ffmpegVideoFilters).toContain('fps=24')
+ })
+ })
})
describe('buildPlayerConfig', () => {
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/config.ts b/nodejs/src/session-replay/recording-rasterizer/capture/config.ts
index 07e6dc3c0f82..d49cdc2556e6 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/config.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/config.ts
@@ -6,6 +6,19 @@ import { CaptureConfig, RasterizeRecordingInput } from '../types'
const DEFAULT_PLAYBACK_SPEED = 4
const DEFAULT_FPS = 24
+// Coerce a value interpolated into an ffmpeg option (`-t`) or filter (`setpts=`, `fps=`) to a
+// finite number. ffmpeg is spawned without a shell, but a non-finite/non-numeric value reaching
+// here (e.g. from a future caller that skips upstream validation) could still land in the option
+// list or filtergraph as a raw string. Throwing keeps interpolation injection-proof regardless of
+// the caller: a finite number stringifies to [0-9.eE+-] only — no spaces or filter metacharacters.
+function toFiniteNumber(value: unknown, field: string): number {
+ const n = Number(value)
+ if (!Number.isFinite(n)) {
+ throw new RasterizationError(`${field} must be a finite number, got: ${String(value)}`, false, 'INVALID_INPUT')
+ }
+ return n
+}
+
export function validateInput(input: RasterizeRecordingInput): void {
if (!input.session_id) {
throw new RasterizationError('session_id is required', false, 'INVALID_INPUT')
@@ -47,8 +60,11 @@ export function validateInput(input: RasterizeRecordingInput): void {
}
export function buildCaptureConfig(input: RasterizeRecordingInput): CaptureConfig {
- const playbackSpeed = input.playback_speed || DEFAULT_PLAYBACK_SPEED
- const outputFps = input.recording_fps || DEFAULT_FPS
+ const playbackSpeed = input.playback_speed
+ ? toFiniteNumber(input.playback_speed, 'playback_speed')
+ : DEFAULT_PLAYBACK_SPEED
+ const outputFps = input.recording_fps ? toFiniteNumber(input.recording_fps, 'recording_fps') : DEFAULT_FPS
+ const trim = input.trim ? toFiniteNumber(input.trim, 'trim') : undefined
// e.g. 3fps output × 8x speed = 24fps capture → setpts stretches 8x → 3fps
const captureFps = outputFps * playbackSpeed
const outputFormat = input.output_format || 'mp4'
@@ -59,8 +75,8 @@ export function buildCaptureConfig(input: RasterizeRecordingInput): CaptureConfi
: outputFormat === 'gif'
? ['-f gif', '-c:v gif', '-loop', '0']
: ['-f mp4', '-c:v libx264', '-preset veryfast', '-crf 23', '-pix_fmt yuv420p', '-movflags +faststart']
- if (input.trim) {
- ffmpegOutputOpts.push(`-t ${input.trim}`)
+ if (trim) {
+ ffmpegOutputOpts.push(`-t ${trim}`)
}
const ffmpegVideoFilters: string[] = []
@@ -92,8 +108,8 @@ export function buildCaptureConfig(input: RasterizeRecordingInput): CaptureConfi
captureFps,
outputFps,
playbackSpeed,
- trim: input.trim,
- trimFrameLimit: input.trim ? input.trim * outputFps : Infinity,
+ trim,
+ trimFrameLimit: trim ? trim * outputFps : Infinity,
maxVirtualTimeMs: input.max_virtual_time ? input.max_virtual_time * 1000 : Infinity,
outputFormat,
ffmpegOutputOpts,
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
index 2b085ccbca32..223cd12dc71d 100644
--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
@@ -58,6 +58,14 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResul
# 1x for short clips so output plays in real time; 4x for full sessions to cap file size.
default_speed = 1 if (duration is not None and duration <= 5) else 4
playback_speed = ctx.get("playback_speed", default_speed)
+ recording_fps = ctx.get("recording_fps", 24)
+ # Cap the render rate so a large fps × speed product can't exhaust the shared rasterizer pool.
+ # Upper bound only: positivity is enforced in the Node validateInput, and fractional
+ # slow-motion speeds (< 1) are valid.
+ if playback_speed is not None:
+ playback_speed = min(360.0, float(playback_speed))
+ if recording_fps is not None:
+ recording_fps = min(60, int(recording_fps))
activity_input = RasterizationActivityInput(
team_id=asset.team_id,
@@ -65,7 +73,7 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResul
s3_bucket=settings.OBJECT_STORAGE_BUCKET,
s3_key_prefix=s3_key_prefix,
playback_speed=playback_speed,
- recording_fps=ctx.get("recording_fps", 24),
+ recording_fps=recording_fps,
trim=ctx.get("trim"),
show_metadata_footer=ctx.get("show_metadata_footer", False),
viewport_width=viewport_width,
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 2a1b3d5426ed..731c127c94a1 100644
--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
@@ -253,6 +253,39 @@ class TestBuildRasterizationInput:
assert result.activity_input is not None
assert getattr(result.activity_input, field) == expected_value
+ @parameterized.expand(
+ [
+ ("in_range", 24, 24),
+ ("at_cap", 60, 60),
+ ("above_cap", 1000, 60),
+ ("absurd", 100_000, 60),
+ ]
+ )
+ def test_recording_fps_capped(self, _name, recording_fps, expected_fps):
+ asset = _make_asset(pk=50, export_context={"session_recording_id": "s1", "recording_fps": recording_fps})
+ patches, _ = _patches(asset)
+ with patches[0], patches[1], patches[2], patches[3], patches[4]:
+ result = build_rasterization_input(50)
+ assert result.activity_input is not None
+ assert result.activity_input.recording_fps == expected_fps
+
+ @parameterized.expand(
+ [
+ ("slow_motion_preserved", 0.5, 0.5),
+ ("default_in_range", 4, 4),
+ ("at_cap", 360, 360),
+ ("above_cap", 1000, 360),
+ ("absurd", 99_999, 360),
+ ]
+ )
+ def test_playback_speed_capped(self, _name, playback_speed, expected_speed):
+ asset = _make_asset(pk=50, export_context={"session_recording_id": "s1", "playback_speed": playback_speed})
+ patches, _ = _patches(asset)
+ with patches[0], patches[1], patches[2], patches[3], patches[4]:
+ result = build_rasterization_input(50)
+ assert result.activity_input is not None
+ assert result.activity_input.playback_speed == expected_speed
+
class TestBuildRasterizationCache:
def _ctx_with_render(self, fingerprint: str, **overrides) -> dict: