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(gateway): drain credential last-used into ProjectSecretAPIKey (#64544)

Richard Solomoue39969bed7c1
diff --git a/posthog/storage/gateway_credential_cache.py b/posthog/storage/gateway_credential_cache.py
index 74b72e536736..0a28a9bf2390 100644
--- a/posthog/storage/gateway_credential_cache.py
+++ b/posthog/storage/gateway_credential_cache.py
@@ -19,6 +19,7 @@ cold Redis.
import os
from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
from decimal import Decimal
from typing import Any
@@ -35,6 +36,7 @@ from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.team.team import Team
from posthog.models.utils import SHA256_HASH_PREFIX, hash_key_value
from posthog.rbac.user_access_control import UserAccessControl, ordered_access_levels
+from posthog.redis import get_client
from posthog.storage.hypercache import HyperCache, HyperCacheStoreMissing, KeyType
logger = structlog.get_logger(__name__)
@@ -389,3 +391,66 @@ def refresh_all_gateway_credentials() -> int:
count += 1
return count
+
+
+# Gateway-owned Valkey hash (credential sha256$<hex> -> unix-second last-used),
+# written by the gateway. Wire contract: must match internal/lastused.ValkeyKey.
+GATEWAY_CREDENTIAL_LAST_USED_KEY = "ai-gateway:cred-last-used"
+
+# Match the authenticator's hour-granular throttle (posthog/auth.py).
+_LAST_USED_THROTTLE = timedelta(hours=1)
+
+
+def _decode_last_used_marks(raw: dict[Any, Any]) -> dict[str, int]:
+ """Fold an HGETALL result (bytes field -> bytes ts) into {hash: unix_ts}."""
+ marks: dict[str, int] = {}
+ for field, value in raw.items():
+ hash_key = field.decode() if isinstance(field, bytes | bytearray) else str(field)
+ raw_ts = value.decode() if isinstance(value, bytes | bytearray) else value
+ try:
+ marks[hash_key] = int(raw_ts)
+ except (TypeError, ValueError):
+ continue
+ return marks
+
+
+def drain_gateway_credential_last_used() -> int:
+ """Stamp ProjectSecretAPIKey.last_used_at from the gateway-coalesced Valkey hash.
+
+ phs_ only (OAuthAccessToken has no such field). bulk_update bypasses signals,
+ like the authenticator's .update(), to avoid churning the cache. Returns rows updated.
+ """
+ if not settings.AI_GATEWAY_REDIS_URL:
+ return 0
+
+ client = get_client(settings.AI_GATEWAY_REDIS_URL)
+ # Atomic read-and-clear (at-most-once): a crash before the DB commit drops
+ # this window's marks. Accepted for a cosmetic, hour-granular, self-healing
+ # field; process-then-delete would be at-least-once but races a gateway HSET.
+ pipe = client.pipeline(transaction=True)
+ pipe.hgetall(GATEWAY_CREDENTIAL_LAST_USED_KEY)
+ pipe.delete(GATEWAY_CREDENTIAL_LAST_USED_KEY)
+ raw = pipe.execute()[0]
+ if not raw:
+ return 0
+
+ marks = _decode_last_used_marks(raw)
+ if not marks:
+ return 0
+
+ to_update = []
+ for secret_key in ProjectSecretAPIKey.objects.filter(secure_value__in=marks.keys()).only(
+ "id", "last_used_at", "secure_value"
+ ):
+ ts = marks.get(secret_key.secure_value or "")
+ if ts is None:
+ continue
+ used = datetime.fromtimestamp(ts, UTC)
+ # Never regress, and honour the hour throttle against whatever last wrote it.
+ if secret_key.last_used_at is None or used - secret_key.last_used_at > _LAST_USED_THROTTLE:
+ secret_key.last_used_at = used
+ to_update.append(secret_key)
+
+ if to_update:
+ ProjectSecretAPIKey.objects.bulk_update(to_update, ["last_used_at"])
+ return len(to_update)
diff --git a/posthog/storage/test/test_gateway_credential_cache.py b/posthog/storage/test/test_gateway_credential_cache.py
index 9fe207d996bd..6cea5fb92607 100644
--- a/posthog/storage/test/test_gateway_credential_cache.py
+++ b/posthog/storage/test/test_gateway_credential_cache.py
@@ -20,13 +20,16 @@ from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token, generate_random_token_secret, hash_key_value
+from posthog.redis import get_client
from posthog.settings.utils import generate_rsa_private_key_pem
from posthog.storage.gateway_credential_cache import (
GATEWAY_CREDENTIAL_FIELDS,
+ GATEWAY_CREDENTIAL_LAST_USED_KEY,
GATEWAY_CREDENTIAL_SECRET_KEY_CACHE_TTL,
OVERSPEND_ALLOWANCE_KEY,
clear_gateway_credential,
credential_hash,
+ drain_gateway_credential_last_used,
format_overspend_allowance_usd,
gateway_credential_hypercache as hypercache,
project_gateway_credential,
@@ -34,12 +37,15 @@ from posthog.storage.gateway_credential_cache import (
validate_overspend_allowance_usd,
)
from posthog.tasks.gateway_credential import (
+ drain_gateway_credential_last_used_task,
refresh_gateway_credentials,
reproject_team_gateway_credentials_task,
reproject_user_gateway_credentials_task,
update_gateway_credential_cache_task,
)
+_TEST_GATEWAY_REDIS_URL = "redis://localhost:6379/15"
+
GATEWAY_SCOPE = "llm_gateway:read"
SECRET_KEY_KIND = "project_secret_api_key"
@@ -767,3 +773,89 @@ class TestGatewayCredentialSignals(GatewayCredentialTestMixin):
team.save()
mock_delay.assert_not_called()
+
+
+@override_settings(AI_GATEWAY_REDIS_URL=_TEST_GATEWAY_REDIS_URL)
+class TestGatewayCredentialLastUsedDrain(GatewayCredentialTestMixin):
+ """The gateway can't write Django's DB, so it coalesces credential use into a
+ Valkey hash; the drain stamps ProjectSecretAPIKey.last_used_at from it."""
+
+ def setUp(self):
+ super().setUp()
+ # fakeredis is a per-URL singleton that survives the DB rollback; clear it.
+ self.redis = get_client(_TEST_GATEWAY_REDIS_URL)
+ self.redis.delete(GATEWAY_CREDENTIAL_LAST_USED_KEY)
+
+ def _seed(self, marks: dict[str, int]) -> None:
+ # Per-field, not mapping=, so str keys satisfy hset's str|bytes without Mapping's invariant key.
+ for field, ts in marks.items():
+ self.redis.hset(GATEWAY_CREDENTIAL_LAST_USED_KEY, field, ts)
+
+ @staticmethod
+ def _hash(secret_key: ProjectSecretAPIKey) -> str:
+ assert secret_key.secure_value is not None # set by _make_secret_key
+ return secret_key.secure_value
+
+ @staticmethod
+ def _stored_ts(secret_key: ProjectSecretAPIKey) -> int:
+ secret_key.refresh_from_db()
+ assert secret_key.last_used_at is not None
+ return int(secret_key.last_used_at.timestamp())
+
+ def test_drain_stamps_secret_key_last_used(self):
+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])
+ self.assertIsNone(secret_key.last_used_at)
+ used_ts = int(timezone.now().timestamp())
+ self._seed({self._hash(secret_key): used_ts})
+
+ updated = drain_gateway_credential_last_used()
+
+ self.assertEqual(updated, 1)
+ self.assertEqual(self._stored_ts(secret_key), used_ts)
+ # The hash is consumed so a stalled drain can't double-process it.
+ self.assertFalse(self.redis.exists(GATEWAY_CREDENTIAL_LAST_USED_KEY))
+
+ @parameterized.expand(
+ [
+ # name, last_used offset from now, gateway-mark offset from now, expect update
+ ("respects_hour_throttle", timedelta(minutes=-10), timedelta(0), False),
+ ("never_regresses", timedelta(0), timedelta(hours=-2), False),
+ ("stamps_when_older_than_throttle", timedelta(hours=-3), timedelta(0), True),
+ ]
+ )
+ def test_drain_throttle_and_regression(self, _name, initial_offset, gateway_offset, expect_update):
+ now = timezone.now()
+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])
+ initial = now + initial_offset
+ ProjectSecretAPIKey.objects.filter(pk=secret_key.pk).update(last_used_at=initial)
+ self._seed({self._hash(secret_key): int((now + gateway_offset).timestamp())})
+
+ updated = drain_gateway_credential_last_used()
+
+ if expect_update:
+ self.assertEqual(updated, 1)
+ self.assertEqual(self._stored_ts(secret_key), int((now + gateway_offset).timestamp()))
+ else:
+ self.assertEqual(updated, 0)
+ self.assertEqual(self._stored_ts(secret_key), int(initial.timestamp()))
+
+ def test_drain_ignores_unknown_hash(self):
+ self._seed({f"{SHA256_HASH_PREFIX}deadbeef": int(timezone.now().timestamp())})
+
+ self.assertEqual(drain_gateway_credential_last_used(), 0)
+
+ def test_drain_empty_hash_is_noop(self):
+ self.assertEqual(drain_gateway_credential_last_used(), 0)
+
+ @override_settings(AI_GATEWAY_REDIS_URL=None)
+ def test_drain_noop_without_redis_url(self):
+ self.assertEqual(drain_gateway_credential_last_used(), 0)
+
+ def test_task_runs_drain(self):
+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])
+ used_ts = int(timezone.now().timestamp())
+ self._seed({self._hash(secret_key): used_ts})
+
+ drain_gateway_credential_last_used_task()
+
+ self.assertEqual(self._stored_ts(secret_key), used_ts)
diff --git a/posthog/tasks/gateway_credential.py b/posthog/tasks/gateway_credential.py
index fc96e6b25f92..35fdabf1e650 100644
--- a/posthog/tasks/gateway_credential.py
+++ b/posthog/tasks/gateway_credential.py
@@ -22,6 +22,7 @@ from posthog.models.team.team import Team
from posthog.scoping_audit import skip_team_scope_audit
from posthog.storage.gateway_credential_cache import (
GATEWAY_CREDENTIAL_REQUIRED_SCOPE,
+ drain_gateway_credential_last_used,
project_gateway_credential,
refresh_all_gateway_credentials,
)
@@ -93,6 +94,16 @@ def reproject_team_gateway_credentials_task(team_id: int) -> None:
project_gateway_credential(token)
+@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
+@skip_team_scope_audit
+def drain_gateway_credential_last_used_task() -> None:
+ """Stamp last_used_at for phs_ keys from the gateway's coalesced Valkey hash,
+ since gateway traffic never hits the Django auth path that would stamp it."""
+ updated = drain_gateway_credential_last_used()
+ if updated:
+ logger.info("Drained gateway credential last_used", updated=updated)
+
+
@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
def refresh_gateway_credentials() -> None:
"""Hourly: re-project every credential granted llm_gateway:read so the cache
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 351b693e5bb8..07ee935e9258 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -18,7 +18,7 @@ from posthog.tasks.email import (
send_hog_functions_daily_digest,
send_matview_failure_digest,
)
-from posthog.tasks.gateway_credential import refresh_gateway_credentials
+from posthog.tasks.gateway_credential import drain_gateway_credential_last_used_task, refresh_gateway_credentials
from posthog.tasks.hypercache_verification import (
verify_and_fix_flag_definitions_cache_task,
verify_and_fix_flag_definitions_without_cohorts_cache_task,
@@ -230,6 +230,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="gateway credential cache sync",
)
+ # Gateway credential last-used drain - every 5 min; the only writer of last_used_at for gateway keys.
+ sender.add_periodic_task(
+ crontab(minute="*/5"),
+ drain_gateway_credential_last_used_task.s(),
+ name="gateway credential last-used drain",
+ )
+
# Stale QUEUED task run cleanup - hourly
add_periodic_task_with_expiry(
sender,
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 87eacfc88790..f858416ac3a6 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -58,6 +58,7 @@
'posthog.tasks.email.send_two_factor_auth_enabled_email',
'posthog.tasks.email.send_two_factor_reset_email',
'posthog.tasks.exporter.export_asset',
+ 'posthog.tasks.gateway_credential.drain_gateway_credential_last_used_task',
'posthog.tasks.gateway_credential.refresh_gateway_credentials',
'posthog.tasks.gateway_credential.reproject_team_gateway_credentials_task',
'posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task',