: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(dev): Update Temporal codec thingy (#63553)
Michael Matloka9a7aa1e7c2bd
diff --git a/bin/temporal-codec-server b/bin/temporal-codec-serverindex 1bec375a9647..54a9579d5ffe 100755--- a/bin/temporal-codec-server+++ b/bin/temporal-codec-server@@ -12,7 +12,7 @@Runs a local HTTP server implementing the Temporal Remote Codec protocol,allowing the Temporal Web UI to decode encrypted payloads in-browser.-Fetches the Django SECRET_KEY from AWS Secrets Manager (via SSO), derives+Fetches TEMPORAL_SECRET_KEY from AWS Secrets Manager (via SSO), derivesthe Fernet key, and keeps it in memory for the lifetime of the process.Usage:@@ -22,15 +22,15 @@ Usage:Then in the Temporal UI, set the codec server endpoint to http://localhost:8089"""-import base64+import sysimport json+import base64import subprocess-import sysfrom http.server import BaseHTTPRequestHandler, HTTPServer-from typing import Any+from typing import Any, Protocolfrom urllib.parse import urlparse-from cryptography.fernet import Fernet+from cryptography.fernet import Fernet, MultiFernetfrom temporalio.api.common.v1 import PayloadREGIONS = {@@ -49,7 +49,11 @@ ALLOWED_ORIGINS = {}-def get_fernet(region: str) -> Fernet:+class _HasDecrypt(Protocol):+ def decrypt(self, data: bytes) -> bytes: ...+++def get_fernet(region: str) -> MultiFernet:import boto3from botocore.exceptions import ClientError, NoCredentialsError, TokenRetrievalError@@ -74,15 +78,40 @@ def get_fernet(region: str) -> Fernet:response = client.get_secret_value(SecretId=AWS_SECRET_NAME)secret_data = json.loads(response["SecretString"])- if "SECRET_KEY" not in secret_data:- print(f"SECRET_KEY not found in {AWS_SECRET_NAME}. Available keys: {sorted(secret_data.keys())}", file=sys.stderr)+ if "TEMPORAL_SECRET_KEY" not in secret_data:+ print(+ f"TEMPORAL_SECRET_KEY not found in {AWS_SECRET_NAME}. Available keys: {sorted(secret_data.keys())}",+ file=sys.stderr,+ )sys.exit(1)- secret_key = secret_data["SECRET_KEY"]- padded = b"\0" * max(32 - len(secret_key), 0) + secret_key.encode()- return Fernet(base64.urlsafe_b64encode(padded[:32]))+ secret_key = Fernet(_prepare_key(_load_as_bytes(secret_data["TEMPORAL_SECRET_KEY"])))++ fallback_keys = (+ Fernet(_prepare_key(_load_as_bytes(secret)))+ for secret in _split_fallback_keys(secret_data.get("TEMPORAL_FALLBACK_SECRET_KEYS", []))+ if secret.strip() # Filter out empty/whitespace strings+ )+++ return MultiFernet([secret_key, *fallback_keys])-def decode_payload(payload: dict, fernet: Fernet) -> dict:++def _split_fallback_keys(raw: str | list[str]) -> list[str]:+ """Normalize the fallback keys to a list.++ The secret stores TEMPORAL_FALLBACK_SECRET_KEYS as a comma-separated string, which+ Django parses with get_list (settings/temporal.py). Iterating the raw string would+ yield single characters, so mirror get_list here; tolerate an already-parsed list too.+ """+ if isinstance(raw, list):+ return raw+ if not raw:+ return []+ return [item.strip() for item in raw.split(",")]+++def decode_payload(payload: dict, fernet: _HasDecrypt) -> dict:"""Decode a single Temporal payload if it's Fernet-encrypted."""metadata = payload.get("metadata", {})if metadata.get("encoding") != ENCRYPTED_ENCODING:@@ -104,7 +133,7 @@ def decode_payload(payload: dict, fernet: Fernet) -> dict:class CodecHandler(BaseHTTPRequestHandler):- fernet: Fernet+ fernet: _HasDecryptdef do_OPTIONS(self) -> None:if not self._is_origin_allowed():@@ -175,13 +204,66 @@ class CodecHandler(BaseHTTPRequestHandler):sys.stderr.write(f"[codec-server] {args[0]}\n")+# region Lifted from posthog.temporal.common.codec+++def _load_as_bytes(raw: str | bytes, /, check_length: bool = True) -> bytes:+ if isinstance(raw, bytes):+ loaded = raw++ else:+ prefix, sep, secret = raw.partition(":")++ if sep and prefix == "hex":+ loaded = bytes.fromhex(secret)++ elif sep and prefix == "base64-urlsafe":+ loaded = base64.urlsafe_b64decode(secret)++ elif sep and prefix == "base64":+ loaded = base64.b64decode(secret, validate=True)++ else:+ # Legacy format, kept for backwards compatibility+ # TODO: Remove this branch & raise after rotating secrets+ loaded = raw.encode()++ # TODO: Also, make the check exact after removing legacy format+ if check_length and len(loaded) < 32:+ raise ValueError(f"Expected at least 32 bytes, got '{len(loaded)}'")++ return loaded+++def _prepare_key(key: bytes) -> bytes:+ """Prepare an encryption key by padding or truncating it, and encoding it.++ We require a URL-safe, base64 encoded, 32 byte key.+ """+ resized_key = _resize_key(key)+ encoded_key = base64.urlsafe_b64encode(resized_key)+ return encoded_key+++def _resize_key(key: bytes, size: int = 32) -> bytes:+ """Resize key to size bytes.++ Adds padding if key is too short, otherwise truncates to first 32 bytes.+ """+ padding = b"\0" * max(size - len(key), 0)+ return (padding + key)[:size]+++# endregion++def main() -> None:if len(sys.argv) < 2 or sys.argv[1] not in REGIONS:print(f"Usage: temporal-codec-server <{'|'.join(REGIONS)}>", file=sys.stderr)sys.exit(1)region = sys.argv[1]- print(f"Fetching SECRET_KEY from AWS Secrets Manager ({region})...")+ print(f"Fetching TEMPORAL_SECRET_KEY from AWS Secrets Manager ({region})...")fernet = get_fernet(region)CodecHandler.fernet = fernet