: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: Django command to rotate Temporal schedule encryption key (#61857)
Tomás Farías Santanacebaa7ed6144
diff --git a/posthog/management/commands/rotate_temporal_schedule_encryption_key.py b/posthog/management/commands/rotate_temporal_schedule_encryption_key.pynew file mode 100644index 000000000000..570a565520a6--- /dev/null+++ b/posthog/management/commands/rotate_temporal_schedule_encryption_key.py@@ -0,0 +1,326 @@+import csv+import sys+import typing+import asyncio+import datetime as dt+import collections.abc+from argparse import ArgumentParser++from django.conf import settings+from django.core.management.base import BaseCommand++import structlog+from cryptography.fernet import InvalidToken+from rich.console import Console+from rich.table import Table+from temporalio.client import (+ ScheduleActionStartWorkflow,+ ScheduleListActionStartWorkflow,+ ScheduleUpdate,+ ScheduleUpdateInput,+)++from posthog.temporal.common import client, codec++LOGGER = structlog.get_logger(__name__)++ScheduleID = str+++class FailedSchedule(typing.TypedDict):+ id: ScheduleID+ error: str+++class SkippedSchedule(typing.TypedDict):+ id: ScheduleID+ reason: str+++class Results(typing.NamedTuple):+ """Results of a command execution."""++ failed: list[FailedSchedule]+ success: list[ScheduleID]+ skipped: list[SkippedSchedule]+++def print_results(results: Results) -> None:+ """Print results to stdout as a rich table."""+ table = Table(title="Schedule encryption key rotation")++ table.add_column("Schedule ID")+ table.add_column("Status")+ table.add_column("Details")++ for schedule_id in results.success:+ table.add_row(schedule_id, "Success", "")++ for skipped in results.skipped:+ table.add_row(+ skipped["id"],+ "Skipped",+ skipped["reason"],+ )++ for failed in results.failed:+ table.add_row(+ failed["id"],+ "Failed",+ failed["error"],+ )++ console = Console()+ with console.pager(styles=True):+ console.print(table)+++def write_csv_results(results: Results) -> None:+ """Write results to stdout as a CSV."""+ writer = csv.writer(sys.stdout)++ writer.writerow(["schedule_id", "status", "details"])++ for schedule_id in results.success:+ writer.writerow([schedule_id, "success", ""])++ for skipped in results.skipped:+ writer.writerow(+ [+ skipped["id"],+ "skipped",+ skipped["reason"],+ ]+ )++ for failed in results.failed:+ writer.writerow(+ [+ failed["id"],+ "failed",+ failed["error"],+ ]+ )+++class Command(BaseCommand):+ help = "Rotate the encryption key used in one or more Temporal schedules."++ def create_parser(self, prog_name: str, subcommand: str, **kwargs: typing.Any):+ parser = super().create_parser(prog_name, subcommand, **kwargs)+ parser.description = """+Rotate the encryption key used in one or more Temporal schedules.++The command can rotate the encryption key for all schedules, for specific schedules+specified by their ID, or for schedules filtered by the workflow they invoke.++In order to rotate an encryption key, the Django settings must configure a+'TEMPORAL_SECRET_KEY' and one or more 'TEMPORAL_FALLBACK_SECRET_KEYS'. The encryption+key will be rotated from any of the fallback keys to the `TEMPORAL_SECRET_KEY`.++Temporal doesn't actually have a 'rotate' operation, so what this command does is read+a schedule's inputs, implicitly decrypting them with a fallback key, and updates the+schedule with the same inputs, which implicitly encrypts them with+`TEMPORAL_SECRET_KEY`.+"""++ parser.epilog = """+Examples:++ manage.py rotate_temporal_schedule_encryption_key id one-schedule-id another-schedule-id+ manage.py rotate_temporal_schedule_encryption_key workflow bigquery-export snowflake-export+ manage.py rotate_temporal_schedule_encryption_key all+"""+ return parser++ def add_arguments(self, parser: ArgumentParser) -> None:+ parser.add_argument("--format", choices=("table", "csv"), default="table", help="Output format")+ parser.add_argument("--dry-run", action="store_true", help="Do a dry-run, nothing will be updated")++ subparsers = parser.add_subparsers(dest="subcommand", required=True)++ by_ids = subparsers.add_parser("id")+ by_ids.add_argument("ids", nargs="+", help="One or more schedule IDs whose encryption key to rotate")++ by_workflows = subparsers.add_parser("workflow")+ by_workflows.add_argument(+ "workflows",+ nargs="+",+ help="Rotate the encryption key of all schedules matching one or more workflow types",+ )++ _ = subparsers.add_parser("all")++ def handle(self, **options: typing.Any) -> None:+ dry_run = options["dry_run"]++ LOGGER.info("Starting", dry_run=dry_run)++ match options["subcommand"]:+ case "all":+ results = asyncio.run(self.run_all(dry_run=dry_run))+ case "id":+ results = asyncio.run(self.run_by_ids(options["ids"], dry_run=dry_run))+ case "workflow":+ results = asyncio.run(self.run_by_workflow(options["workflows"], dry_run=dry_run))+ case invalid:+ raise ValueError(f"Invalid subcommand '{invalid}'")++ match options["format"]:+ case "table":+ print_results(results)+ case "csv":+ write_csv_results(results)+ case invalid:+ raise ValueError(f"Invalid format '{invalid}'")++ async def run_all(self, /, dry_run: bool) -> Results:+ """Rotate encryption key for all schedules."""+ temporal = await client.async_connect()++ async def iter_ids() -> collections.abc.AsyncIterator[ScheduleID]:+ async for list_schedule in await temporal.list_schedules():+ yield list_schedule.id++ results = await self.run_by_ids(iter_ids(), dry_run=dry_run)++ return results++ async def run_by_workflow(self, workflows_iter: collections.abc.Iterable[str], /, dry_run: bool) -> Results:+ """Rotate encryption key for schedules that trigger specific workflows."""+ temporal = await client.async_connect()+ workflows = set(workflows_iter)++ async def iter_ids() -> collections.abc.AsyncIterator[ScheduleID]:+ async for list_schedule in await temporal.list_schedules():+ action = list_schedule.schedule.action if list_schedule.schedule else None+ if isinstance(action, ScheduleListActionStartWorkflow) and action.workflow in workflows:+ yield list_schedule.id++ results = await self.run_by_ids(iter_ids(), dry_run=dry_run)++ return results++ async def run_by_ids(+ self, ids: collections.abc.Iterable[ScheduleID] | collections.abc.AsyncIterable[ScheduleID], /, dry_run: bool+ ) -> Results:+ """Rotate encryption key for schedules with given IDs.++ In order to rotate an encryption key for a schedule we first read its current+ arguments. This implicitly decrypts the arguments, which means that we must+ still support the old encryption key as a fallback. Then, we update the+ schedule with the same arguments, which encrypts them with the main key,+ completing the rotation.+ """+ temporal = await client.async_connect()+ failed: list[FailedSchedule] = []+ success: list[ScheduleID] = []+ skipped: list[SkippedSchedule] = []++ async def do_update(input: ScheduleUpdateInput) -> ScheduleUpdate:+ action = input.description.schedule.action+ assert isinstance(action, ScheduleActionStartWorkflow)++ decoded_args = await temporal.data_converter.decode(list(action.args))+ action.args = decoded_args++ now = dt.datetime.now(dt.UTC)+ re_encryption_message = f"Schedule inputs re-encrypted on {now.isoformat()}"++ current_message = input.description.schedule.state.note+ if current_message is None:+ input.description.schedule.state.note = re_encryption_message+ else:+ input.description.schedule.state.note = re_encryption_message + ". " + current_message++ return ScheduleUpdate(schedule=input.description.schedule)++ async for schedule_id in _as_async_iter(ids):+ handle = temporal.get_schedule_handle(schedule_id)++ try:+ description = await handle.describe()+ except Exception:+ LOGGER.warning("Schedule not found", schedule_id=schedule_id, dry_run=dry_run)++ failed_schedule: FailedSchedule = {"id": schedule_id, "error": "Schedule was not found"}+ failed.append(failed_schedule)++ continue++ action = description.schedule.action+ assert isinstance(action, ScheduleActionStartWorkflow)++ is_not_encrypted = any(+ payload.metadata.get("encoding") != b"binary/encrypted" for payload in list(action.args)+ )+ if is_not_encrypted:+ LOGGER.info(+ "Skipping schedule that is NOT encrypted",+ schedule_id=schedule_id,+ dry_run=dry_run,+ )+ skipped_schedule: SkippedSchedule = {+ "id": schedule_id,+ "reason": "No encryption in use",+ }+ skipped.append(skipped_schedule)+ continue++ uses_main_key = await _payloads_use_main_key(list(action.args))++ if uses_main_key:+ LOGGER.info(+ "Skipping schedule already encrypted with main key",+ schedule_id=schedule_id,+ dry_run=dry_run,+ )+ skipped_schedule = {+ "id": schedule_id,+ "reason": "Main encryption key already in use",+ }+ skipped.append(skipped_schedule)+ continue++ if dry_run:+ LOGGER.info("Encryption key not rotated in a dry-run", dry_run=dry_run, schedule_id=schedule_id)+ skipped_schedule = {"id": schedule_id, "reason": "Dry-run"}+ skipped.append(skipped_schedule)+ continue++ LOGGER.info("Rotating encryption key for schedule", dry_run=dry_run, schedule_id=schedule_id)+ try:+ await handle.update(do_update)+ except Exception:+ LOGGER.exception("Update failed", schedule_id=schedule_id, dry_run=dry_run)++ failed_schedule = {"id": schedule_id, "error": "Update operation failed"}+ failed.append(failed_schedule)++ continue++ success.append(schedule_id)++ return Results(failed=failed, success=success, skipped=skipped)+++async def _as_async_iter(+ it: collections.abc.Iterable[ScheduleID] | collections.abc.AsyncIterable[ScheduleID],+) -> collections.abc.AsyncIterator[ScheduleID]:+ if hasattr(it, "__aiter__"):+ async for item in it:+ yield item+ else:+ for item in it:+ yield item+++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), [])+ try:+ await main_key_codec.decode(payloads)+ except InvalidToken:+ return False+ return Truediff --git a/posthog/management/commands/test/test_rotate_temporal_schedule_encryption_key.py b/posthog/management/commands/test/test_rotate_temporal_schedule_encryption_key.pynew file mode 100644index 000000000000..2e465517638e--- /dev/null+++ b/posthog/management/commands/test/test_rotate_temporal_schedule_encryption_key.py@@ -0,0 +1,314 @@+import csv+import uuid+import asyncio+import datetime as dt+from io import StringIO++import pytest++from django.core.management import call_command++from cryptography.fernet import InvalidToken+from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleDescription,+ ScheduleIntervalSpec,+ ScheduleListActionStartWorkflow,+ ScheduleSpec,+ ScheduleState,+)+from temporalio.service import RPCError++from posthog.temporal.common.client import async_connect, connect++pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]++OLD_TEMPORAL_SECRET_KEY = "old-key-for-schedule-rotation-test"+NEW_TEMPORAL_SECRET_KEY = "new-key-for-schedule-rotation-test"+++async def temporal() -> Client:+ return await async_connect()+++async def schedule_ids(temporal: Client):+ created_schedule_ids: list[str] = []+ yield created_schedule_ids++ for schedule_id in created_schedule_ids:+ await _delete_schedule(temporal, schedule_id)+++def _schedule_id() -> str:+ return f"test-rotate-temporal-schedule-key-{uuid.uuid4()}"+++def _workflow_name() -> str:+ return f"test-rotate-temporal-schedule-key-workflow-{uuid.uuid4()}"+++async def _connect_with_keys(settings, secret_key: str, fallback_keys: list[str] | None = None) -> Client:+ settings.TEMPORAL_SECRET_KEY = secret_key+ settings.TEMPORAL_FALLBACK_SECRET_KEYS = fallback_keys or []+ return await async_connect()+++async def _connect_without_encryption(settings) -> Client:+ return await connect(+ settings.TEMPORAL_HOST,+ settings.TEMPORAL_PORT,+ settings.TEMPORAL_NAMESPACE,+ settings.TEMPORAL_CLIENT_CERT,+ settings.TEMPORAL_CLIENT_KEY,+ settings=None,+ )+++async def _create_schedule(+ temporal: Client, schedule_id: str, workflow_name: str, *, note: str = "existing note"+) -> None:+ await temporal.create_schedule(+ schedule_id,+ Schedule(+ action=ScheduleActionStartWorkflow(+ workflow_name,+ args=[{"schedule_id": schedule_id}],+ id=f"{schedule_id}-workflow",+ task_queue="test-task-queue",+ ),+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=dt.timedelta(days=365))]),+ state=ScheduleState(note=note, paused=True),+ ),+ )+++async def _delete_schedule(temporal: Client, schedule_id: str) -> None:+ try:+ await temporal.get_schedule_handle(schedule_id).delete()+ except RPCError:+ pass+++async def _describe_schedule(temporal: Client, schedule_id: str) -> ScheduleDescription:+ return await temporal.get_schedule_handle(schedule_id).describe()+++async def _decode_schedule_args(temporal: Client, schedule_id: str) -> list[object]:+ description = await temporal.get_schedule_handle(schedule_id).describe()+ action = description.schedule.action+ assert isinstance(action, ScheduleActionStartWorkflow)+ return await temporal.data_converter.decode(list(action.args))+++async def _list_schedule_ids_for_workflow(temporal: Client, workflow_name: str) -> list[str]:+ schedule_ids: list[str] = []+ async for listing in await temporal.list_schedules():+ action = listing.schedule.action if listing.schedule else None+ if isinstance(action, ScheduleListActionStartWorkflow) and action.workflow == workflow_name:+ schedule_ids.append(listing.id)+ return schedule_ids+++async def _wait_for_schedule_listed_by_workflow(temporal: Client, schedule_id: str, workflow_name: str) -> None:+ deadline = asyncio.get_running_loop().time() + 10+ while asyncio.get_running_loop().time() < deadline:+ if schedule_id in await _list_schedule_ids_for_workflow(temporal, workflow_name):+ return+ await asyncio.sleep(0.5)++ raise AssertionError(f"Schedule {schedule_id} was not listed for workflow {workflow_name}")+++async def _call_command(*args: str) -> None:+ await asyncio.to_thread(call_command, "rotate_temporal_schedule_encryption_key", *args)+++def _csv_output(output: str) -> list[list[str]]:+ return list(csv.reader(StringIO(output)))+++async def test_rotate_by_id_updates_schedule_key_and_writes_csv(+ settings, schedule_ids: list[str], capsys: pytest.CaptureFixture[str]+) -> None:+ schedule_id = _schedule_id()+ schedule_ids.append(schedule_id)+ old_key_client = await _connect_with_keys(settings, OLD_TEMPORAL_SECRET_KEY)+ await _create_schedule(old_key_client, schedule_id, _workflow_name())++ new_key_client = await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY)+ with pytest.raises(InvalidToken):+ await _decode_schedule_args(new_key_client, schedule_id)++ await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY, [OLD_TEMPORAL_SECRET_KEY])++ await _call_command(+ "--format=csv",+ "id",+ schedule_id,+ )++ captured = capsys.readouterr()+ assert _csv_output(captured.out) == [+ ["schedule_id", "status", "details"],+ [schedule_id, "success", ""],+ ]++ new_key_client = await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY)+ description = await _describe_schedule(new_key_client, schedule_id)+ assert description.schedule.state.note is not None+ assert "Schedule inputs re-encrypted on" in description.schedule.state.note+ assert "existing note" in description.schedule.state.note+ assert await _decode_schedule_args(new_key_client, schedule_id) == [{"schedule_id": schedule_id}]+++async def test_rotate_by_id_skips_schedule_already_using_main_key(+ settings, schedule_ids: list[str], capsys: pytest.CaptureFixture[str]+) -> None:+ schedule_id = _schedule_id()+ schedule_ids.append(schedule_id)+ new_key_client = await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY)+ await _create_schedule(new_key_client, schedule_id, _workflow_name())++ await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY, [OLD_TEMPORAL_SECRET_KEY])++ await _call_command(+ "--format=csv",+ "id",+ schedule_id,+ )++ captured = capsys.readouterr()+ assert _csv_output(captured.out) == [+ ["schedule_id", "status", "details"],+ [schedule_id, "skipped", "Main encryption key already in use"],+ ]++ description = await _describe_schedule(new_key_client, schedule_id)+ assert description.schedule.state.note == "existing note"+ assert await _decode_schedule_args(new_key_client, schedule_id) == [{"schedule_id": schedule_id}]+++async def test_rotate_by_id_skips_schedule_without_encrypted_args(+ settings, schedule_ids: list[str], capsys: pytest.CaptureFixture[str]+) -> None:+ schedule_id = _schedule_id()+ schedule_ids.append(schedule_id)+ unencrypted_client = await _connect_without_encryption(settings)+ await _create_schedule(unencrypted_client, schedule_id, _workflow_name())++ await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY, [OLD_TEMPORAL_SECRET_KEY])++ await _call_command(+ "--format=csv",+ "id",+ schedule_id,+ )++ captured = capsys.readouterr()+ assert _csv_output(captured.out) == [+ ["schedule_id", "status", "details"],+ [schedule_id, "skipped", "No encryption in use"],+ ]++ description = await _describe_schedule(unencrypted_client, schedule_id)+ assert description.schedule.state.note == "existing note"+ assert await _decode_schedule_args(unencrypted_client, schedule_id) == [{"schedule_id": schedule_id}]+++async def test_dry_run_does_not_update_schedule(+ settings, schedule_ids: list[str], capsys: pytest.CaptureFixture[str]+) -> None:+ schedule_id = _schedule_id()+ schedule_ids.append(schedule_id)+ old_key_client = await _connect_with_keys(settings, OLD_TEMPORAL_SECRET_KEY)+ await _create_schedule(old_key_client, schedule_id, _workflow_name())++ new_key_client = await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY)+ with pytest.raises(InvalidToken):+ await _decode_schedule_args(new_key_client, schedule_id)++ await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY, [OLD_TEMPORAL_SECRET_KEY])++ await _call_command(+ "--format=csv",+ "--dry-run",+ "id",+ schedule_id,+ )++ captured = capsys.readouterr()+ assert _csv_output(captured.out) == [+ ["schedule_id", "status", "details"],+ [schedule_id, "skipped", "Dry-run"],+ ]++ description = await _describe_schedule(old_key_client, schedule_id)+ assert description.schedule.state.note == "existing note"+ with pytest.raises(InvalidToken):+ await _decode_schedule_args(new_key_client, schedule_id)+ assert await _decode_schedule_args(old_key_client, schedule_id) == [{"schedule_id": schedule_id}]+++async def test_missing_schedule_reports_failure(capsys: pytest.CaptureFixture[str]) -> None:+ schedule_id = _schedule_id()++ await _call_command(+ "--format=csv",+ "id",+ schedule_id,+ )++ captured = capsys.readouterr()+ assert _csv_output(captured.out) == [+ ["schedule_id", "status", "details"],+ [schedule_id, "failed", "Schedule was not found"],+ ]+++async def test_workflow_filter_updates_matching_schedules_only(+ settings, temporal: Client, schedule_ids: list[str], capsys: pytest.CaptureFixture[str]+) -> None:+ matching_workflow = _workflow_name()+ other_workflow = _workflow_name()+ matching_schedule_id = _schedule_id()+ other_schedule_id = _schedule_id()+ schedule_ids.extend([matching_schedule_id, other_schedule_id])+ old_key_client = await _connect_with_keys(settings, OLD_TEMPORAL_SECRET_KEY)+ await _create_schedule(old_key_client, matching_schedule_id, matching_workflow)+ await _create_schedule(old_key_client, other_schedule_id, other_workflow)+ await _wait_for_schedule_listed_by_workflow(temporal, matching_schedule_id, matching_workflow)++ new_key_client = await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY)+ with pytest.raises(InvalidToken):+ await _decode_schedule_args(new_key_client, matching_schedule_id)+ with pytest.raises(InvalidToken):+ await _decode_schedule_args(new_key_client, other_schedule_id)++ await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY, [OLD_TEMPORAL_SECRET_KEY])++ await _call_command(+ "--format=csv",+ "workflow",+ matching_workflow,+ )++ captured = capsys.readouterr()+ assert _csv_output(captured.out) == [+ ["schedule_id", "status", "details"],+ [matching_schedule_id, "success", ""],+ ]++ new_key_client = await _connect_with_keys(settings, NEW_TEMPORAL_SECRET_KEY)+ matching_description = await _describe_schedule(new_key_client, matching_schedule_id)+ other_description = await _describe_schedule(old_key_client, other_schedule_id)+ assert matching_description.schedule.state.note is not None+ assert "Schedule inputs re-encrypted on" in matching_description.schedule.state.note+ assert other_description.schedule.state.note == "existing note"+ assert await _decode_schedule_args(new_key_client, matching_schedule_id) == [{"schedule_id": matching_schedule_id}]+ with pytest.raises(InvalidToken):+ await _decode_schedule_args(new_key_client, other_schedule_id)+ assert await _decode_schedule_args(old_key_client, other_schedule_id) == [{"schedule_id": other_schedule_id}]diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 12e5351330e1..c15cb68d1bb0 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -15,7 +15,7 @@ TEMPORAL_WORKFLOW_MAX_ATTEMPTS: str = os.getenv("TEMPORAL_WORKFLOW_MAX_ATTEMPTS"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]+TEMPORAL_FALLBACK_SECRET_KEYS: list[str] = get_list(os.getenv("TEMPORAL_FALLBACK_SECRET_KEYS", "")) or [SECRET_KEY]GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS: int | None = get_from_env(diff --git a/posthog/temporal/common/codec.py b/posthog/temporal/common/codec.pyindex 857c8727f5c8..3cdc8bed8846 100644--- a/posthog/temporal/common/codec.py+++ b/posthog/temporal/common/codec.py@@ -11,7 +11,7 @@ class _RequiredSettings(typing.Protocol):"""Protocol for required settings."""TEMPORAL_SECRET_KEY: str | bytes- TEMPORAL_FALLBACK_KEYS: collections.abc.Iterable[str | bytes]+ TEMPORAL_FALLBACK_SECRET_KEYS: collections.abc.Iterable[str | bytes]TEST: boolDEBUG: bool@@ -74,12 +74,12 @@ class EncryptionCodec(PayloadCodec):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)+ 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_KEYS)+ fallback_keys = map(_prepare_key, settings.TEMPORAL_FALLBACK_SECRET_KEYS)return cls(main_key, fallback_keys)diff --git a/posthog/temporal/data_imports/sources/temporalio/temporalio.py b/posthog/temporal/data_imports/sources/temporalio/temporalio.pyindex 0bf18a148d5d..94a1a8531332 100644--- a/posthog/temporal/data_imports/sources/temporalio/temporalio.py+++ b/posthog/temporal/data_imports/sources/temporalio/temporalio.py@@ -112,7 +112,7 @@ class FakeSettings:"""Required to trick temporal.io client to think its reading from django settings"""TEMPORAL_SECRET_KEY: str | bytes- TEMPORAL_FALLBACK_KEYS: Iterable[str | bytes] = dataclasses.field(default_factory=list)+ TEMPORAL_FALLBACK_SECRET_KEYS: Iterable[str | bytes] = dataclasses.field(default_factory=list)TEST: bool = FalseDEBUG: bool = Falsediff --git a/posthog/temporal/data_imports/sources/temporalio/test_temporalio.py b/posthog/temporal/data_imports/sources/temporalio/test_temporalio.pyindex 9d8106cd2ded..6bc237989516 100644--- a/posthog/temporal/data_imports/sources/temporalio/test_temporalio.py+++ b/posthog/temporal/data_imports/sources/temporalio/test_temporalio.py@@ -10,7 +10,7 @@ from posthog.temporal.data_imports.sources.temporalio.temporalio import FakeSettclass TestTemporalIOClient:def test_fake_settings_satisfies_encryption_codec_contract(self):# FakeSettings must expose every attribute EncryptionCodec.from_settings reads- # (TEST, DEBUG, TEMPORAL_SECRET_KEY, TEMPORAL_FALLBACK_KEYS); a missing one raises+ # (TEST, DEBUG, TEMPORAL_SECRET_KEY, TEMPORAL_FALLBACK_SECRET_KEYS); a missing one raises# AttributeError. The 32-byte key clears the prod (TEST=False) length guard.codec = EncryptionCodec.from_settings(FakeSettings(TEMPORAL_SECRET_KEY="k" * 32))diff --git a/posthog/temporal/tests/test_encryption_codec.py b/posthog/temporal/tests/test_encryption_codec.pyindex 39f4df760ecd..5cddec90a188 100644--- a/posthog/temporal/tests/test_encryption_codec.py+++ b/posthog/temporal/tests/test_encryption_codec.py@@ -62,7 +62,7 @@ def test_prepare_key(key: bytes, expected: bytes) -> None: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] = []+ TEMPORAL_FALLBACK_SECRET_KEYS: collections.abc.Iterable[str | bytes] = []TEST: bool = FalseDEBUG: bool = False@@ -71,7 +71,7 @@ def test_codec_rejects_short_keys_when_not_debug_or_test():with pytest.raises(ValueError):_ = EncryptionCodec.from_settings(settings)- settings.TEMPORAL_FALLBACK_KEYS = [b"b"]+ settings.TEMPORAL_FALLBACK_SECRET_KEYS = [b"b"]settings.TEMPORAL_SECRET_KEY = b"a" * 32with pytest.raises(ValueError):@@ -87,7 +87,7 @@ def test_codec_rejects_short_keys_when_not_debug_or_test():class TestEncryptionSettings:TEMPORAL_SECRET_KEY: str | bytes = b"a" * 32- TEMPORAL_FALLBACK_KEYS: collections.abc.Iterable[str | bytes] = [b"b" * 32, b"c" * 32]+ TEMPORAL_FALLBACK_SECRET_KEYS: collections.abc.Iterable[str | bytes] = [b"b" * 32, b"c" * 32]TEST: bool = FalseDEBUG: bool = False