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(temporal): Multiple secret string format handling (#62362)

Tomás Farías Santanad4aa892ab5d4
diff --git a/posthog/management/commands/rotate_temporal_schedule_encryption_key.py b/posthog/management/commands/rotate_temporal_schedule_encryption_key.py
index 570a565520a6..4a9a43c4d9a7 100644
--- a/posthog/management/commands/rotate_temporal_schedule_encryption_key.py
+++ b/posthog/management/commands/rotate_temporal_schedule_encryption_key.py
@@ -318,7 +318,7 @@ async def _as_async_iter(
async def _payloads_use_main_key(payloads) -> bool:
if not payloads:
return True
- main_key_codec = codec.EncryptionCodec(codec._prepare_key(settings.TEMPORAL_SECRET_KEY), [])
+ main_key_codec = codec.EncryptionCodec(codec._prepare_key(codec._load_as_bytes(settings.TEMPORAL_SECRET_KEY)), [])
try:
await main_key_codec.decode(payloads)
except InvalidToken:
diff --git a/posthog/temporal/common/codec.py b/posthog/temporal/common/codec.py
index 3cdc8bed8846..7b89baebd273 100644
--- a/posthog/temporal/common/codec.py
+++ b/posthog/temporal/common/codec.py
@@ -16,13 +16,40 @@ class _RequiredSettings(typing.Protocol):
DEBUG: bool
-def _prepare_key(key: str | bytes) -> bytes:
+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.
"""
- key_bytes = key.encode() if isinstance(key, str) else key
- resized_key = _resize_key(key_bytes)
+ resized_key = _resize_key(key)
encoded_key = base64.urlsafe_b64encode(resized_key)
return encoded_key
@@ -71,15 +98,15 @@ class EncryptionCodec(PayloadCodec):
ValueError: If a key with less than 32 bytes is used in non-TEST non-DEBUG
environments.
"""
- if not settings.TEST and not settings.DEBUG:
- if any(
- len(key.encode() if isinstance(key, str) else key) < 32
- for key in (settings.TEMPORAL_SECRET_KEY, *settings.TEMPORAL_FALLBACK_SECRET_KEYS)
- ):
- raise ValueError("Keys must be at least 32 bytes")
-
- main_key = _prepare_key(settings.TEMPORAL_SECRET_KEY)
- fallback_keys = map(_prepare_key, settings.TEMPORAL_FALLBACK_SECRET_KEYS)
+ should_check_length = not settings.TEST and not settings.DEBUG
+ main_key = _prepare_key(_load_as_bytes(settings.TEMPORAL_SECRET_KEY, check_length=should_check_length))
+ fallback_keys = map(
+ _prepare_key,
+ (
+ _load_as_bytes(secret, check_length=should_check_length)
+ for secret in settings.TEMPORAL_FALLBACK_SECRET_KEYS
+ ),
+ )
return cls(main_key, fallback_keys)
diff --git a/posthog/temporal/tests/test_encryption_codec.py b/posthog/temporal/tests/test_encryption_codec.py
index 5cddec90a188..92734720e446 100644
--- a/posthog/temporal/tests/test_encryption_codec.py
+++ b/posthog/temporal/tests/test_encryption_codec.py
@@ -14,7 +14,7 @@ from temporalio.api.enums.v1 import EventType
from temporalio.client import Client
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
-from posthog.temporal.common.codec import EncryptionCodec, _prepare_key, _resize_key
+from posthog.temporal.common.codec import EncryptionCodec, _load_as_bytes, _prepare_key, _resize_key
from products.batch_exports.backend.service import NoOpInputs
from products.batch_exports.backend.temporal.noop import NoOpWorkflow, noop_activity
@@ -59,6 +59,29 @@ def test_prepare_key(key: bytes, expected: bytes) -> None:
assert base64.urlsafe_b64decode(result) == _resize_key(key)
+# The presence of '?' is important as it encodes differently in standard and
+# urlsafe base64 ('/' vs '_').
+BYTES = b"decaf???" * 4 # 32 bytes
+TEST_HEX_STRING = "hex:" + (BYTES).hex()
+TEST_BASE64_URLSAFE_STRING = "base64-urlsafe:" + base64.urlsafe_b64encode(BYTES).decode()
+TEST_BASE64_STRING = "base64:" + base64.b64encode(BYTES).decode()
+
+
+ "raw,check_length,expected",
+ [
+ (b"a", False, b"a"),
+ (TEST_HEX_STRING, True, BYTES),
+ (TEST_BASE64_URLSAFE_STRING, True, BYTES),
+ (TEST_BASE64_STRING, True, BYTES),
+ ("any string", False, b"any string"),
+ ],
+)
+def test_load_as_bytes(raw: str | bytes, check_length: bool, expected: bytes) -> None:
+ result = _load_as_bytes(raw, check_length=check_length)
+ assert result == expected
+
+
def test_codec_rejects_short_keys_when_not_debug_or_test():
class EncryptionSettings:
TEMPORAL_SECRET_KEY: str | bytes = b"a"