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: Support for multiple keys in Temporal EncryptionCodec (#61080)

Tomás Farías Santana61277f3c2443
diff --git a/posthog/api/test/batch_exports/conftest.py b/posthog/api/test/batch_exports/conftest.py
index a0adf019b181..c71c0cee063d 100644
--- a/posthog/api/test/batch_exports/conftest.py
+++ b/posthog/api/test/batch_exports/conftest.py
@@ -2,6 +2,8 @@ import logging
import pytest
+from django.conf import settings
+
from asgiref.sync import async_to_sync
from temporalio.client import (
Client as TemporalClient,
@@ -13,6 +15,7 @@ from temporalio.service import RPCError
from posthog.api.test.batch_exports.fixtures import create_organization, create_team, create_user
from posthog.api.test.batch_exports.operations import start_test_worker
from posthog.temporal.common.client import sync_connect
+from posthog.temporal.common.codec import EncryptionCodec
from products.batch_exports.backend.models.batch_export import BATCH_EXPORT_INTERVAL_TO_START_JITTER, BatchExport
@@ -106,3 +109,9 @@ def assert_is_weekly_schedule(schedule: ScheduleDescription, expected_day: int,
assert calendars[0].day_of_week == (ScheduleRange(start=expected_day, end=expected_day),)
assert calendars[0].hour == (ScheduleRange(start=expected_hour, end=expected_hour),)
assert schedule.schedule.spec.jitter == BATCH_EXPORT_INTERVAL_TO_START_JITTER["week"]
+
+
[email protected](scope="module")
+def encryption_codec() -> EncryptionCodec:
+ codec = EncryptionCodec.from_settings(settings)
+ return codec
diff --git a/posthog/api/test/batch_exports/test_create.py b/posthog/api/test/batch_exports/test_create.py
index eff971f290a6..83e41d6d0043 100644
--- a/posthog/api/test/batch_exports/test_create.py
+++ b/posthog/api/test/batch_exports/test_create.py
@@ -6,7 +6,6 @@ from zoneinfo import ZoneInfo
import pytest
from unittest import mock
-from django.conf import settings
from django.test import override_settings
from django.test.client import Client as HttpClient
@@ -22,7 +21,6 @@ from posthog.api.test.batch_exports.fixtures import create_organization
from posthog.api.test.batch_exports.operations import create_batch_export
from posthog.api.test.test_team import create_team
from posthog.api.test.test_user import create_user
-from posthog.temporal.common.codec import EncryptionCodec
from products.batch_exports.backend.models.batch_export import BatchExport
@@ -36,7 +34,9 @@ pytestmark = [
# tests live alongside in `test_create_<destination>.py`.
-def test_create_batch_export_with_interval_schedule(client: HttpClient, temporal, organization, team, user):
+def test_create_batch_export_with_interval_schedule(
+ client: HttpClient, temporal, encryption_codec, organization, team, user
+):
"""Test creating a BatchExport.
When creating a BatchExport, we should create a corresponding Schedule in
@@ -92,14 +92,13 @@ def test_create_batch_export_with_interval_schedule(client: HttpClient, temporal
}
# validate the underlying temporal schedule has been created
- codec = EncryptionCodec(settings=settings)
schedule = describe_schedule(temporal, data["id"])
batch_export = BatchExport.objects.get(id=data["id"])
assert schedule.schedule.spec.intervals[0].every == batch_export.interval_time_delta
assert schedule.schedule.spec.jitter == batch_export.jitter
- decoded_payload = async_to_sync(codec.decode)(schedule.schedule.action.args)
+ decoded_payload = async_to_sync(encryption_codec.decode)(schedule.schedule.action.args)
args = json.loads(decoded_payload[0].data)
# Common inputs
@@ -415,7 +414,9 @@ FROM events
"""
-def test_create_batch_export_with_custom_schema(client: HttpClient, temporal, organization, team, user):
+def test_create_batch_export_with_custom_schema(
+ client: HttpClient, temporal, encryption_codec, organization, team, user
+):
"""Test creating a BatchExport with a custom schema expressed as a HogQL Query.
When creating a BatchExport, we should create a corresponding Schedule in
@@ -456,12 +457,11 @@ def test_create_batch_export_with_custom_schema(client: HttpClient, temporal, or
expected_hogql_query = " ".join(TEST_HOGQL_QUERY.split()) # Don't care about whitespace
assert data["schema"]["hogql_query"] == expected_hogql_query
- codec = EncryptionCodec(settings=settings)
schedule = describe_schedule(temporal, data["id"])
batch_export = BatchExport.objects.get(id=data["id"])
- decoded_payload = async_to_sync(codec.decode)(schedule.schedule.action.args)
+ decoded_payload = async_to_sync(encryption_codec.decode)(schedule.schedule.action.args)
args = json.loads(decoded_payload[0].data)
expected_fields = [
diff --git a/posthog/api/test/batch_exports/test_update.py b/posthog/api/test/batch_exports/test_update.py
index 8495c1053b0a..e79258088c1d 100644
--- a/posthog/api/test/batch_exports/test_update.py
+++ b/posthog/api/test/batch_exports/test_update.py
@@ -4,7 +4,6 @@ import datetime as dt
import pytest
-from django.conf import settings
from django.test.client import Client as HttpClient
from asgiref.sync import async_to_sync
@@ -22,7 +21,6 @@ from posthog.api.test.batch_exports.operations import (
put_batch_export,
)
from posthog.models.integration import Integration
-from posthog.temporal.common.codec import EncryptionCodec
from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination
from products.batch_exports.backend.service import sync_batch_export
@@ -50,7 +48,7 @@ def bigquery_integration(team, user):
)
-def test_can_put_config(client: HttpClient, temporal, organization, team, user):
+def test_can_put_config(client: HttpClient, temporal, encryption_codec, organization, team, user):
destination_data: dict[str, t.Any] = {
"type": "S3",
"config": {
@@ -111,21 +109,20 @@ def test_can_put_config(client: HttpClient, temporal, organization, team, user):
assert batch_export["offset_hour"] == 0
# validate the underlying temporal schedule has been updated
- codec = EncryptionCodec(settings=settings)
new_schedule = describe_schedule(temporal, batch_export["id"])
assert_is_daily_schedule(new_schedule, 0)
assert new_schedule.schedule.spec.start_at == dt.datetime(2022, 7, 19, 0, 0, 0, tzinfo=dt.UTC)
assert new_schedule.schedule.spec.end_at == dt.datetime(2023, 7, 20, 0, 0, 0, tzinfo=dt.UTC)
assert new_schedule.schedule.spec.time_zone_name == "UTC" # UTC is the default timezone if not provided
- decoded_payload = async_to_sync(codec.decode)(new_schedule.schedule.action.args)
+ decoded_payload = async_to_sync(encryption_codec.decode)(new_schedule.schedule.action.args)
args = json.loads(decoded_payload[0].data)
assert args["bucket_name"] == "my-new-production-s3-bucket"
assert args["aws_secret_access_key"] == "new-secret"
@pytest.mark.parametrize("interval", ["hour", "day"])
-def test_can_patch_config(client: HttpClient, interval, temporal, organization, team, user):
+def test_can_patch_config(client: HttpClient, interval, temporal, encryption_codec, organization, team, user):
timezone = "Europe/Berlin"
# use offset of 1 hour for daily exports and None for hourly exports (these don't support offsets)
offset_hour = None if interval == "hour" else 1
@@ -195,7 +192,6 @@ def test_can_patch_config(client: HttpClient, interval, temporal, organization,
assert batch_export_data["destination"]["config"]["bucket_name"] == "my-new-production-s3-bucket"
# validate the underlying temporal schedule has been updated
- codec = EncryptionCodec(settings=settings)
new_schedule = describe_schedule(temporal, batch_export["id"])
if interval == "day":
expected_hour = offset_hour if offset_hour is not None else 0
@@ -204,7 +200,7 @@ def test_can_patch_config(client: HttpClient, interval, temporal, organization,
else:
assert new_schedule.schedule.spec.intervals[0].every == dt.timedelta(hours=1)
assert old_schedule.schedule.spec.intervals[0].every == new_schedule.schedule.spec.intervals[0].every
- decoded_payload = async_to_sync(codec.decode)(new_schedule.schedule.action.args)
+ decoded_payload = async_to_sync(encryption_codec.decode)(new_schedule.schedule.action.args)
args = json.loads(decoded_payload[0].data)
assert args["bucket_name"] == "my-new-production-s3-bucket"
assert new_schedule.schedule.spec.time_zone_name == timezone
@@ -480,7 +476,9 @@ def test_can_patch_schedule_configuration(
@pytest.mark.django_db
@pytest.mark.parametrize("interval", ["hour", "day"])
-def test_can_patch_config_with_invalid_old_values(client: HttpClient, interval, temporal, organization, team, user):
+def test_can_patch_config_with_invalid_old_values(
+ client: HttpClient, encryption_codec, interval, temporal, organization, team, user
+):
destination_data = {
"type": "S3",
"config": {
@@ -536,9 +534,8 @@ def test_can_patch_config_with_invalid_old_values(client: HttpClient, interval,
assert batch_export_data["destination"]["config"]["bucket_name"] == "my-new-production-s3-bucket"
# validate the underlying temporal schedule has been updated
- codec = EncryptionCodec(settings=settings)
new_schedule = describe_schedule(temporal, batch_export_data["id"])
- decoded_payload = async_to_sync(codec.decode)(new_schedule.schedule.action.args)
+ decoded_payload = async_to_sync(encryption_codec.decode)(new_schedule.schedule.action.args)
args = json.loads(decoded_payload[0].data)
assert args["bucket_name"] == "my-new-production-s3-bucket"
assert args.get("invalid_key", None) is None
@@ -646,7 +643,7 @@ def test_put_rejects_destination_type_change(
assert refreshed["destination"]["config"]["bucket_name"] == "my-production-s3-bucket"
-def test_can_patch_hogql_query(client: HttpClient, temporal, organization, team, user):
+def test_can_patch_hogql_query(client: HttpClient, temporal, encryption_codec, organization, team, user):
"""Test we can patch a schema with a HogQL query."""
destination_data = {
"type": "S3",
@@ -705,10 +702,9 @@ def test_can_patch_hogql_query(client: HttpClient, temporal, organization, team,
}
# validate the underlying temporal schedule has been updated
- codec = EncryptionCodec(settings=settings)
new_schedule = describe_schedule(temporal, batch_export["id"])
assert old_schedule.schedule.spec.intervals[0].every == new_schedule.schedule.spec.intervals[0].every
- decoded_payload = async_to_sync(codec.decode)(new_schedule.schedule.action.args)
+ decoded_payload = async_to_sync(encryption_codec.decode)(new_schedule.schedule.action.args)
args = json.loads(decoded_payload[0].data)
assert args["bucket_name"] == "my-production-s3-bucket"
assert args["interval"] == "hour"
@@ -802,6 +798,7 @@ def databricks_integration_2(team, user):
def test_can_update_batch_export_with_integration(
client: HttpClient,
temporal,
+ encryption_codec,
organization,
team,
user,
@@ -863,10 +860,9 @@ def test_can_update_batch_export_with_integration(
}
# validate the underlying temporal schedule has been updated
- codec = EncryptionCodec(settings=settings)
new_schedule = describe_schedule(temporal, batch_export["id"])
assert old_schedule.schedule.spec.intervals[0].every == new_schedule.schedule.spec.intervals[0].every
- decoded_payload = async_to_sync(codec.decode)(new_schedule.schedule.action.args)
+ decoded_payload = async_to_sync(encryption_codec.decode)(new_schedule.schedule.action.args)
args = json.loads(decoded_payload[0].data)
assert args["integration_id"] == databricks_integration_2.id
diff --git a/posthog/helpers/encrypted_flag_payloads.py b/posthog/helpers/encrypted_flag_payloads.py
index aaedfbc424bc..4603bfe3ebb1 100644
--- a/posthog/helpers/encrypted_flag_payloads.py
+++ b/posthog/helpers/encrypted_flag_payloads.py
@@ -21,7 +21,7 @@ def get_decrypted_flag_payloads(encrypted_payloads: dict, should_decrypt: bool)
def get_decrypted_flag_payload(encrypted_payload: str | object, should_decrypt: bool) -> str:
- codec = EncryptionCodec(settings)
+ codec = EncryptionCodec.from_settings(settings)
return (
codec.decrypt(str(encrypted_payload).encode("utf-8")).decode("utf-8")
if should_decrypt
@@ -41,7 +41,7 @@ def encrypt_flag_payloads(validated_data: dict):
payloads = validated_data["filters"]["payloads"]
- codec = EncryptionCodec(settings)
+ codec = EncryptionCodec.from_settings(settings)
for key, value in payloads.items():
try:
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 9be09e8ff107..a68cf8c5d2b3 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -1,5 +1,6 @@
import os
+from posthog.settings.access import SECRET_KEY
from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUG
from posthog.settings.utils import get_from_env, get_list, str_to_bool
@@ -12,6 +13,11 @@ TEMPORAL_CLIENT_CERT: str | None = os.getenv("TEMPORAL_CLIENT_CERT", None)
TEMPORAL_CLIENT_KEY: str | None = os.getenv("TEMPORAL_CLIENT_KEY", None)
TEMPORAL_WORKFLOW_MAX_ATTEMPTS: str = os.getenv("TEMPORAL_WORKFLOW_MAX_ATTEMPTS", "3")
TEMPORAL_USE_PYDANTIC_CONVERTER: bool = get_from_env("TEMPORAL_USE_PYDANTIC_CONVERTER", False, type_cast=str_to_bool)
+
+TEMPORAL_SECRET_KEY: str = os.getenv("TEMPORAL_SECRET_KEY", SECRET_KEY)
+TEMPORAL_FALLBACK_KEYS: list[str] = get_list(os.getenv("TEMPORAL_FALLBACK_KEYS", "")) or [SECRET_KEY]
+
+
GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS: int | None = get_from_env(
"GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS", None, optional=True, type_cast=int
)
diff --git a/posthog/temporal/codec_server.py b/posthog/temporal/codec_server.py
index f251de1fe2d5..deb6765b1d7b 100644
--- a/posthog/temporal/codec_server.py
+++ b/posthog/temporal/codec_server.py
@@ -81,7 +81,7 @@ def decode_payloads(request):
try:
payloads = json_format.Parse(request.body, Payloads())
- codec = EncryptionCodec(settings)
+ codec = EncryptionCodec.from_settings(settings)
decoded_list = async_to_sync(codec.decode)(payloads.payloads)
diff --git a/posthog/temporal/common/client.py b/posthog/temporal/common/client.py
index a960be802b57..c5f9422bf3e0 100644
--- a/posthog/temporal/common/client.py
+++ b/posthog/temporal/common/client.py
@@ -39,7 +39,7 @@ async def connect(
if settings is not None:
data_converter = dataclasses.replace(
data_converter,
- payload_codec=EncryptionCodec(settings=settings),
+ payload_codec=EncryptionCodec.from_settings(settings=settings),
)
client = await Client.connect(
diff --git a/posthog/temporal/common/codec.py b/posthog/temporal/common/codec.py
index 42e775a24ba3..857c8727f5c8 100644
--- a/posthog/temporal/common/codec.py
+++ b/posthog/temporal/common/codec.py
@@ -1,28 +1,89 @@
import base64
-from collections.abc import Iterable
+import typing
+import collections.abc
-from cryptography.fernet import Fernet
+from cryptography.fernet import Fernet, MultiFernet
from temporalio.api.common.v1 import Payload
from temporalio.converter import PayloadCodec
+class _RequiredSettings(typing.Protocol):
+ """Protocol for required settings."""
+
+ TEMPORAL_SECRET_KEY: str | bytes
+ TEMPORAL_FALLBACK_KEYS: collections.abc.Iterable[str | bytes]
+ TEST: bool
+ DEBUG: bool
+
+
+def _prepare_key(key: str | 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)
+ 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]
+
+
class EncryptionCodec(PayloadCodec):
- """A PayloadCodec that encrypts/decrypts all Payloads.
+ """Handles encryption and decryption of all Temporal payloads.
+
+ Pass an instance of this when initializing a Temporal client to ensure all inputs
+ and outputs going to and from the Temporal server are encrypted.
+
+ All encryption keys must be URL-safe, base64 encoded, 32-byte keys.
Args:
- settings: Django settings to obtain the SECRET_KEY to use for encryption.
+ key: The preferred encryption key.
+ fallback_keys: Any number of additional keys to be used when decrypting with
+ key fails. This allows rotating keys by moving the current key to the
+ fallbacks temporarily.
"""
- def __init__(self, settings) -> None:
+ def __init__(self, key: bytes, fallback_keys: collections.abc.Iterable[bytes]) -> None:
super().__init__()
- # Fernet requires a URL safe, base64 encoded, 32 byte key. So, we pad the SECRET_KEY
- # if it's not long enough (like in TEST environments) or we truncate it if it's too long.
- padded_key = b"\0" * max(32 - len(settings.SECRET_KEY), 0) + settings.SECRET_KEY.encode()
- encoded_key = base64.urlsafe_b64encode(padded_key[:32])
- self.fernet = Fernet(encoded_key)
+ main = Fernet(key)
+ fallbacks = map(Fernet, fallback_keys)
+ self.fernet = MultiFernet([main, *fallbacks])
+
+ @classmethod
+ def from_settings(cls, settings: _RequiredSettings) -> typing.Self:
+ """Initialize an EncryptionCodec from any settings-like object.
+
+ Args:
+ settings: Any settings-like object containing required encryption keys,
+ like a Django settings module. Keys must be at least 32 bytes long, and
+ will be padded to 32 bytes in TEST or DEBUG environments.
+
+ Raises:
+ 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_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_KEYS)
+
+ return cls(main_key, fallback_keys)
- async def encode(self, payloads: Iterable[Payload]) -> list[Payload]:
+ async def encode(self, payloads: collections.abc.Iterable[Payload]) -> list[Payload]:
"""Encrypt all payloads during encoding."""
return [
Payload(
@@ -34,7 +95,7 @@ class EncryptionCodec(PayloadCodec):
for p in payloads
]
- async def decode(self, payloads: Iterable[Payload]) -> list[Payload]:
+ async def decode(self, payloads: collections.abc.Iterable[Payload]) -> list[Payload]:
"""Decode all payloads decrypting those with expected encoding."""
ret: list[Payload] = []
for p in payloads:
diff --git a/posthog/temporal/tests/test_codec_server.py b/posthog/temporal/tests/test_codec_server.py
index 9b04264980a3..7bf849d9a30d 100644
--- a/posthog/temporal/tests/test_codec_server.py
+++ b/posthog/temporal/tests/test_codec_server.py
@@ -14,7 +14,7 @@ from posthog.temporal.common.codec import EncryptionCodec
class CodecServerTestCase(TestCase):
def setUp(self):
self.client = Client()
- self.codec = EncryptionCodec(settings)
+ self.codec = EncryptionCodec.from_settings(settings)
# Set up test auth token
self.test_token = "test-codec-auth-token"
diff --git a/posthog/temporal/tests/test_encryption_codec.py b/posthog/temporal/tests/test_encryption_codec.py
index 58c9daf85ff1..39f4df760ecd 100644
--- a/posthog/temporal/tests/test_encryption_codec.py
+++ b/posthog/temporal/tests/test_encryption_codec.py
@@ -1,22 +1,141 @@
import json
import uuid
+import base64
import dataclasses
+import collections.abc
import pytest
from django.conf import settings
import temporalio.converter
+from cryptography.fernet import InvalidToken
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
+from posthog.temporal.common.codec import EncryptionCodec, _prepare_key, _resize_key
from products.batch_exports.backend.service import NoOpInputs
from products.batch_exports.backend.temporal.noop import NoOpWorkflow, noop_activity
+ "key,size,expected",
+ [
+ (b"aaa", 32, b"\0" * 29 + b"aaa"),
+ (b"aaa", 1, b"a"),
+ ],
+)
+def test_resize_key_to_size(key: bytes, size: int, expected: bytes) -> None:
+ result = _resize_key(key, size=size)
+ assert len(result) == size
+ assert result == expected
+
+
+ "key,expected",
+ [
+ (b"aaa", b"\0" * 29 + b"aaa"),
+ (b"a" * 32, b"a" * 32),
+ ],
+)
+def test_resize_key(key: bytes, expected: bytes) -> None:
+ result = _resize_key(key)
+ assert len(result) == 32
+ assert result == expected
+
+
+ "key,expected",
+ [
+ (b"aaa", b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABhYWE="),
+ (b"a+" * 16, b"YSthK2ErYSthK2ErYSthK2ErYSthK2ErYSthK2ErYSs="),
+ ],
+)
+def test_prepare_key(key: bytes, expected: bytes) -> None:
+ result = _prepare_key(key)
+ assert result == expected
+ assert base64.urlsafe_b64decode(result) == _resize_key(key)
+
+
+def test_codec_rejects_short_keys_when_not_debug_or_test():
+ class EncryptionSettings:
+ TEMPORAL_SECRET_KEY: str | bytes = b"a"
+ TEMPORAL_FALLBACK_KEYS: collections.abc.Iterable[str | bytes] = []
+ TEST: bool = False
+ DEBUG: bool = False
+
+ settings = EncryptionSettings()
+
+ with pytest.raises(ValueError):
+ _ = EncryptionCodec.from_settings(settings)
+
+ settings.TEMPORAL_FALLBACK_KEYS = [b"b"]
+ settings.TEMPORAL_SECRET_KEY = b"a" * 32
+
+ with pytest.raises(ValueError):
+ _ = EncryptionCodec.from_settings(settings)
+
+ settings.DEBUG = True
+ _ = EncryptionCodec.from_settings(settings)
+
+ settings.DEBUG = False
+ settings.TEST = True
+ _ = EncryptionCodec.from_settings(settings)
+
+
+class TestEncryptionSettings:
+ TEMPORAL_SECRET_KEY: str | bytes = b"a" * 32
+ TEMPORAL_FALLBACK_KEYS: collections.abc.Iterable[str | bytes] = [b"b" * 32, b"c" * 32]
+ TEST: bool = False
+ DEBUG: bool = False
+
+
+def codec() -> EncryptionCodec:
+ codec = EncryptionCodec.from_settings(TestEncryptionSettings())
+ return codec
+
+
+def test_encrypt_decrypt_round_trip(codec: EncryptionCodec):
+ payload = b"very-secret"
+
+ encrypted = codec.encrypt(payload)
+ decrypted = codec.decrypt(encrypted)
+
+ assert payload == decrypted
+
+
+def test_encrypt_uses_main_key(codec: EncryptionCodec):
+ """Assert codec encrypts using main key."""
+ payload = b"very-secret"
+
+ token = codec.encrypt(payload)
+
+ main = codec.fernet._fernets[0]
+
+ assert main.decrypt(token) == payload
+
+ for fallback in codec.fernet._fernets[1:]:
+ with pytest.raises(InvalidToken):
+ fallback.decrypt(token)
+
+
+def test_decrypt_fallsback_to_fallback_keys(codec: EncryptionCodec):
+ """Assert codec can decrypt payloads encrypted with fallback keys."""
+ payload = b"very-secret"
+
+ tokens = []
+ for fallback in codec.fernet._fernets[1:]:
+ tokens.append(fallback.encrypt(payload))
+
+ assert len(tokens) > 0
+
+ for token in tokens:
+ assert codec.decrypt(token) == payload
+
+
def get_history_event_payloads(event):
"""Return a history event's payloads if it has any.
@@ -38,7 +157,7 @@ def get_history_event_payloads(event):
@pytest.mark.asyncio
async def test_payloads_are_encrypted():
"""Test the payloads of a Workflow are encrypted when running with EncryptionCodec."""
- codec = EncryptionCodec(settings=settings)
+ codec = EncryptionCodec.from_settings(settings=settings)
client = await Client.connect(
f"{settings.TEMPORAL_HOST}:{settings.TEMPORAL_PORT}",
namespace=settings.TEMPORAL_NAMESPACE,
diff --git a/products/data_modeling/backend/management/commands/delete_orphaned_saved_query_schedules.py b/products/data_modeling/backend/management/commands/delete_orphaned_saved_query_schedules.py
index bb672c2efa7a..08161d101a72 100644
--- a/products/data_modeling/backend/management/commands/delete_orphaned_saved_query_schedules.py
+++ b/products/data_modeling/backend/management/commands/delete_orphaned_saved_query_schedules.py
@@ -188,7 +188,7 @@ class Command(BaseCommand):
from posthog.temporal.common.codec import EncryptionCodec
- codec = EncryptionCodec(settings=settings)
+ codec = EncryptionCodec.from_settings(settings=settings)
payload_converter = temporalio.converter.default().payload_converter
semaphore = asyncio.Semaphore(concurrency)
results: dict[str, int | None] = {}