: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
feat(hogbox-preview): give each preview box an OAuth signing key (#97774)
Shy Alter347c3d6f4128
diff --git a/tools/hogbox-preview/hogbox_preview/stack.py b/tools/hogbox-preview/hogbox_preview/stack.pyindex d142267cf62b..0dfc6026f03e 100644--- a/tools/hogbox-preview/hogbox_preview/stack.py+++ b/tools/hogbox-preview/hogbox_preview/stack.py@@ -130,6 +130,7 @@ class PostHogPreviewStack:# into the compose override so every process of THIS preview shares it, and# never shared across previews — see the module-level note above.self.secret_key = secrets.token_hex(32)+ self.oidc_private_key = "" # see _ensure_oidc_private_keyself.branch = branch# Default (None) -> the ready-made image; "" -> build-from-checkout escape# hatch; any tag -> run that published image.@@ -156,6 +157,7 @@ class PostHogPreviewStack:url = self.backend.web_urlif self.branch:self.checkout_branch(self.branch)+ self._ensure_oidc_private_key()self.write_override()if self.image:self.pull_image() # escape hatch: run a published image, skip build@@ -206,6 +208,7 @@ class PostHogPreviewStack:# rotate the key bring_up already migrated + seeded under, or anything it# wrote encrypted becomes undecryptable (and any live session drops).self._reuse_existing_secret_key()+ self._ensure_oidc_private_key()# Rewrite the override so it now carries the frontend/dist + staticfiles# mounts (write_override only adds them when a dist is set), lay the dist# in + re-run collectstatic into the mounted staticfiles/, then recreate@@ -216,18 +219,49 @@ class PostHogPreviewStack:self.wait_for_health()return self.backend.web_url+ def _override_value(self, name: str) -> str:+ """Read one environment value out of the override the box already runs+ with. Empty when the box has no override yet, or no such entry."""+ return self.backend.exec(+ f"sed -n 's/.*{name}=//p' {self.repo_dir}/{self.OVERRIDE} 2>/dev/null | head -n1",+ timeout=60,+ ).stdout.strip()+def _reuse_existing_secret_key(self) -> None:- """Adopt the SECRET_KEY the box already runs with (read from its override)- so a deferred swap doesn't rotate it. Falls back to the freshly-minted- key when the override can't be read — shouldn't happen post-bring_up, but- a random key is a safe default either way."""+ """Adopt the SECRET_KEY the box already runs with so a deferred swap+ doesn't rotate it. Falls back to the freshly-minted key when the override+ can't be read — shouldn't happen post-bring_up, but a random key is a+ safe default either way."""+ self.secret_key = self._override_value("SECRET_KEY") or self.secret_key++ def _ensure_oidc_private_key(self) -> None:+ """Give the box an RSA key for OAuth token signing, once per box.++ PostHog signs OAuth tokens with RS256 and refuses to save an OAuth+ application without OIDC_RSA_PRIVATE_KEY, so a preview cannot host an+ OAuth client (PostHog Desktop, for one) until this is set. Adopted from+ the override when the box already has one, because rotating it would+ invalidate every token the preview already issued. Left empty when the+ box cannot mint one, which serves everything except OAuth.+ """+ existing = self._override_value("OIDC_RSA_PRIVATE_KEY")+ if existing:+ self.oidc_private_key = existing+ return+ # One line, because it lives in a compose environment entry. The Django+ # setting turns the escapes back into newlines.r = self.backend.exec(- f"sed -n 's/.*SECRET_KEY=//p' {self.repo_dir}/{self.OVERRIDE} 2>/dev/null | head -n1",- timeout=60,+ r"""openssl genrsa 2048 2>/dev/null | openssl pkcs8 -topk8 -nocrypt -outform PEM """+ r"""| awk 'NF {sub(/\r/, ""); printf "%s\\n", $0}'""",+ timeout=120,)key = r.stdout.strip()- if key:- self.secret_key = key+ if not key.startswith("-----BEGIN PRIVATE KEY-----"):+ sys.stderr.write(+ "[hogbox-preview] could not mint an RSA key; OAuth applications will not save on this preview\n"+ )+ return+ self.oidc_private_key = key# --- steps (each usable standalone, mirroring bin/hobby-ci.py) -----------def start_runtime(self) -> None:@@ -303,10 +337,12 @@ class PostHogPreviewStack:lines += [f" - ./{src}:{dst}" for src, dst in mounts]lines += [" environment:",- # SITE_URL is a cosmetic placeholder (absolute links in emails etc.);- # serving is driven by JS_URL="" (relative assets) + the wildcard- # CSRF origin, so the box's own edge host serves with no per-box env.- " - SITE_URL=http://localhost:8000",+ # The OAuth metadata documents (RFC 8414, RFC 9728) build their+ # issuer and endpoints from SITE_URL, so a placeholder would send a+ # discovery client to its own machine. Serving still needs no per-box+ # env: JS_URL="" keeps assets relative, and the CSRF origin is a+ # wildcard.+ f" - SITE_URL={self.backend.web_url}"," - JS_URL=",f" - EXTRA_CSRF_TRUSTED_ORIGINS={_CSRF_TRUSTED_ORIGINS}"," - DISABLE_SECURE_SSL_REDIRECT=1",@@ -316,6 +352,7 @@ class PostHogPreviewStack:# (compose run --rm web) needs it too. Not shared across previews, so# a public preview URL can't be used to forge sessions on another.f" - SECRET_KEY={self.secret_key}",+ f" - OIDC_RSA_PRIVATE_KEY={self.oidc_private_key}",# A preview serves one user, and each worker costs a full Django import# at boot, so one worker reaches a serving /_health much sooner." - GRANIAN_WORKERS=1",diff --git a/tools/hogbox-preview/tests/test_deep_health.py b/tools/hogbox-preview/tests/test_deep_health.pyindex 5d1c91a3a13f..6643af26da88 100644--- a/tools/hogbox-preview/tests/test_deep_health.py+++ b/tools/hogbox-preview/tests/test_deep_health.py@@ -41,6 +41,7 @@ class _RecordingBackend:def __init__(self, *, probe_result: ExecResult | None = None):self.web_port = 8000+ self.web_url = "https://pen-test.boxes.example.dev"self.files: dict[str, str] = {}self.execs: list[str] = []self.long_runs: list[str] = []diff --git a/tools/hogbox-preview/tests/test_stack_admin_portal.py b/tools/hogbox-preview/tests/test_stack_admin_portal.pyindex 1519e1d9f98a..f7907cb4b517 100644--- a/tools/hogbox-preview/tests/test_stack_admin_portal.py+++ b/tools/hogbox-preview/tests/test_stack_admin_portal.py@@ -28,6 +28,7 @@ class _RecordingBackend:write_file, so that's all the stack needs from us here."""def __init__(self):+ self.web_url = "https://pen-test.boxes.example.dev"self.files: dict[str, str] = {}def write_file(self, remote_path, content) -> None:diff --git a/tools/hogbox-preview/tests/test_stack_secret_key.py b/tools/hogbox-preview/tests/test_stack_secret_key.pyindex 3d15dfb0a01c..b7da663dffdc 100644--- a/tools/hogbox-preview/tests/test_stack_secret_key.py+++ b/tools/hogbox-preview/tests/test_stack_secret_key.py@@ -1,10 +1,14 @@-"""Unit tests for the preview SECRET_KEY handling in the stack.+"""Unit tests for the environment the preview stack pins into the override.-Self-contained: no network, no live box. The stack's ``write_override`` only-touches ``backend.write_file``, so a recording fake backend is enough to assert-the key is random per preview (not a shared, publicly derivable constant) —-previews are served on PUBLIC URLs, so a shared key would let anyone forge-sessions across every preview.+Self-contained: no network, no live box. A recording fake backend is enough,+because the key paths only write the override and read it back.++``SECRET_KEY`` must be random per preview (not a shared, publicly derivable+constant) — previews are served on PUBLIC URLs, so a shared key would let anyone+forge sessions across every preview. ``OIDC_RSA_PRIVATE_KEY`` must exist at all,+because PostHog signs OAuth tokens with RS256 and refuses to save an OAuth+application without it, which kept OAuth clients (PostHog Desktop, for one) off+every preview.cd tools/hogbox-preview && python -m unittest discover tests"""@@ -30,25 +34,51 @@ except ImportError:_OLD_DERIVABLE_KEY = hashlib.sha256(b"hogbox-preview-ephemeral-tailnet-only").hexdigest()+_PEM = "-----BEGIN PRIVATE KEY-----\\nMIIB\\n-----END PRIVATE KEY-----\\n"+++class _ExecResult:+ def __init__(self, stdout: str = ""):+ self.stdout = stdout+ self.stderr = ""+ self.exit_code = 0++class _RecordingBackend:- """Duck-typed stand-in for a PreviewBackend: write_override only calls- write_file, so that's all the stack needs from us here."""+ """Duck-typed stand-in for a PreviewBackend: the key paths call write_file+ and exec, so that's all the stack needs from us here. ``stored_key`` stands+ for an override the box already carries; ``mints`` for whether openssl+ answers."""- def __init__(self):+ def __init__(self, stored_key: str = "", mints: bool = True):+ self.web_url = "https://pen-test.boxes.example.dev"self.files: dict[str, str] = {}+ self.stored_key = stored_key+ self.mints = mints+ self.commands: list[str] = []def write_file(self, remote_path, content) -> None:self.files[remote_path] = content if isinstance(content, str) else content.decode()+ def exec(self, command: str, *, timeout: int = 120) -> _ExecResult:+ self.commands.append(command)+ if "sed -n" in command:+ return _ExecResult(self.stored_key)+ return _ExecResult(_PEM if self.mints else "")-def _secret_key_from_override(stack, backend: _RecordingBackend) -> str:++def _from_override(stack, backend: _RecordingBackend, name: str) -> str:stack.write_override()override = backend.files[f"{stack.repo_dir}/{stack.OVERRIDE}"]for line in override.splitlines():stripped = line.strip().lstrip("- ")- if stripped.startswith("SECRET_KEY="):+ if stripped.startswith(f"{name}="):return stripped.split("=", 1)[1]- raise AssertionError(f"no SECRET_KEY in override:\n{override}")+ raise AssertionError(f"no {name} in override:\n{override}")+++def _secret_key_from_override(stack, backend: _RecordingBackend) -> str:+ return _from_override(stack, backend, "SECRET_KEY")@unittest.skipUnless(HAVE_SDK, "posthog-hogland SDK not installed")@@ -81,5 +111,35 @@ class PreviewSecretKeyTest(unittest.TestCase):)[email protected](HAVE_SDK, "posthog-hogland SDK not installed")+class PreviewOidcKeyTest(unittest.TestCase):+ def test_the_box_gets_a_minted_key(self):+ backend = _RecordingBackend()+ stack = PostHogPreviewStack(backend)+ stack._ensure_oidc_private_key()+ self.assertEqual(_from_override(stack, backend, "OIDC_RSA_PRIVATE_KEY"), _PEM)++ def test_an_existing_key_survives_a_rewrite(self):+ # Minting a second key would invalidate every token the preview issued.+ backend = _RecordingBackend(stored_key="-----BEGIN PRIVATE KEY-----\\nold\\n")+ stack = PostHogPreviewStack(backend)+ stack._ensure_oidc_private_key()+ self.assertEqual(stack.oidc_private_key, backend.stored_key)+ self.assertNotIn("openssl", " ".join(backend.commands))++ def test_the_site_url_is_the_preview_url(self):+ # OAuth metadata builds its issuer and endpoints from SITE_URL, so a+ # placeholder sends a discovery client to its own machine.+ backend = _RecordingBackend()+ stack = PostHogPreviewStack(backend)+ self.assertEqual(_from_override(stack, backend, "SITE_URL"), backend.web_url)++ def test_a_box_that_cannot_mint_serves_without_a_key(self):+ backend = _RecordingBackend(mints=False)+ stack = PostHogPreviewStack(backend)+ stack._ensure_oidc_private_key()+ self.assertEqual(_from_override(stack, backend, "OIDC_RSA_PRIVATE_KEY"), "")++if __name__ == "__main__":unittest.main()