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.

feat: backfill legacy secret tokens into PSAK table (#109984)

Patriciofac39409b21e
diff --git a/posthog/migrations/1394_backfill_secret_tokens_to_psak.py b/posthog/migrations/1394_backfill_secret_tokens_to_psak.py
new file mode 100644
index 000000000000..c425a1bd6278
--- /dev/null
+++ b/posthog/migrations/1394_backfill_secret_tokens_to_psak.py
@@ -0,0 +1,115 @@
+from django.db import migrations
+
+import structlog
+
+from posthog.models.utils import hash_key_value, mask_key_value
+
+logger = structlog.get_logger(__name__)
+
+BATCH_SIZE = 500
+
+# The surfaces that keep accepting PSAKs after the legacy verifiers go away. Much
+# narrower than the legacy token, which authorized every surface at once. account:read
+# is deliberately absent: it would also open the customer-analytics bulk account export,
+# which refuses the team-wide legacy token on purpose.
+MIGRATED_SCOPES = ["feature_flag:read", "support_ticket:read"]
+
+
+def _fallback_label(label: str, secure_value: str) -> str:
+ return f"{label} {secure_value[-8:]}"
+
+
+def _flush(ProjectSecretAPIKey, RevokedTeamSecretToken, db, pending: list) -> int:
+ """Insert one chunk with four queries, so row locks last seconds overall instead
+ of one round trip per token."""
+ hashes = [key.secure_value for key in pending]
+ existing = set(
+ ProjectSecretAPIKey.objects.using(db).filter(secure_value__in=hashes).values_list("secure_value", flat=True)
+ )
+ # Read per chunk, not once up front: a mirror row deleted by leak revocation must
+ # stay dead, including revocations that commit while this migration runs.
+ existing |= set(
+ RevokedTeamSecretToken.objects.using(db).filter(secure_value__in=hashes).values_list("secure_value", flat=True)
+ )
+ # A customer may already use these exact labels; (team, label) is unique.
+ candidate_labels = {key.label for key in pending} | {
+ _fallback_label(key.label, key.secure_value) for key in pending
+ }
+ taken = set(
+ ProjectSecretAPIKey.objects.using(db)
+ .filter(team_id__in={key.team_id for key in pending}, label__in=candidate_labels)
+ .values_list("team_id", "label")
+ )
+ rows = []
+ for key in pending:
+ if key.secure_value in existing:
+ continue
+ existing.add(key.secure_value)
+ if (key.team_id, key.label) in taken:
+ key.label = _fallback_label(key.label, key.secure_value)
+ if (key.team_id, key.label) in taken:
+ # Both labels are taken, so skip this token rather than abort the deploy.
+ # The legacy token keeps working. #66179 plans a second run of this
+ # backfill before it drops the plaintext columns; that run retries this team.
+ logger.warning("backfill_label_collision_skipped", team_id=key.team_id)
+ continue
+ taken.add((key.team_id, key.label))
+ rows.append(key)
+ ProjectSecretAPIKey.objects.using(db).bulk_create(rows)
+ return len(rows)
+
+
+def backfill_tokens(apps, schema_editor):
+ """
+ Create a ProjectSecretAPIKey row holding the SHA256 of every existing legacy
+ secret_api_token (and backup), so the same string keeps authenticating after the
+ plaintext columns drop (#63111). Customers change nothing.
+ """
+ Team = apps.get_model("posthog", "Team")
+ ProjectSecretAPIKey = apps.get_model("posthog", "ProjectSecretAPIKey")
+ RevokedTeamSecretToken = apps.get_model("posthog", "RevokedTeamSecretToken")
+ # Production applies migrations on a dedicated alias; unpinned managers would write
+ # to "default", outside this migration's transaction.
+ db = schema_editor.connection.alias
+
+ teams = (
+ Team.objects.using(db)
+ # Blocks a concurrent rotation from retiring a token between our read and our
+ # insert (its UPDATE needs this lock), while no_key keeps FK writers unblocked.
+ .select_for_update(no_key=True)
+ .exclude(secret_api_token__isnull=True)
+ .exclude(secret_api_token="")
+ .only("id", "secret_api_token", "secret_api_token_backup")
+ )
+
+ created_total = 0
+ pending: list = []
+ for team in teams.iterator(chunk_size=BATCH_SIZE):
+ tokens = [(team.secret_api_token, "Migrated legacy secret API key")]
+ if team.secret_api_token_backup:
+ tokens.append((team.secret_api_token_backup, "Migrated legacy key (backup)"))
+ for token, label in tokens:
+ pending.append(
+ ProjectSecretAPIKey(
+ team_id=team.id,
+ label=label,
+ secure_value=hash_key_value(token),
+ mask_value=mask_key_value(token),
+ scopes=MIGRATED_SCOPES,
+ )
+ )
+ if len(pending) >= BATCH_SIZE:
+ created_total += _flush(ProjectSecretAPIKey, RevokedTeamSecretToken, db, pending)
+ pending = []
+ if pending:
+ created_total += _flush(ProjectSecretAPIKey, RevokedTeamSecretToken, db, pending)
+
+ logger.info("backfilled_secret_tokens_to_psak", created_rows=created_total)
+
+
+class Migration(migrations.Migration):
+ dependencies = [("posthog", "1393_revokedteamsecrettoken")]
+
+ operations = [
+ migrations.RunPython(backfill_tokens, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 16c58978aae0..367641279289 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1393_revokedteamsecrettoken
+1394_backfill_secret_tokens_to_psak
diff --git a/posthog/test/test_migration_backfill_secret_tokens_to_psak.py b/posthog/test/test_migration_backfill_secret_tokens_to_psak.py
new file mode 100644
index 000000000000..dbc7777844f9
--- /dev/null
+++ b/posthog/test/test_migration_backfill_secret_tokens_to_psak.py
@@ -0,0 +1,130 @@
+from typing import Any
+
+from posthog.test.base import TestMigrations
+
+import structlog.testing
+
+from posthog.models.project_secret_api_key import find_project_secret_api_key
+from posthog.models.utils import hash_key_value
+
+PRIMARY = "phs_backfill_test_primary_token"
+BACKUP = "phs_backfill_test_backup_token"
+COLLIDING = "phs_backfill_test_label_collision_token"
+LEAK_REVOKED = "phs_backfill_test_leak_revoked_token"
+DOUBLE_COLLIDING = "phs_backfill_test_double_collision_token"
+
+
+class TestBackfillSecretTokensToPsak(TestMigrations):
+ migrate_from = "1393_revokedteamsecrettoken"
+ migrate_to = "1394_backfill_secret_tokens_to_psak"
+
+ def setUpBeforeMigration(self, apps: Any) -> None:
+ Team = apps.get_model("posthog", "Team")
+ ProjectSecretAPIKey = apps.get_model("posthog", "ProjectSecretAPIKey")
+
+ Team.objects.filter(id=self.team.id).update(secret_api_token=PRIMARY, secret_api_token_backup=BACKUP)
+ # The primary already has a row (a rerun, or a key the customer made themselves):
+ # the backfill must not duplicate it or touch its label.
+ ProjectSecretAPIKey.objects.create(
+ team_id=self.team.id,
+ label="Customer-made key",
+ secure_value=hash_key_value(PRIMARY),
+ scopes=["feature_flag:read"],
+ )
+
+ self.collision_team_id = Team.objects.create(
+ organization_id=self.organization.id,
+ project_id=self.team.project_id,
+ name="label collision",
+ secret_api_token=COLLIDING,
+ ).id
+ ProjectSecretAPIKey.objects.create(
+ team_id=self.collision_team_id,
+ label="Migrated legacy secret API key",
+ secure_value=hash_key_value("phs_backfill_test_unrelated_token"),
+ scopes=["feature_flag:read"],
+ )
+
+ self.double_collision_team_id = Team.objects.create(
+ organization_id=self.organization.id,
+ project_id=self.team.project_id,
+ name="double label collision",
+ secret_api_token=DOUBLE_COLLIDING,
+ ).id
+ for label in (
+ "Migrated legacy secret API key",
+ f"Migrated legacy secret API key {hash_key_value(DOUBLE_COLLIDING)[-8:]}",
+ ):
+ ProjectSecretAPIKey.objects.create(
+ team_id=self.double_collision_team_id,
+ label=label,
+ secure_value=hash_key_value(f"phs_backfill_test_unrelated_{label[-4:]}"),
+ scopes=["feature_flag:read"],
+ )
+
+ self.leaked_team_id = Team.objects.create(
+ organization_id=self.organization.id,
+ project_id=self.team.project_id,
+ name="leak revoked",
+ secret_api_token=LEAK_REVOKED,
+ ).id
+ apps.get_model("posthog", "RevokedTeamSecretToken").objects.create(
+ team_id=self.leaked_team_id, secure_value=hash_key_value(LEAK_REVOKED)
+ )
+
+ self.empty_team_id = Team.objects.create(
+ organization_id=self.organization.id,
+ project_id=self.team.project_id,
+ name="no legacy token",
+ secret_api_token="",
+ ).id
+
+ # Fresh teams start with NULL, and exclude(field="") keeps NULL rows: only the
+ # isnull exclude stops hash_key_value(None) from aborting the deploy.
+ self.null_team_id = Team.objects.create(
+ organization_id=self.organization.id,
+ project_id=self.team.project_id,
+ name="null legacy token",
+ secret_api_token=None,
+ ).id
+
+ def setUp(self) -> None:
+ with structlog.testing.capture_logs() as logs:
+ super().setUp()
+ self.logs = logs
+
+ def test_backfill_covers_backup_dedup_label_collision_and_empty(self) -> None:
+ assert self.apps is not None
+ ProjectSecretAPIKey = self.apps.get_model("posthog", "ProjectSecretAPIKey")
+
+ # The backup gets its own row, resolvable like any PSAK.
+ migrated = find_project_secret_api_key(BACKUP)
+ assert migrated is not None
+ assert migrated.team_id == self.team.id
+ assert migrated.scopes == ["feature_flag:read", "support_ticket:read"]
+ assert migrated.label == "Migrated legacy key (backup)"
+ assert migrated.mask_value
+
+ # The primary's pre-existing row is left alone: no duplicate, label untouched.
+ primary_rows = ProjectSecretAPIKey.objects.filter(secure_value=hash_key_value(PRIMARY))
+ assert [row.label for row in primary_rows] == ["Customer-made key"]
+
+ # A taken base label falls back to a suffixed one instead of violating (team, label).
+ collision_row = find_project_secret_api_key(COLLIDING)
+ assert collision_row is not None
+ assert collision_row.label == f"Migrated legacy secret API key {hash_key_value(COLLIDING)[-8:]}"
+
+ # Base and fallback labels both taken: the row is skipped, not an IntegrityError,
+ # and the warning operators grep for before the column drop names the team.
+ assert find_project_secret_api_key(DOUBLE_COLLIDING) is None
+ assert ProjectSecretAPIKey.objects.filter(team_id=self.double_collision_team_id).count() == 2
+ skip_logs = [log for log in self.logs if log.get("event") == "backfill_label_collision_skipped"]
+ assert [log["team_id"] for log in skip_logs] == [self.double_collision_team_id]
+
+ # A leak-revoked hash stays dead: no fresh mirror row for a still-leaked token.
+ assert find_project_secret_api_key(LEAK_REVOKED) is None
+ assert not ProjectSecretAPIKey.objects.filter(team_id=self.leaked_team_id).exists()
+
+ # A team with an empty or NULL legacy token gets nothing.
+ assert not ProjectSecretAPIKey.objects.filter(team_id=self.empty_team_id).exists()
+ assert not ProjectSecretAPIKey.objects.filter(team_id=self.null_team_id).exists()