: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(cdp): add a command to clean plaintext destination secrets (#108965)
Daniel Marchuk4c1b5996efac
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex fe7bbc7e57ce..8494a405b472 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -133,6 +133,7 @@ Rows written before a field joined `field_with_masked_contents` still store itsCode that returns a row's `detail` to a user must read `ActivityLog.safe_detail`, which masks those fields in old rows too.The activity log API, the advanced activity logs API and its exports, the notifications feed, and the PostHog AI context all do.The `system.activity_logs` SQL table and the search filter read the stored `detail`, so old rows need rewriting to stay masked there.+`python manage.py clean_destination_secrets --step activity-logs` rewrites them. It is a dry run until you pass `--commit`.These protections do not revoke exposed credentials.Destination mappings do not support secret inputs.diff --git a/products/cdp/backend/management/commands/clean_destination_secrets.py b/products/cdp/backend/management/commands/clean_destination_secrets.pynew file mode 100644index 000000000000..a9a037dee7e1--- /dev/null+++ b/products/cdp/backend/management/commands/clean_destination_secrets.py@@ -0,0 +1,114 @@+"""Remove destination credentials and input values that older code stored in plain text.++Three stores hold them, and each step cleans one:++- `debug-logs`: debug lines in `log_entries` where native and Segment destinations dumped+ their resolved config. Needs `--debug-logs-before`, the deploy time of the redaction fix.+- `activity-logs`: activity log rows that recorded values of masked fields, such as destination and+ workflow inputs, before the log masked them.+- `mapping-secrets`: secret mapping inputs, moved into the destination's encrypted inputs.++Dry run by default. Every step skips what is already clean, so a rerun is safe.+"""++from datetime import datetime+from typing import Any, Optional++from django.core.management.base import BaseCommand, CommandError++from posthog.clickhouse.log_entries import LOG_ENTRIES_SHARDED_TABLE++from products.cdp.backend.services.destination_activity_logs import (+ ActivityLogScope,+ count_unmasked_activity_logs,+ mask_activity_logs,+)+from products.cdp.backend.services.destination_debug_logs import (+ DebugLogScope,+ count_debug_logs,+ delete_debug_logs,+ find_destination_functions,+)+from products.cdp.backend.services.destination_mapping_secrets import find_mapping_secret_keys, move_mapping_secrets++STEPS = ["debug-logs", "activity-logs", "mapping-secrets"]+++class Command(BaseCommand):+ help = "Remove destination credentials and input values stored in plain text. Dry run by default."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument(+ "--step", choices=STEPS, action="append", help="Run only this step. Repeat to run several. Default: all."+ )+ parser.add_argument(+ "--debug-logs-before",+ help="ISO 8601 cutoff for the debug-logs step. Use the deploy time of the log redaction fix.",+ )+ parser.add_argument("--team-id", type=int, default=None, help="Restrict to one team.")+ parser.add_argument("--commit", action="store_true", help="Write the changes. Omit for a dry run.")++ def handle(self, *args: Any, **options: Any) -> None:+ steps = options["step"] or STEPS+ debug_logs_before = self._parse_cutoff(options["debug_logs_before"]) if "debug-logs" in steps else None+ if "debug-logs" in steps and debug_logs_before is None:+ raise CommandError("The debug-logs step needs --debug-logs-before, or leave it out with --step.")++ team_id: Optional[int] = options["team_id"]+ commit: bool = options["commit"]+ if debug_logs_before is not None:+ self._debug_logs(DebugLogScope(before=debug_logs_before, team_id=team_id), commit)+ if "activity-logs" in steps:+ self._activity_logs(ActivityLogScope(team_id=team_id), commit)+ if "mapping-secrets" in steps:+ self._mapping_secrets(team_id, commit)+ if not commit:+ self.stdout.write("Dry run. Re-run with --commit to write the changes.")++ def _parse_cutoff(self, value: Optional[str]) -> Optional[datetime]:+ if value is None:+ return None+ try:+ cutoff = datetime.fromisoformat(value)+ except ValueError:+ raise CommandError(+ "--debug-logs-before must be an ISO 8601 datetime, for example 2026-09-18T10:00:00+00:00"+ )+ if cutoff.tzinfo is None:+ raise CommandError("--debug-logs-before must carry a timezone offset")+ return cutoff++ def _debug_logs(self, scope: DebugLogScope, commit: bool) -> None:+ functions = find_destination_functions(scope)+ count = count_debug_logs(scope, functions)+ self.stdout.write(+ f"debug-logs: {count.lines} lines across {count.functions} functions in {count.teams} teams "+ f"(first {count.first_seen}, last {count.last_seen})"+ )+ if commit and count.lines:+ delete_debug_logs(scope, functions)+ self.stdout.write(+ "debug-logs: delete submitted. Watch progress with: "+ f"SELECT is_done, parts_to_do, latest_fail_reason FROM system.mutations "+ f"WHERE table = '{LOG_ENTRIES_SHARDED_TABLE}' ORDER BY create_time DESC LIMIT 5"+ )++ def _activity_logs(self, scope: ActivityLogScope, commit: bool) -> None:+ if commit:+ self.stdout.write(f"activity-logs: masked {mask_activity_logs(scope)} rows")+ return+ count = count_unmasked_activity_logs(scope)+ self.stdout.write(f"activity-logs: {count.rows} rows in {count.teams} teams to mask")++ def _mapping_secrets(self, team_id: Optional[int], commit: bool) -> None:+ keys = find_mapping_secret_keys(team_id)+ movable = [key for key in keys if key.movable]+ self.stdout.write(f"mapping-secrets: {len(movable)} of {len(keys)} secret mapping keys can move")+ for key in keys:+ if not key.movable:+ self.stdout.write(+ f"mapping-secrets: skipped team {key.team_id} function {key.function_id} "+ f"key {key.key}: {key.skip_reason}"+ )+ if commit and movable:+ self.stdout.write(f"mapping-secrets: moved keys on {move_mapping_secrets(movable)} functions")diff --git a/products/cdp/backend/services/destination_activity_logs.py b/products/cdp/backend/services/destination_activity_logs.pynew file mode 100644index 000000000000..75ce280394d9--- /dev/null+++ b/products/cdp/backend/services/destination_activity_logs.py@@ -0,0 +1,84 @@+"""Mask values in activity log rows written before the log masked their fields.++Until a field was added to the masked-fields registry, each change to it stored the old and+new values in plain text. For hog functions that included credentials in `inputs`, and for+workflows the secret inputs in `actions`. Read-time masking hides the rows from the activity+log API, but the `system.activity_logs` HogQL table and the search filter read `detail`+directly, so the rows need rewriting.++Masking uses `ActivityLog.safe_detail`, which keeps the field name and change action.+A row that is already masked is left untouched, so a rerun changes nothing.+"""++from collections.abc import Iterator+from typing import Optional+from uuid import UUID++from django.db.models import Q++from posthog.dataclasses import frozen+from posthog.models.activity_logging.activity_log import ActivityLog, field_with_masked_contents, read_masked_fields+++@frozen+class ActivityLogScope:+ team_id: Optional[int] = None+ batch_size: int = 500+++@frozen+class ActivityLogMaskCount:+ rows: int+ teams: int+++def _masked_fields() -> dict[str, set[str]]:+ fields: dict[str, set[str]] = {}+ for registry in (field_with_masked_contents, read_masked_fields):+ for model_scope, names in registry.items():+ fields.setdefault(model_scope, set()).update(names)+ return fields+++def _candidate_ids(scope: ActivityLogScope) -> list[UUID]:+ # Containment on `detail` uses the GIN index. Adding an ORDER BY or LIMIT here lets the+ # planner walk the primary key instead, which scans the whole table and times out in production.+ # The change `type` keeps common field names such as `name` from matching millions of rows.+ ids: list[UUID] = []+ for model_scope, fields in _masked_fields().items():+ field_filter = Q()+ for field in sorted(fields):+ field_filter |= Q(detail__contains={"changes": [{"type": model_scope, "field": field}]})+ queryset = ActivityLog.objects.filter(field_filter, scope=model_scope)+ if scope.team_id is not None:+ queryset = queryset.filter(team_id=scope.team_id)+ ids.extend(queryset.values_list("id", flat=True))+ return ids+++def _unmasked_batches(scope: ActivityLogScope) -> Iterator[list[ActivityLog]]:+ ids = _candidate_ids(scope)+ for start in range(0, len(ids), scope.batch_size):+ batch = ActivityLog.objects.filter(id__in=ids[start : start + scope.batch_size]).only(+ "id", "team_id", "scope", "detail"+ )+ yield [log for log in batch if log.safe_detail != log.detail]+++def count_unmasked_activity_logs(scope: ActivityLogScope) -> ActivityLogMaskCount:+ rows = 0+ teams: set[int] = set()+ for batch in _unmasked_batches(scope):+ rows += len(batch)+ teams.update(log.team_id for log in batch if log.team_id is not None)+ return ActivityLogMaskCount(rows=rows, teams=len(teams))+++def mask_activity_logs(scope: ActivityLogScope) -> int:+ masked = 0+ for batch in _unmasked_batches(scope):+ for log in batch:+ log.detail = log.safe_detail+ ActivityLog.objects.bulk_update(batch, ["detail"])+ masked += len(batch)+ return maskeddiff --git a/products/cdp/backend/services/destination_debug_logs.py b/products/cdp/backend/services/destination_debug_logs.pynew file mode 100644index 000000000000..8590417dc37d--- /dev/null+++ b/products/cdp/backend/services/destination_debug_logs.py@@ -0,0 +1,123 @@+"""Delete the debug log lines in which native and segment destinations dumped their+resolved inputs and request options in plain text.++With debug mode on, both executors logged `config`, `options`, `headers`,+`requestExtension` and `fetchOptions` as raw JSON, so integration credentials and+secret inputs landed in `log_entries`, readable by any member of the project.+The executors redact these lines now, and this removes the lines written before+that, which otherwise stay until the table's 90 day TTL.++Scoped to the functions built on those executors, matched by template prefix,+and to lines older than the cutoff the operator passes, so redacted lines written+after the fix are never touched.+"""++from datetime import datetime+from typing import Any, Optional++from django.db.models import Q++from posthog.clickhouse.client.execute import sync_execute+from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE+from posthog.clickhouse.log_entries import LOG_ENTRIES_SHARDED_TABLE, LOG_ENTRIES_TABLE+from posthog.dataclasses import frozen+from posthog.settings import CLICKHOUSE_DATABASE++from products.cdp.backend.models.hog_functions.hog_function import HogFunction++DESTINATION_TEMPLATE_PREFIXES = ("segment-", "native-")++# The executors log these as `addLog('debug', '<name>', object)`, which the log+# sanitizer renders as `<name>, {...json...}`.+DEBUG_LOG_PREFIXES = ("config, {", "options, {", "headers, {", "requestExtension, {", "fetchOptions, {")+++@frozen+class DebugLogScope:+ before: datetime+ team_id: Optional[int] = None+++@frozen+class DebugLogCount:+ lines: int+ functions: int+ teams: int+ first_seen: Optional[datetime]+ last_seen: Optional[datetime]+++def find_destination_functions(scope: DebugLogScope) -> list[tuple[int, str]]:+ # Deleted functions keep their logs, so they stay in scope.+ template_filter = Q()+ for prefix in DESTINATION_TEMPLATE_PREFIXES:+ template_filter |= Q(template_id__startswith=prefix)+ queryset = HogFunction.objects.filter(template_filter)+ if scope.team_id is not None:+ queryset = queryset.filter(team_id=scope.team_id)+ return [(team_id, str(function_id)) for team_id, function_id in queryset.values_list("team_id", "id")]+++def _predicate() -> str:+ message_filter = " OR ".join(f"message LIKE %(prefix_{i})s" for i in range(len(DEBUG_LOG_PREFIXES)))+ # `(team_id, log_source_id)` is the primary key prefix, so the pair list prunes parts.+ return f"""+ log_source = 'hog_function'+ AND level = 'debug'+ AND (team_id, log_source_id) IN %(functions)s+ AND timestamp < %(before)s+ AND ({message_filter})+ """+++def _args(scope: DebugLogScope, functions: list[tuple[int, str]]) -> dict[str, Any]:+ args: dict[str, Any] = {"functions": functions, "before": scope.before}+ for i, prefix in enumerate(DEBUG_LOG_PREFIXES):+ args[f"prefix_{i}"] = f"{prefix}%"+ return args+++def count_debug_logs(scope: DebugLogScope, functions: list[tuple[int, str]]) -> DebugLogCount:+ if not functions:+ return DebugLogCount(lines=0, functions=0, teams=0, first_seen=None, last_seen=None)+ # nosemgrep: clickhouse-fstring-param-audit - only constants are interpolated; scope and functions are bound parameters+ rows = sync_execute(+ f"""+ SELECT count(), uniqExact(log_source_id), uniqExact(team_id), min(timestamp), max(timestamp)+ FROM {LOG_ENTRIES_TABLE}+ WHERE {_predicate()}+ """,+ _args(scope, functions),+ )+ lines, function_count, teams, first_seen, last_seen = rows[0]+ return DebugLogCount(+ lines=lines,+ functions=function_count,+ teams=teams,+ first_seen=first_seen if lines else None,+ last_seen=last_seen if lines else None,+ )+++def _data_table() -> str:+ # Production holds the rows in `sharded_log_entries`; the test schema has no such table.+ rows = sync_execute(+ "SELECT count() FROM system.tables WHERE database = %(database)s AND name = %(name)s",+ {"database": CLICKHOUSE_DATABASE, "name": LOG_ENTRIES_SHARDED_TABLE},+ )+ return LOG_ENTRIES_SHARDED_TABLE if rows[0][0] else LOG_ENTRIES_TABLE+++def delete_debug_logs(scope: DebugLogScope, functions: list[tuple[int, str]], wait: bool = False) -> None:+ if not functions:+ return+ # Waiting on every replica outlasts the client timeout in production, so it runs asynchronously.+ # nosemgrep: clickhouse-fstring-param-audit - only constants are interpolated; scope and functions are bound parameters+ sync_execute(+ f"""+ DELETE FROM {_data_table()} {ON_CLUSTER_CLAUSE()}+ WHERE {_predicate()}+ """,+ _args(scope, functions),+ settings={"lightweight_deletes_sync": 2 if wait else 0},+ )diff --git a/products/cdp/backend/services/destination_mapping_secrets.py b/products/cdp/backend/services/destination_mapping_secrets.pynew file mode 100644index 000000000000..9df370a0ddde--- /dev/null+++ b/products/cdp/backend/services/destination_mapping_secrets.py@@ -0,0 +1,127 @@+"""Move secret mapping inputs into a destination's encrypted inputs.++Mappings have no encrypted column, so a secret mapping input stores its value in plain text.+The API now rejects secret mapping inputs, which also blocks every UI save of a destination+that still has one, because the UI resends the whole `mappings` list.++The executor builds each mapping's inputs as `{...inputs, ...encrypted_inputs, ...mapping.inputs}`.+A key that has one value across all mappings, and that the destination inputs do not already+use, can move to the destination inputs as a secret without changing what the destination sends.+Other keys are reported and left in place.+"""++import copy+import json+from typing import Any, Optional++from django.db import transaction++from posthog.dataclasses import frozen++from products.cdp.backend.models.hog_functions.hog_function import HogFunction+++@frozen+class MappingSecretKey:+ team_id: int+ function_id: str+ key: str+ skip_reason: Optional[str] = None++ @property+ def movable(self) -> bool:+ return self.skip_reason is None+++def _secret_mapping_keys(mappings: list[Any]) -> list[str]:+ keys: list[str] = []+ for mapping in mappings:+ for schema in (mapping or {}).get("inputs_schema") or []:+ if schema.get("secret") and schema.get("key") and schema["key"] not in keys:+ keys.append(schema["key"])+ return keys+++def _stored_values(mappings: list[Any], key: str) -> list[Any]:+ return [+ (mapping.get("inputs") or {})[key]+ for mapping in mappings+ if isinstance(mapping, dict) and ((mapping.get("inputs") or {}).get(key) or {}).get("value") is not None+ ]+++def _skip_reason(hog_function: HogFunction, key: str) -> Optional[str]:+ if any(schema.get("key") == key for schema in hog_function.inputs_schema or []):+ return "the destination inputs already use this key"+ values = {+ json.dumps(value.get("value"), sort_keys=True) for value in _stored_values(hog_function.mappings or [], key)+ }+ if len(values) > 1:+ return "mappings store different values for this key"+ # A moved value reaches every mapping, so a mapping that stores no value would start sending it.+ mappings = [mapping for mapping in hog_function.mappings or [] if isinstance(mapping, dict)]+ if values and len(_stored_values(mappings, key)) < len(mappings):+ return "some mappings do not store this key"+ return None+++def find_mapping_secret_keys(team_id: Optional[int] = None) -> list[MappingSecretKey]:+ # Deleted destinations still hold the plain text value, so they stay in scope.+ queryset = HogFunction.objects.filter(mappings__contains=[{"inputs_schema": [{"secret": True}]}])+ if team_id is not None:+ queryset = queryset.filter(team_id=team_id)+ return [+ MappingSecretKey(+ team_id=hog_function.team_id,+ function_id=str(hog_function.id),+ key=key,+ skip_reason=_skip_reason(hog_function, key),+ )+ for hog_function in queryset.only("id", "team_id", "inputs_schema", "mappings")+ for key in _secret_mapping_keys(hog_function.mappings or [])+ ]+++def _move_keys(hog_function: HogFunction, keys: list[str]) -> None:+ inputs_schema = list(hog_function.inputs_schema or [])+ inputs = dict(hog_function.inputs or {})+ mappings: list[Any] = copy.deepcopy(hog_function.mappings or [])+ for key in keys:+ # A key can be secret in one mapping and not in another; the moved schema must stay secret.+ schema = next(+ schema+ for mapping in mappings+ for schema in mapping.get("inputs_schema") or []+ if schema.get("key") == key and schema.get("secret")+ )+ # A default sits in plaintext in `inputs_schema`, and the server never reads a top-level default.+ inputs_schema.append({k: v for k, v in schema.items() if k != "default"})+ values = _stored_values(mappings, key)+ if values:+ # `save` moves every secret key of `inputs` into `encrypted_inputs`.+ inputs[key] = values[0]+ for mapping in mappings:+ mapping["inputs_schema"] = [s for s in mapping.get("inputs_schema") or [] if s.get("key") != key]+ (mapping.get("inputs") or {}).pop(key, None)+ hog_function.inputs_schema = inputs_schema+ hog_function.inputs = inputs+ hog_function.mappings = mappings+ hog_function.save()+++def move_mapping_secrets(keys: list[MappingSecretKey]) -> int:+ keys_by_function: dict[tuple[int, str], list[str]] = {}+ for secret_key in keys:+ if secret_key.movable:+ keys_by_function.setdefault((secret_key.team_id, secret_key.function_id), []).append(secret_key.key)+ moved = 0+ for (team_id, function_id), function_keys in keys_by_function.items():+ with transaction.atomic():+ hog_function = HogFunction.objects.select_for_update().get(team_id=team_id, id=function_id)+ # The row can change between the scan and the lock, so check each key again on the locked row.+ current_keys = _secret_mapping_keys(hog_function.mappings or [])+ eligible = [key for key in function_keys if key in current_keys and _skip_reason(hog_function, key) is None]+ if eligible:+ _move_keys(hog_function, eligible)+ moved += 1+ return moveddiff --git a/products/cdp/backend/test/test_destination_activity_logs.py b/products/cdp/backend/test/test_destination_activity_logs.pynew file mode 100644index 000000000000..6d899fcdd392--- /dev/null+++ b/products/cdp/backend/test/test_destination_activity_logs.py@@ -0,0 +1,92 @@+from posthog.test.base import BaseTest++from posthog.models.activity_logging.activity_log import ActivityLog++from products.cdp.backend.services.destination_activity_logs import (+ ActivityLogScope,+ count_unmasked_activity_logs,+ mask_activity_logs,+)+++class TestDestinationActivityLogs(BaseTest):+ def _log(self, scope: str, changes: list[dict]) -> ActivityLog:+ return ActivityLog.objects.create(+ team_id=self.team.pk,+ organization_id=self.organization.pk,+ user=self.user,+ scope=scope,+ activity="updated",+ item_id="1",+ detail={"name": "example", "changes": changes},+ )++ def test_masks_destination_values_and_keeps_everything_else(self) -> None:+ destination = self._log(+ "HogFunction",+ [+ {+ "type": "HogFunction",+ "field": "inputs",+ "action": "changed",+ "before": {"api_key": {"value": "key-1"}},+ "after": {"api_key": {"value": "key-2"}},+ },+ {+ "type": "HogFunction",+ "field": "mappings",+ "action": "changed",+ "before": None,+ "after": [{"inputs": {"token": {"value": "token-1"}}}],+ },+ {+ "type": "HogFunction",+ "field": "transpiled",+ "action": "changed",+ "before": "old",+ "after": 'const key = "key-2"',+ },+ {"type": "HogFunction", "field": "description", "action": "changed", "before": "a", "after": "b"},+ ],+ )+ workflow = self._log(+ "HogFlow",+ [+ {+ "type": "HogFlow",+ "field": "actions",+ "action": "changed",+ "before": [{"config": {"inputs": {"api_key": {"value": "key-1"}}}}],+ "after": [{"config": {"inputs": {"api_key": {"value": "key-2"}}}}],+ },+ ],+ )+ already_masked = self._log(+ "HogFunction",+ [{"type": "HogFunction", "field": "inputs", "action": "changed", "before": "masked", "after": "masked"}],+ )+ flag = self._log(+ "FeatureFlag",+ [{"type": "FeatureFlag", "field": "filters", "action": "changed", "before": {"a": 1}, "after": {"a": 2}}],+ )+ untouched = {log.pk: log.detail for log in (already_masked, flag)}+ scope = ActivityLogScope(team_id=self.team.pk, batch_size=1)++ assert count_unmasked_activity_logs(scope).rows == 2+ assert mask_activity_logs(scope) == 2++ destination.refresh_from_db()+ assert destination.detail is not None+ assert [(c["field"], c.get("before"), c.get("after")) for c in destination.detail["changes"]] == [+ ("inputs", {"api_key": "masked"}, {"api_key": "changed"}),+ ("mappings", None, "masked"),+ ("transpiled", "masked", "masked"),+ ("description", "a", "b"),+ ]+ workflow.refresh_from_db()+ assert workflow.detail is not None+ assert [(c["field"], c["before"], c["after"]) for c in workflow.detail["changes"]] == [+ ("actions", "masked", "masked")+ ]+ assert {log.pk: log.detail for log in ActivityLog.objects.filter(pk__in=untouched)} == untouched+ assert count_unmasked_activity_logs(scope).rows == 0diff --git a/products/cdp/backend/test/test_destination_debug_logs.py b/products/cdp/backend/test/test_destination_debug_logs.pynew file mode 100644index 000000000000..8b682747acc2--- /dev/null+++ b/products/cdp/backend/test/test_destination_debug_logs.py@@ -0,0 +1,86 @@+from datetime import UTC, datetime, timedelta++from posthog.test.base import BaseTest, ClickhouseTestMixin++from posthog.clickhouse.client.execute import sync_execute+from posthog.clickhouse.log_entries import INSERT_LOG_ENTRY_SQL++from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cdp.backend.services.destination_debug_logs import (+ DebugLogScope,+ count_debug_logs,+ delete_debug_logs,+ find_destination_functions,+)++CUTOFF = datetime(2026, 9, 18, 10, 0, 0, tzinfo=UTC)+BEFORE = CUTOFF - timedelta(days=1)+AFTER = CUTOFF + timedelta(hours=1)+++class TestDestinationDebugLogs(ClickhouseTestMixin, BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.segment = HogFunction.objects.create(+ team=self.team, name="segment", type="destination", template_id="segment-actions-example", hog=""+ )+ self.deleted_segment = HogFunction.objects.create(+ team=self.team, name="old", type="destination", template_id="segment-example", hog="", deleted=True+ )+ self.hog = HogFunction.objects.create(+ team=self.team, name="hog", type="destination", template_id="template-webhook", hog=""+ )++ def _insert(self, function: HogFunction, level: str, message: str, timestamp: datetime) -> None:+ # The table is a ReplacingMergeTree keyed on the timestamp, so every row needs its own.+ sync_execute(+ INSERT_LOG_ENTRY_SQL,+ {+ "team_id": function.team_id,+ "log_source": "hog_function",+ "log_source_id": str(function.id),+ "instance_id": "inv-1",+ "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),+ "level": level,+ "message": message,+ },+ )++ def _remaining(self) -> set[tuple[str, str]]:+ rows = sync_execute(+ "SELECT log_source_id, message FROM log_entries WHERE team_id = %(team_id)s", {"team_id": self.team.pk}+ )+ return {(function_id, message) for function_id, message in rows}++ def test_deletes_only_the_dumped_lines_of_destination_functions_before_the_cutoff(self) -> None:+ doomed = [+ (self.segment, 'config, {"apiKey":"key-1234567890"}'),+ (self.segment, 'options, {"json":{"apiKey":"key-1234567890"}}'),+ (self.segment, 'headers, {"Api-Key":"key-1234567890"}'),+ (self.segment, 'requestExtension, {"headers":{"Api-Key":"key-1234567890"}}'),+ (self.segment, 'fetchOptions, {"body":"{\\"apiKey\\":\\"key-1234567890\\"}"}'),+ (self.deleted_segment, 'config, {"apiKey":"key-0987654321"}'),+ ]+ kept = [+ (self.segment, "debug", "endpoint, https://api.example.com/track", BEFORE),+ (self.segment, "info", "Function completed in 12ms.", BEFORE),+ (self.segment, "error", 'config, {"apiKey":"key-1234567890"}', BEFORE),+ (self.segment, "debug", 'config, {"apiKey":"key-1234567890"}', AFTER),+ (self.hog, "debug", 'config, {"apiKey":"key-1234567890"}', BEFORE),+ ]+ for i, (function, message) in enumerate(doomed):+ self._insert(function, "debug", message, BEFORE + timedelta(seconds=i))+ for i, (function, level, message, timestamp) in enumerate(kept):+ self._insert(function, level, message, timestamp + timedelta(seconds=i))++ scope = DebugLogScope(before=CUTOFF, team_id=self.team.pk)+ functions = find_destination_functions(scope)+ assert set(functions) == {(self.team.pk, str(self.segment.id)), (self.team.pk, str(self.deleted_segment.id))}++ count = count_debug_logs(scope, functions)+ assert (count.lines, count.functions, count.teams) == (len(doomed), 2, 1)++ delete_debug_logs(scope, functions, wait=True)++ assert self._remaining() == {(str(function.id), message) for function, _, message, _ in kept}+ assert count_debug_logs(scope, functions).lines == 0diff --git a/products/cdp/backend/test/test_destination_mapping_secrets.py b/products/cdp/backend/test/test_destination_mapping_secrets.pynew file mode 100644index 000000000000..045e4ee9e7f8--- /dev/null+++ b/products/cdp/backend/test/test_destination_mapping_secrets.py@@ -0,0 +1,73 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cdp.backend.services.destination_mapping_secrets import find_mapping_secret_keys, move_mapping_secrets++SECRET_SCHEMA = {"key": "api_key", "type": "string", "label": "API key", "secret": True, "required": False}+URL_SCHEMA = {"key": "url", "type": "string", "label": "URL", "required": False}+++def _mapping(name: str, api_key: str) -> dict:+ return {+ "name": name,+ "inputs_schema": [URL_SCHEMA, SECRET_SCHEMA],+ "inputs": {"url": {"value": f"https://example.com/{name}"}, "api_key": {"value": api_key}},+ }+++class TestDestinationMappingSecrets(BaseTest):+ def _destination(self, inputs_schema: list[dict], mappings: list[dict]) -> HogFunction:+ hog_function = HogFunction.objects.create(team=self.team, name="destination", type="destination", hog="")+ # Written with `update` because these rows predate the rule that rejects secret mapping inputs.+ HogFunction.objects.filter(pk=hog_function.pk).update(inputs_schema=inputs_schema, inputs={}, mappings=mappings)+ return HogFunction.objects.get(pk=hog_function.pk)++ @parameterized.expand([("all_secret", True), ("first_mapping_not_secret", False)])+ def test_moves_a_shared_secret_into_encrypted_inputs(self, _name: str, first_secret: bool) -> None:+ first = _mapping("a", "key-1")+ first["inputs_schema"] = [URL_SCHEMA, {**SECRET_SCHEMA, "secret": first_secret, "default": "default-key"}]+ hog_function = self._destination([], [first, _mapping("b", "key-1")])++ keys = find_mapping_secret_keys(self.team.pk)+ assert [(k.function_id, k.key, k.movable) for k in keys] == [(str(hog_function.pk), "api_key", True)]+ assert move_mapping_secrets(keys) == 1++ hog_function.refresh_from_db()+ assert hog_function.encrypted_inputs == {"api_key": {"value": "key-1"}}+ assert "api_key" not in (hog_function.inputs or {})+ assert [(s["key"], s.get("secret"), s.get("default")) for s in hog_function.inputs_schema or []] == [+ ("api_key", True, None)+ ]+ for mapping in hog_function.mappings or []:+ assert [s["key"] for s in mapping["inputs_schema"]] == ["url"]+ assert set(mapping["inputs"]) == {"url"}+ assert find_mapping_secret_keys(self.team.pk) == []++ def test_leaves_keys_that_cannot_move_without_changing_what_is_sent(self) -> None:+ differing = self._destination([], [_mapping("a", "key-1"), _mapping("b", "key-2")])+ clashing = self._destination([{**SECRET_SCHEMA, "secret": False}], [_mapping("a", "key-1")])+ partial = self._destination([], [_mapping("a", "key-1"), {**_mapping("b", "unused"), "inputs": {}}])+ stored = {h.pk: (h.inputs_schema, h.mappings) for h in (differing, clashing, partial)}++ keys = find_mapping_secret_keys(self.team.pk)+ assert {(k.function_id, k.skip_reason) for k in keys} == {+ (str(differing.pk), "mappings store different values for this key"),+ (str(clashing.pk), "the destination inputs already use this key"),+ (str(partial.pk), "some mappings do not store this key"),+ }+ assert move_mapping_secrets(keys) == 0+ assert {h.pk: (h.inputs_schema, h.mappings) for h in HogFunction.objects.filter(pk__in=stored)} == stored++ def test_rechecks_keys_on_the_locked_row(self) -> None:+ hog_function = self._destination([], [_mapping("a", "key-1"), _mapping("b", "key-1")])+ keys = find_mapping_secret_keys(self.team.pk)+ changed = [_mapping("a", "key-1"), _mapping("b", "key-2")]+ HogFunction.objects.filter(pk=hog_function.pk).update(mappings=changed)++ assert move_mapping_secrets(keys) == 0++ hog_function.refresh_from_db()+ assert hog_function.mappings == changed+ assert not hog_function.encrypted_inputs