: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(auth): migrate reschedule_parked and recording-api onto the scoped JWT machinery (#82784)
Harley Alexander51def57ea12d
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex 2b500a7ffeb8..7745d9e1e012 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -7,6 +7,8 @@ import supertest from 'supertest'import express from 'ultimate-express'import { HogFlow } from '~/cdp/schema/hogflow'+import { PosthogJwtAudience } from '~/cdp/utils/jwt-utils'+import { ScopedServiceJwt } from '~/cdp/utils/scoped-service-jwt'import { setupExpressApp } from '~/common/api/router'import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'import { createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'@@ -1694,7 +1696,7 @@ describe('CDP API', () => {it('fails closed when the reschedule JWT key is not provisioned', async () => {const savedJwt = api['rescheduleJwt']- api['rescheduleJwt'] = null+ api['rescheduleJwt'] = new ScopedServiceJwt(PosthogJwtAudience.WORKFLOWS_RESCHEDULE_PARKED, '')try {const res = await supertest(app).post(diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 5c4e0572582a..489f78e02dc6 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -72,7 +72,8 @@ import {import { dualRead, dualWrite } from './utils/dual-store'import { convertToHogFunctionFilterGlobal } from './utils/hog-function-filtering'import { buildHogFunctionInvocations } from './utils/invocation-utils'-import { JWT, PosthogJwtAudience } from './utils/jwt-utils'+import { PosthogJwtAudience } from './utils/jwt-utils'+import { ScopedServiceJwt } from './utils/scoped-service-jwt'// Allowlist of safe content types for webhook responses to prevent XSSconst SAFE_CONTENT_TYPES = new Set([@@ -144,9 +145,9 @@ export class CdpApi {private groupsManager: GroupsManagerServiceprivate batchResolverProducer: CyclotronV2JobProducer | null// Scoped auth for the reschedule_parked route (exempted from the shared internal-secret- // middleware): Django mints per-call JWTs pinned to a team + workflow. Null when the key+ // middleware): Django mints per-call JWTs pinned to a team + workflow. Disabled when the key// isn't provisioned — the route then fails closed.- private rescheduleJwt: JWT | null+ private rescheduleJwt: ScopedServiceJwtconstructor(private config: PluginsServerConfig,@@ -198,9 +199,10 @@ export class CdpApi {this.hogWatcherMirror)this.batchResolverProducer = batchResolverProducer- this.rescheduleJwt = config.WORKFLOWS_RESCHEDULE_JWT_SECRET- ? new JWT(config.WORKFLOWS_RESCHEDULE_JWT_SECRET)- : null+ this.rescheduleJwt = new ScopedServiceJwt(+ PosthogJwtAudience.WORKFLOWS_RESCHEDULE_PARKED,+ config.WORKFLOWS_RESCHEDULE_JWT_SECRET || ''+ )}public get service(): PluginServerService {@@ -1035,7 +1037,7 @@ export class CdpApi {error: 'Cyclotron producer not initialized (CYCLOTRON_NODE_DATABASE_URL unset)',})}- if (!this.rescheduleJwt) {+ if (!this.rescheduleJwt.enabled) {return res.status(503).json({error: 'Reschedule auth not configured (WORKFLOWS_RESCHEDULE_JWT_SECRET unset)',})@@ -1046,11 +1048,12 @@ export class CdpApi {const authHeader = req.headers['authorization']const token =typeof authHeader === 'string' && authHeader.startsWith('Bearer ') ? authHeader.slice(7) : undefined- const claims = token- ? (this.rescheduleJwt.verify(token, PosthogJwtAudience.WORKFLOWS_RESCHEDULE_PARKED, {- ignoreVerificationErrors: true,- }) as { team_id?: number; hog_flow_id?: string } | undefined)- : undefined+ let claims: { team_id?: number; hog_flow_id?: string } | undefined+ try {+ claims = token ? (this.rescheduleJwt.verify(token) as typeof claims) : undefined+ } catch {+ claims = undefined+ }// The claims pin the token to one team + workflow, so a leaked token can't sweep anything else.if (!claims || claims.team_id !== parseInt(team_id) || claims.hog_flow_id !== id) {return res.status(401).json({ error: 'Unauthorized: Invalid reschedule token' })diff --git a/posthog/jwt.py b/posthog/jwt.pyindex 0f7e8a557b90..8a9f0ffeed3c 100644--- a/posthog/jwt.py+++ b/posthog/jwt.py@@ -19,6 +19,7 @@ class PosthogJwtAudience(Enum):LIVESTREAM = "posthog:livestream"SHARING_PASSWORD_PROTECTED = "posthog:sharing_password_protected"RECORDING_API = "posthog:recording_api"+ WORKFLOWS_RESCHEDULE_PARKED = "posthog:workflows:reschedule_parked"INTEGRATION_SERVICE = "posthog:integration_service"diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.pyindex 2d9d4ae49ff1..6891c3ea6ab9 100644--- a/posthog/plugins/plugin_server_api.py+++ b/posthog/plugins/plugin_server_api.py@@ -1,15 +1,14 @@import json-from datetime import UTC, datetime, timedelta+from datetime import timedeltafrom typing import Optional, Union-from django.conf import settings--import jwtimport requestsimport structlog+from posthog.jwt import PosthogJwtAudiencefrom posthog.models.utils import UUIDTfrom posthog.redis import get_client+from posthog.scoped_service_jwt import ScopedServiceJwtPurposefrom posthog.security.outbound_proxy import internal_requestsfrom posthog.settings import CDP_API_URL, INTERNAL_API_SECRET, PLUGINS_RELOAD_REDIS_URL@@ -122,24 +121,21 @@ def get_hog_flow_in_flight_count(team_id: int, hog_flow_id: str) -> requests.Res)+WORKFLOWS_RESCHEDULE_JWT_PURPOSE = ScopedServiceJwtPurpose(+ audience=PosthogJwtAudience.WORKFLOWS_RESCHEDULE_PARKED,+ settings_name="WORKFLOWS_RESCHEDULE_JWT_SECRETS",+ default_ttl=timedelta(minutes=2),+)++def _mint_reschedule_parked_jwt(team_id: int, hog_flow_id: str) -> str:"""Short-lived scoped JWT for one reschedule_parked call — a leaked token can only sweep thisone team + workflow. Signed with the dedicated key (never INTERNAL_API_SECRET / SECRET_KEY /JWT_SIGNING_KEY, per .agents/security.md); raises when unprovisioned so the sweep fails closed.Verified in the plugin server's CdpApi.postHogFlowRescheduleParked."""- secrets = settings.WORKFLOWS_RESCHEDULE_JWT_SECRETS- if not secrets:+ if not WORKFLOWS_RESCHEDULE_JWT_PURPOSE.enabled():raise RuntimeError("WORKFLOWS_RESCHEDULE_JWT_SECRET is not configured — cannot call reschedule_parked")- return jwt.encode(- {- "team_id": team_id,- "hog_flow_id": hog_flow_id,- "aud": "posthog:workflows:reschedule_parked",- "exp": datetime.now(tz=UTC) + timedelta(minutes=2),- },- secrets[0],- algorithm="HS256",- )+ return WORKFLOWS_RESCHEDULE_JWT_PURPOSE.mint({"team_id": team_id, "hog_flow_id": hog_flow_id})def reschedule_hog_flow_parked_jobs(diff --git a/posthog/session_recordings/recordings/recording_api_jwt.py b/posthog/session_recordings/recordings/recording_api_jwt.pyindex 48f7317d4b31..48176c8e7e7d 100644--- a/posthog/session_recordings/recordings/recording_api_jwt.py+++ b/posthog/session_recordings/recordings/recording_api_jwt.py@@ -5,8 +5,8 @@ from django.conf import settingsimport structlog-from posthog.jwt import PosthogJwtAudience, encode_jwt-from posthog.settings.utils import get_list+from posthog.jwt import PosthogJwtAudience+from posthog.scoped_service_jwt import ScopedServiceJwtPurposelogger = structlog.get_logger(__name__)@@ -17,18 +17,24 @@ RecordingApiOp = Literal["read", "delete"]# longer ttl explicitly.DEFAULT_RECORDING_API_TOKEN_TTL = timedelta(minutes=5)+RECORDING_API_JWT_PURPOSE = ScopedServiceJwtPurpose(+ audience=PosthogJwtAudience.RECORDING_API,+ settings_name="RECORDING_API_JWT_SECRET",+ default_ttl=DEFAULT_RECORDING_API_TOKEN_TTL,+)+def recording_api_signing_keys() -> list[str]:"""The comma-separated `new_key,old_key` set, newest first. Whitespace-trimmed (matching theNode verifier's parseJwtKeys) and empty entries dropped."""- return [key for key in get_list(settings.RECORDING_API_JWT_SECRET or "") if key]+ return RECORDING_API_JWT_PURPOSE.signing_keys()def recording_api_jwt_enabled() -> bool:"""True once a dedicated signing secret is configured. Until then callers fall back to thelegacy X-Internal-Api-Secret, so the JWT scheme can be rolled out per environment (dev, thenprod) without leaving any environment unauthenticated in the meantime."""- return bool(recording_api_signing_keys())+ return RECORDING_API_JWT_PURPOSE.enabled()def recording_api_auth_headers(team_id: int, op: RecordingApiOp) -> dict[str, str]:@@ -50,7 +56,4 @@ def recording_api_auth_headers(team_id: int, op: RecordingApiOp) -> dict[str, stdef 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])+ return RECORDING_API_JWT_PURPOSE.mint({"team_id": team_id, "op": op}, ttl=ttl)