: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(gateway): project gateway credentials into HyperCache (#62035)
Richard Solomouaf8dc815c4e3
diff --git a/posthog/apps.py b/posthog/apps.pyindex 90ba9bc666c8..7d5321572408 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -26,9 +26,13 @@ class PostHogConfig(AppConfig):def ready(self):import posthog.storage.team_access_cache_signal_handlers # noqa: F401+ from posthog.storage.gateway_credential_signal_handlers import (+ connect_signal_handlers as connect_gateway_credential_signal_handlers,+ )from posthog.storage.team_llm_gateway_policy_signal_handlers import connect_signal_handlersconnect_signal_handlers()+ connect_gateway_credential_signal_handlers()# Connect core signal receivers at app-population. They used to wire in as an import# side effect of viewset modules; with the lazy API router those no longer load atdiff --git a/posthog/migrations/1220_projectsecretapikey_scopes_gin.py b/posthog/migrations/1220_projectsecretapikey_scopes_gin.pynew file mode 100644index 000000000000..529132b923c9--- /dev/null+++ b/posthog/migrations/1220_projectsecretapikey_scopes_gin.py@@ -0,0 +1,38 @@+from django.contrib.postgres.indexes import GinIndex+from django.db import migrations++from posthog.migration_helpers import CreateIndexConcurrently+++class Migration(migrations.Migration):+ # CONCURRENTLY so building the GIN index doesn't take an ACCESS EXCLUSIVE lock on+ # project_secret_api_key. Concurrent builds can't run in a transaction, so the+ # migration is non-atomic. CreateIndexConcurrently (vs Django's AddIndexConcurrently)+ # disables lock_timeout/statement_timeout, drops any invalid leftover from an+ # interrupted build, and uses IF NOT EXISTS — so a transient cancellation during+ # deploy doesn't wedge retries. SeparateDatabaseAndState keeps the Django model+ # state in sync via the matching AddIndex.+ atomic = False++ dependencies = [+ ("posthog", "1219_filesystemfoldercontextgeneration"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddIndex(+ model_name="projectsecretapikey",+ index=GinIndex(fields=["scopes"], name="projectsecretapikey_scopes_gin"),+ ),+ ],+ database_operations=[+ CreateIndexConcurrently(+ index_name="projectsecretapikey_scopes_gin",+ table_name="posthog_projectsecretapikey",+ columns="(scopes)",+ using="gin",+ ),+ ],+ ),+ ]diff --git a/posthog/migrations/1221_oauthaccesstoken_scope_trgm.py b/posthog/migrations/1221_oauthaccesstoken_scope_trgm.pynew file mode 100644index 000000000000..86841fa8aa12--- /dev/null+++ b/posthog/migrations/1221_oauthaccesstoken_scope_trgm.py@@ -0,0 +1,46 @@+from django.contrib.postgres.indexes import GinIndex+from django.db import migrations+from django.db.models import Q++from posthog.migration_helpers import CreateIndexConcurrently+++class Migration(migrations.Migration):+ # CONCURRENTLY so building the trigram GIN index doesn't take an ACCESS EXCLUSIVE lock+ # on oauthaccesstoken. Concurrent builds can't run in a transaction, so the migration+ # is non-atomic. CreateIndexConcurrently (vs Django's AddIndexConcurrently) disables+ # lock_timeout/statement_timeout, drops any invalid leftover from an interrupted build,+ # and uses IF NOT EXISTS — so a transient cancellation during deploy doesn't wedge+ # retries. SeparateDatabaseAndState keeps the Django model state in sync via the+ # matching AddIndex. pg_trgm is already installed (migration 0034), so the gin_trgm_ops+ # index needs no extension op.+ atomic = False++ dependencies = [+ ("posthog", "1220_projectsecretapikey_scopes_gin"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddIndex(+ model_name="oauthaccesstoken",+ index=GinIndex(+ fields=["scope"],+ name="oauthaccesstoken_scope_trgm",+ opclasses=["gin_trgm_ops"],+ condition=Q(application__isnull=False),+ ),+ ),+ ],+ database_operations=[+ CreateIndexConcurrently(+ index_name="oauthaccesstoken_scope_trgm",+ table_name="posthog_oauthaccesstoken",+ columns="(scope gin_trgm_ops)",+ using="gin",+ where="WHERE application_id IS NOT NULL",+ ),+ ],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 06d945bac2f4..d4feacee9cfa 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1219_filesystemfoldercontextgeneration+1221_oauthaccesstoken_scope_trgmdiff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 32b44de6c0bc..36adf013ecf6 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -432,6 +432,9 @@ field_exclusions: dict[AuditableScope, list[str]] = {],"ProjectSecretAPIKey": ["secure_value",+ # Gateway is team-scoped; resolving it for a diff would hit the fail-closed+ # manager. Binding changes are audited by the gateway management API instead.+ "gateway",],"Person": ["distinct_ids",diff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex 373e8812059b..c53e295856b3 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -5,8 +5,10 @@ from urllib.parse import urlparsefrom django.conf import settingsfrom django.contrib.auth.signals import user_logged_outfrom django.contrib.postgres.fields import ArrayField+from django.contrib.postgres.indexes import GinIndexfrom django.core.exceptions import ValidationErrorfrom django.db import models, transaction+from django.db.models import Qfrom django.dispatch import receiverfrom django.utils import timezone@@ -316,6 +318,19 @@ class OAuthAccessToken(AbstractAccessToken):verbose_name = "OAuth Access Token"verbose_name_plural = "OAuth Access Tokens"swappable = "OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL"+ indexes = [+ # The gateway credential cache scans for tokens holding a given scope via a+ # whitespace-bounded regex on the space-separated `scope` text. A trigram GIN+ # index lets that parameterized `~*` use an index scan; partial on+ # application_id IS NOT NULL (which every such scan already filters on) keeps+ # it to app tokens. See posthog/storage/gateway_credential_cache.py.+ GinIndex(+ fields=["scope"],+ name="oauthaccesstoken_scope_trgm",+ opclasses=["gin_trgm_ops"],+ condition=Q(application__isnull=False),+ ),+ ]id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False)diff --git a/posthog/models/project_secret_api_key.py b/posthog/models/project_secret_api_key.pyindex 6e0aae0e4a33..559789ee03d5 100644--- a/posthog/models/project_secret_api_key.py+++ b/posthog/models/project_secret_api_key.py@@ -1,6 +1,7 @@from typing import Optionalfrom django.contrib.postgres.fields import ArrayField+from django.contrib.postgres.indexes import GinIndexfrom django.db import modelsfrom django.utils import timezone@@ -51,7 +52,12 @@ class ProjectSecretAPIKey(ModelActivityMixin, models.Model):class Meta:db_table = "posthog_projectsecretapikey"- indexes = [models.Index(fields=["team", "created_at"])]+ indexes = [+ models.Index(fields=["team", "created_at"]),+ # `scopes` is filtered with the array `@>` operator (scopes__contains) on+ # the gateway-credential refresh; GIN makes it an index scan, not a seq scan.+ GinIndex(fields=["scopes"], name="projectsecretapikey_scopes_gin"),+ ]constraints = [models.UniqueConstraint(fields=["team", "label"], name="unique_team_label")]diff --git a/posthog/scopes.py b/posthog/scopes.pyindex ed1592b4400d..5074f02132e9 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -145,7 +145,10 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(# clients (the consent screen, MCP, third-party apps) to discover it.OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"metrics", "wizard_session"})-PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIScopeActions]] = [("endpoint", "read")]+PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIScopeActions]] = [+ ("endpoint", "read"),+ ("llm_gateway", "read"),+]# Server-side scope assignment string-set constants (see RFC: server-side scope# assignment for OAuthApplications).diff --git a/posthog/storage/gateway_credential_cache.py b/posthog/storage/gateway_credential_cache.pynew file mode 100644index 000000000000..7f369f9578c9--- /dev/null+++ b/posthog/storage/gateway_credential_cache.py@@ -0,0 +1,353 @@+"""+Gateway credential HyperCache — projection for the Go ai-gateway's auth path (RFC #1103).++One blob per phs_ project secret key / pha_ OAuth token, keyed by the credential's hash+so the secret never sits in a Redis key. Public phc_ project tokens can't dispatch.++ Key: cache/team_tokens_hashed/<sha256$hex>/team_metadata/gateway_credential.json+ Body: {team_id, project_token, scopes, billing_mode, revoked_at}++The hash matches Django's hash_key_value(token, mode="sha256") = "sha256$"+hex, which the+gateway derives identically. A credential holding llm_gateway:read attributes to its team+directly (no per-gateway entity); team_id is the billing-attribution dimension. project_token+is the team's phc_ key, carried only so the gateway can stamp the $ai_generation envelope —+it never authorizes dispatch; the phs_/pha_ secret does. The gateway fails closed on a+missing field, so a blob is written only for a fully-resolvable credential and cleared+otherwise. Redis-only: a ~1h OAuth token would outlive an S3 lifecycle and resurrect on a+cold Redis.+"""++import os+from collections.abc import Callable+from typing import Any++from django.conf import settings+from django.db import OperationalError+from django.utils import timezone++import structlog++from posthog.caching.ai_gateway_redis_cache import AI_GATEWAY_DEDICATED_CACHE_ALIAS+from posthog.models.oauth import OAuthAccessToken+from posthog.models.organization import OrganizationMembership+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.storage.hypercache import HyperCache, HyperCacheStoreMissing, KeyType++logger = structlog.get_logger(__name__)++GATEWAY_CREDENTIAL_REQUIRED_SCOPE = "llm_gateway:read"++# billing_mode is provisional — the gateway treats it as opaque pass-through and+# does not enforce it yet. Open: whether it is ever non-internal.+GATEWAY_CREDENTIAL_BILLING_MODE = "internal"++# Minimum project access level a user needs for the bound team. The project read+# level is the second-highest in the member ladder (none < member < admin).+_PROJECT_READ_ACCESS_LEVEL = ordered_access_levels("project")[-2]++GATEWAY_CREDENTIAL_CACHE_TTL = int(os.environ.get("GATEWAY_CREDENTIAL_CACHE_TTL", str(60 * 60 * 24 * 7)))+GATEWAY_CREDENTIAL_CACHE_MISS_TTL = int(os.environ.get("GATEWAY_CREDENTIAL_CACHE_MISS_TTL", str(60 * 60 * 24)))++# Caps the secret-key blob TTL so a signal-bypassing removal (e.g. .update())+# self-heals in hours, not the 7-day default. Must stay above the hourly refresh.+GATEWAY_CREDENTIAL_SECRET_KEY_CACHE_TTL = int(+ os.environ.get("GATEWAY_CREDENTIAL_SECRET_KEY_CACHE_TTL", str(60 * 60 * 6))+)++GATEWAY_CREDENTIAL_FIELDS = [+ "team_id",+ "project_token",+ "scopes",+ "billing_mode",+ "revoked_at",+]++Credential = ProjectSecretAPIKey | OAuthAccessToken+++class _RefreshMemo:+ """Per-run memo for the batch refresh: caches the per-(org, user) / (team, user) OAuth+ auth checks so a full re-projection does O(distinct users) lookups, not O(credentials).+ Single-credential callers pass no memo and are unaffected."""++ def __init__(self) -> None:+ self._memberships: dict[tuple[Any, Any], Any] = {}+ self._access: dict[tuple[Any, Any], bool] = {}+ self._teams: dict[Any, Team | None] = {}+ self._org_roots: dict[Any, int | None] = {}++ def membership(self, organization_id: Any, user_id: Any, load: Callable[[], Any]) -> Any:+ key = (organization_id, user_id)+ if key not in self._memberships:+ self._memberships[key] = load()+ return self._memberships[key]++ def access(self, team_id: Any, user_id: Any, load: Callable[[], bool]) -> bool:+ key = (team_id, user_id)+ if key not in self._access:+ self._access[key] = load()+ return self._access[key]++ def team(self, team_id: Any, load: Callable[[], "Team | None"]) -> "Team | None":+ if team_id not in self._teams:+ self._teams[team_id] = load()+ return self._teams[team_id]++ def org_root(self, organization_id: Any, load: Callable[[], int | None]) -> int | None:+ if organization_id not in self._org_roots:+ self._org_roots[organization_id] = load()+ return self._org_roots[organization_id]+++def credential_hash(credential: Credential) -> str | None:+ """The sha256$<hex> cache-key hash for a credential.++ ProjectSecretAPIKey.secure_value already stores hash_key_value(token); OAuth+ keeps the plaintext token, so hash it the same way (its token_checksum is bare+ hex, which would not match the gateway's sha256$-prefixed derivation).+ """+ if isinstance(credential, ProjectSecretAPIKey):+ return credential.secure_value+ return hash_key_value(credential.token, mode="sha256")+++def credential_has_gateway_scope(credential: Credential) -> bool:+ """Whether the credential literally holds llm_gateway:read.++ Literal only — a "*" wildcard must not subsume this privileged scope (RFC #1103);+ the gateway rejects a "*" blob and the legacy wildcard is being retired (#60342).+ """+ if isinstance(credential, ProjectSecretAPIKey):+ return GATEWAY_CREDENTIAL_REQUIRED_SCOPE in (credential.scopes or [])+ return GATEWAY_CREDENTIAL_REQUIRED_SCOPE in credential.scope.split()+++def _org_root_team_id(organization_id: Any) -> int | None:+ """An organization's single project-root team, or None when absent/ambiguous.++ An OAuth app is org-scoped, so it attributes to the org's root team. Resolve only when+ exactly one root exists (fetch 2 to detect ambiguity) — fail closed otherwise."""+ if not organization_id:+ return None+ roots = list(+ Team.objects.filter(organization_id=organization_id, parent_team_id__isnull=True).values_list("id", flat=True)[+ :2+ ]+ )+ return roots[0] if len(roots) == 1 else None+++def _team_by_id(team_id: int, memo: "_RefreshMemo | None") -> "Team | None":+ def load() -> "Team | None":+ return Team.objects.filter(pk=team_id).first()++ return memo.team(team_id, load) if memo else load()+++def _team_for_credential(credential: Credential, memo: "_RefreshMemo | None" = None) -> "Team | None":+ """The team a credential attributes to (no per-gateway entity).++ A secret key attributes to its canonical (project-root) team; an OAuth token to its+ application's org root team. Returns None when the team can't be resolved unambiguously.+ """+ if isinstance(credential, ProjectSecretAPIKey):+ team_id: int | None = credential.team.parent_team_id or credential.team_id+ elif credential.application is not None:+ org_id = credential.application.organization_id+ team_id = memo.org_root(org_id, lambda: _org_root_team_id(org_id)) if memo else _org_root_team_id(org_id)+ else:+ team_id = None+ if team_id is None:+ return None+ return _team_by_id(team_id, memo)+++def _ttl_for_credential(credential: Credential) -> float:+ """Seconds the blob may live. OAuth: remaining token lifetime from one now() read (may+ be <=0 if it just expired → caller clears instead of writing). Secret keys never expire,+ so cap them at a short TTL the hourly refresh keeps warm."""+ if isinstance(credential, OAuthAccessToken):+ return (credential.expires - timezone.now()).total_seconds()+ return GATEWAY_CREDENTIAL_SECRET_KEY_CACHE_TTL+++def _oauth_authorization_ok(credential: OAuthAccessToken, team: Any, team_id: int, memo: "_RefreshMemo | None") -> bool:+ """Authorization checks that only apply to an OAuth credential.++ OAuth tokens carry a user, an expiry, and scoped_* narrowing the gateway can't+ see — all enforced here, since the gateway authenticates from the cached blob+ alone (and the hourly refresh re-checks). Returns False to fail closed.+ """+ user = credential.user+ if user is None or not user.is_active:+ return False+ if credential.application_id is None:+ return False+ if credential.expires <= timezone.now():+ return False++ # scoped_* narrows below the user's membership. team_id is the gateway's canonical+ # (project-root) team, so a token scoped only to a child env fails closed here.+ if credential.scoped_teams and team_id not in credential.scoped_teams:+ return False+ if credential.scoped_organizations and str(team.organization_id) not in credential.scoped_organizations:+ return False++ # scoped_organizations is a static ceiling that doesn't track membership changing.+ def _load_membership() -> Any:+ return (+ OrganizationMembership.objects.select_related("organization")+ .filter(organization_id=team.organization_id, user_id=user.id)+ .first()+ )++ membership = memo.membership(team.organization_id, user.id, _load_membership) if memo else _load_membership()+ if membership is None:+ return False++ # Project RBAC can revoke project access without touching org membership.+ # check_access_level_for_object default-allows admins/creators/no-AC-feature orgs,+ # so this only fails closed on an explicit revocation.+ def _load_access() -> bool:+ return UserAccessControl(user=user, team=team).check_access_level_for_object(+ team, required_level=_PROJECT_READ_ACCESS_LEVEL+ )++ return memo.access(team_id, user.id, _load_access) if memo else _load_access()+++def _policy_for_credential(+ credential: Credential, memo: "_RefreshMemo | None" = None+) -> dict[str, Any] | HyperCacheStoreMissing:+ """Project a credential into the wire blob, or signal a clear.++ The credential's team (not a user's current team) is the source of truth for the billed+ team. Fails closed on missing scope, an unresolvable team, a team with no token, or — for+ OAuth — the user/expiry/scope/membership/RBAC checks. A project secret key has no user, so+ scope + resolvable-team + team-has-token is sufficient.+ """+ if not credential_has_gateway_scope(credential):+ return HyperCacheStoreMissing()++ team = _team_for_credential(credential, memo)+ if team is None:+ return HyperCacheStoreMissing()++ project_token = team.api_token+ if not project_token:+ return HyperCacheStoreMissing()++ if isinstance(credential, OAuthAccessToken) and not _oauth_authorization_ok(credential, team, team.id, memo):+ return HyperCacheStoreMissing()++ return {+ "team_id": team.id,+ "project_token": project_token,+ "scopes": [GATEWAY_CREDENTIAL_REQUIRED_SCOPE],+ "billing_mode": GATEWAY_CREDENTIAL_BILLING_MODE,+ "revoked_at": None,+ }+++def _resolve_credential(hash_key: str) -> Credential | None:+ """Reverse a cache-key hash back to its credential (Django-side reads only;+ the gateway never calls Django). ProjectSecretAPIKey.secure_value stores the+ prefixed hash directly; OAuth.token_checksum is the bare hex, so strip the prefix."""+ secret_key = ProjectSecretAPIKey.objects.select_related("team").filter(secure_value=hash_key).first()+ if secret_key is not None:+ return secret_key+ if hash_key.startswith(SHA256_HASH_PREFIX):+ checksum = hash_key[len(SHA256_HASH_PREFIX) :]+ return OAuthAccessToken.objects.select_related("user", "application").filter(token_checksum=checksum).first()+ return None+++def _load_gateway_credential(hash_key: KeyType) -> dict[str, Any] | HyperCacheStoreMissing:+ # Narrow except clause for the same reason as the team analog: only a genuine+ # miss or a transient DB error should write a negative entry; a bug must+ # propagate so the next read retries instead of 401ing for the miss TTL.+ if not isinstance(hash_key, str):+ return HyperCacheStoreMissing()+ try:+ credential = _resolve_credential(hash_key)+ if credential is None:+ return HyperCacheStoreMissing()+ return _policy_for_credential(credential)+ except OperationalError as e:+ logger.exception("Database error loading gateway credential", error_type=type(e).__name__)+ return HyperCacheStoreMissing()+++# Write-only from Django (the Go gateway reads Redis directly). Don't call+# get_from_cache — its lazy-fill ignores _ttl_for_credential and would write the 7-day+# default, defeating the secret-key cap. load_fn exists only because HyperCache requires one.+gateway_credential_hypercache = HyperCache(+ namespace="team_metadata",+ value="gateway_credential.json",+ hashed_credential_based=True,+ load_fn=_load_gateway_credential,+ cache_ttl=GATEWAY_CREDENTIAL_CACHE_TTL,+ cache_miss_ttl=GATEWAY_CREDENTIAL_CACHE_MISS_TTL,+ cache_alias=(AI_GATEWAY_DEDICATED_CACHE_ALIAS if AI_GATEWAY_DEDICATED_CACHE_ALIAS in settings.CACHES else None),+)+++def project_gateway_credential(credential: Credential, memo: "_RefreshMemo | None" = None) -> None:+ """Write (or clear) the credential's policy blob from current DB state."""+ cache_hash = credential_hash(credential)+ if not cache_hash:+ return++ policy = _policy_for_credential(credential, memo)+ if isinstance(policy, HyperCacheStoreMissing):+ gateway_credential_hypercache.delete_cache_entry(cache_hash, kinds=["redis"])+ return++ ttl = _ttl_for_credential(credential)+ if ttl <= 0: # OAuth token expired since the policy check — clear, don't write a 1s blob+ gateway_credential_hypercache.delete_cache_entry(cache_hash, kinds=["redis"])+ return++ # Floor at 1s so a sub-second-but-valid token isn't written with timeout=0,+ # which Django treats as evict-immediately.+ gateway_credential_hypercache.set_cache_value_redis_only(cache_hash, policy, ttl=max(1, int(ttl)))+++def clear_gateway_credential(credential_or_hash: Credential | str) -> None:+ cache_hash = credential_or_hash if isinstance(credential_or_hash, str) else credential_hash(credential_or_hash)+ if not cache_hash:+ return+ gateway_credential_hypercache.delete_cache_entry(cache_hash, kinds=["redis"])+++def refresh_all_gateway_credentials() -> int:+ """Re-project every credential currently granted llm_gateway:read, keeping entries warm.++ Forward-only (the cache key is a one-way hash); signals and the per-OAuth TTL handle+ removal. The team resolution and the per-OAuth membership/RBAC checks are memoized by team /+ (org, user) / (team, user) so the run does O(distinct teams/users) lookups, and .iterator()+ keeps the working set flat. The secret-key scopes lookup rides the projectsecretapikey_scopes_gin+ index; the OAuth scope regex rides the oauthaccesstoken_scope_trgm trigram GIN index.+ """+ now = timezone.now()+ memo = _RefreshMemo()+ querysets = (+ ProjectSecretAPIKey.objects.select_related("team").filter(scopes__contains=[GATEWAY_CREDENTIAL_REQUIRED_SCOPE]),+ OAuthAccessToken.objects.select_related("user", "application").filter(+ scope__iregex=r"(^|\s)llm_gateway:read(\s|$)",+ user__is_active=True,+ application_id__isnull=False,+ expires__gt=now,+ ),+ )++ count = 0+ for queryset in querysets:+ for credential in queryset.iterator(chunk_size=1000):+ project_gateway_credential(credential, memo)+ count += 1++ return countdiff --git a/posthog/storage/gateway_credential_signal_handlers.py b/posthog/storage/gateway_credential_signal_handlers.pynew file mode 100644index 000000000000..55a43db39b1e--- /dev/null+++ b/posthog/storage/gateway_credential_signal_handlers.py@@ -0,0 +1,371 @@+"""+Signal handlers that keep the gateway credential cache in sync with credential and user state.++The blob is keyed by the credential hash, so a revoke / scope removal / rotation that+doesn't invalidate it leaves a stale entry for the full TTL. OAuth access also depends on+user state the token row doesn't carry (deactivation, org membership, RBAC), so those+re-project the user's OAuth credentials. Project secret keys have no user, so they+re-project only on their own save/delete and on gateway/team changes.++A pre_save fallback handles credentials loaded with hash/scope deferred (.only()/.defer()),+where post_init skips the snapshot — without it a deferred-load rotation wouldn't clear the+old hash. Wired from PostHogConfig.ready(). All handlers no-op without AI_GATEWAY_REDIS_URL,+and skip credentials that never held the gateway scope before touching Celery/Redis.+Mutations must go through .save()/.delete(); bulk_update()/.update() bypass signals.+"""++from typing import Any++from django.conf import settings+from django.db import transaction+from django.db.models.signals import post_delete, post_init, post_save, pre_delete, pre_save++import structlog++from posthog.models.oauth import OAuthAccessToken+from posthog.models.organization import OrganizationMembership+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+from posthog.storage.gateway_credential_cache import (+ GATEWAY_CREDENTIAL_REQUIRED_SCOPE,+ clear_gateway_credential,+ credential_has_gateway_scope,+)+from posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTER++# The gateway-credential task functions are imported lazily inside the handlers+# below: this module is wired at django.setup(), and importing posthog.tasks.*+# eagerly loads every task module (celery autoimport), dragging posthog.schema /+# posthog.hogql onto the startup path of every process. See django-startup-time.++logger = structlog.get_logger(__name__)++_NAMESPACE = "gateway_credential"++_LOADED_HASH_ATTR = "_fp_loaded_hash"+_LOADED_ELIGIBLE_ATTR = "_fp_loaded_eligible"+_LOADED_IS_ACTIVE_ATTR = "_fp_loaded_is_active"+_LOADED_MEMBERSHIP_LEVEL_ATTR = "_fp_loaded_membership_level"+_LOADED_TEAM_API_TOKEN_ATTR = "_fp_loaded_team_api_token"++_SECRET_KEY_KIND = "project_secret_api_key"+_OAUTH_KIND = "oauth_access_token"+++def _secret_key_hash(instance: ProjectSecretAPIKey) -> str | None:+ return instance.secure_value+++def _oauth_hash(instance: OAuthAccessToken) -> str | None:+ return f"{SHA256_HASH_PREFIX}{instance.token_checksum}" if instance.token_checksum else None+++def _snapshot_secret_key(sender: type[ProjectSecretAPIKey], instance: ProjectSecretAPIKey, **kwargs: Any) -> None:+ if not settings.AI_GATEWAY_REDIS_URL:+ return+ deferred = instance.get_deferred_fields()+ if "secure_value" in deferred or "scopes" in deferred:+ return+ instance.__dict__[_LOADED_HASH_ATTR] = _secret_key_hash(instance)+ instance.__dict__[_LOADED_ELIGIBLE_ATTR] = credential_has_gateway_scope(instance)+++def _snapshot_oauth(sender: type[OAuthAccessToken], instance: OAuthAccessToken, **kwargs: Any) -> None:+ if not settings.AI_GATEWAY_REDIS_URL:+ return+ deferred = instance.get_deferred_fields()+ if "token_checksum" in deferred or "scope" in deferred:+ return+ instance.__dict__[_LOADED_HASH_ATTR] = _oauth_hash(instance)+ instance.__dict__[_LOADED_ELIGIBLE_ATTR] = credential_has_gateway_scope(instance)+++def _snapshot_user(sender: type[User], instance: User, **kwargs: Any) -> None:+ if not settings.AI_GATEWAY_REDIS_URL:+ return+ if "is_active" not in instance.get_deferred_fields():+ instance.__dict__[_LOADED_IS_ACTIVE_ATTR] = instance.is_active+++def _capture_old_user_is_active_if_deferred(sender: type[User], instance: User, **kwargs: Any) -> None:+ # Fallback for a user loaded with is_active deferred (.only()/.defer()): re-read the+ # old value so a deferred-load deactivation still clears the blob. No query on the+ # common full-load path, where post_init already snapshotted.+ if not settings.AI_GATEWAY_REDIS_URL or _LOADED_IS_ACTIVE_ATTR in instance.__dict__:+ return+ if not instance.pk or instance._state.adding:+ return+ row = User.objects.filter(pk=instance.pk).values("is_active").first()+ if row is not None:+ instance.__dict__[_LOADED_IS_ACTIVE_ATTR] = row["is_active"]+++def _capture_old_secret_key_if_deferred(+ sender: type[ProjectSecretAPIKey], instance: ProjectSecretAPIKey, **kwargs: Any+) -> None:+ # Fallback for a secret key loaded with secure_value/scopes deferred (post_init+ # skipped the snapshot): re-read the old values so a deferred-load rotation still+ # clears the old hash. No-op (no query) on the common full-load path.+ if not settings.AI_GATEWAY_REDIS_URL or _LOADED_HASH_ATTR in instance.__dict__:+ return+ if not instance.pk or instance._state.adding:+ return+ row = ProjectSecretAPIKey.objects.filter(pk=instance.pk).values("secure_value", "scopes").first()+ if row is None:+ return+ instance.__dict__[_LOADED_HASH_ATTR] = row["secure_value"]+ instance.__dict__[_LOADED_ELIGIBLE_ATTR] = GATEWAY_CREDENTIAL_REQUIRED_SCOPE in (row["scopes"] or [])+++def _capture_old_oauth_if_deferred(sender: type[OAuthAccessToken], instance: OAuthAccessToken, **kwargs: Any) -> None:+ if not settings.AI_GATEWAY_REDIS_URL or _LOADED_HASH_ATTR in instance.__dict__:+ return+ if not instance.pk or instance._state.adding:+ return+ row = OAuthAccessToken.objects.filter(pk=instance.pk).values("token_checksum", "scope").first()+ if row is None:+ return+ checksum = row["token_checksum"]+ instance.__dict__[_LOADED_HASH_ATTR] = f"{SHA256_HASH_PREFIX}{checksum}" if checksum else None+ instance.__dict__[_LOADED_ELIGIBLE_ATTR] = GATEWAY_CREDENTIAL_REQUIRED_SCOPE in (row["scope"] or "").split()+++def _on_credential_save(+ kind: str, instance: ProjectSecretAPIKey | OAuthAccessToken, new_hash: str | None, eligible_now: bool+) -> None:+ if not settings.AI_GATEWAY_REDIS_URL:+ return++ old_hash: str | None = instance.__dict__.get(_LOADED_HASH_ATTR)+ old_eligible: bool = instance.__dict__.get(_LOADED_ELIGIBLE_ATTR, False)+ instance.__dict__[_LOADED_HASH_ATTR] = new_hash+ instance.__dict__[_LOADED_ELIGIBLE_ATTR] = eligible_now++ # Skip credentials that never held the scope before touching Celery/Redis —+ # OAuth mints constantly and would otherwise flood the queue.+ if not eligible_now and not old_eligible:+ return++ def enqueue() -> None:+ from posthog.tasks.gateway_credential import update_gateway_credential_cache_task # noqa: PLC0415++ try:+ # A rotated/changed hash leaves the old key live for the full TTL —+ # clear it synchronously so the stale secret stops authenticating now.+ if old_hash and old_hash != new_hash:+ clear_gateway_credential(old_hash)+ if eligible_now:+ update_gateway_credential_cache_task.delay(kind, str(instance.pk))+ elif new_hash:+ # Scope was removed: clear promptly rather than waiting for a task.+ clear_gateway_credential(new_hash)+ except Exception as e:+ HYPERCACHE_SIGNAL_UPDATE_COUNTER.labels(namespace=_NAMESPACE, operation="enqueue", result="failure").inc()+ logger.exception("Failed to enqueue gateway credential cache update", kind=kind, error=str(e))+ # A sync clear/enqueue failed (e.g. transient Redis) — queue the task so a+ # revoke self-heals in queue-time instead of waiting out the blob TTL. The+ # task re-projects the current credential: writes if eligible, clears if not.+ update_gateway_credential_cache_task.delay(kind, str(instance.pk))++ transaction.on_commit(enqueue)+++def _update_secret_key_on_save(+ sender: type[ProjectSecretAPIKey], instance: ProjectSecretAPIKey, created: bool, **kwargs: Any+) -> None:+ # A scope/team change keeps the hash and re-projects through the update task,+ # which resolves the key's team gateway afresh.+ _on_credential_save(_SECRET_KEY_KIND, instance, _secret_key_hash(instance), credential_has_gateway_scope(instance))+++def _update_oauth_on_save(+ sender: type[OAuthAccessToken], instance: OAuthAccessToken, created: bool, **kwargs: Any+) -> None:+ _on_credential_save(_OAUTH_KIND, instance, _oauth_hash(instance), credential_has_gateway_scope(instance))+++def _clear_secret_key_on_delete(+ sender: type[ProjectSecretAPIKey], instance: ProjectSecretAPIKey, **kwargs: Any+) -> None:+ # Clear if eligible now or at load, so an in-memory scope change before delete+ # still drops the blob promptly instead of waiting out the TTL.+ if not settings.AI_GATEWAY_REDIS_URL:+ return+ if not (credential_has_gateway_scope(instance) or instance.__dict__.get(_LOADED_ELIGIBLE_ATTR)):+ return+ cache_hash = _secret_key_hash(instance)+ if cache_hash:+ clear_gateway_credential(cache_hash)+++def _clear_oauth_on_delete(sender: type[OAuthAccessToken], instance: OAuthAccessToken, **kwargs: Any) -> None:+ if not settings.AI_GATEWAY_REDIS_URL:+ return+ if not (credential_has_gateway_scope(instance) or instance.__dict__.get(_LOADED_ELIGIBLE_ATTR)):+ return+ cache_hash = _oauth_hash(instance)+ if cache_hash:+ clear_gateway_credential(cache_hash)+++def _reproject_user_sync_then_async(user_id: int) -> None:+ # Revocation must clear synchronously so the blob can't outlive the request; the+ # credential's own revocation already does. Reproject (not a blind clear) so any+ # blobs still valid for the user's other orgs survive. Celery is the retry/warm path.+ def _invalidate() -> None:+ from posthog.tasks.gateway_credential import reproject_user_gateway_credentials_task # noqa: PLC0415++ try:+ reproject_user_gateway_credentials_task(user_id)+ except Exception as e:+ logger.exception("Synchronous gateway credential reprojection failed", user_id=user_id, error=str(e))+ # Sync clear failed (e.g. transient Redis) — queue an async retry so the+ # blob can't outlive the TTL. No retry needed when the sync run succeeded.+ reproject_user_gateway_credentials_task.delay(user_id)++ transaction.on_commit(_invalidate)+++def _reproject_user_on_save(sender: type[User], instance: User, created: bool, **kwargs: Any) -> None:+ # Only OAuth carries a user. Deactivation must clear it (the token row doesn't+ # change on is_active flips); reactivation re-grants.+ if not settings.AI_GATEWAY_REDIS_URL or created:+ return+ old_is_active = instance.__dict__.get(_LOADED_IS_ACTIVE_ATTR)+ instance.__dict__[_LOADED_IS_ACTIVE_ATTR] = instance.is_active+ if old_is_active is None or old_is_active == instance.is_active:+ return++ _reproject_user_sync_then_async(instance.pk)+++def _reproject_on_membership_delete(+ sender: type[OrganizationMembership], instance: OrganizationMembership, **kwargs: Any+) -> None:+ # Losing membership revokes OAuth access without touching the token, so reproject+ # the user — the policy now fails closed for a non-member and clears the blob.+ if not settings.AI_GATEWAY_REDIS_URL:+ return+ _reproject_user_sync_then_async(instance.user_id)+++def _capture_old_team_token_if_deferred(sender: type[Team], instance: Team, **kwargs: Any) -> None:+ # Sole snapshot source for Team: no post_init handler, since these rows are loaded+ # far more often than saved — one query per save beats a snapshot on every load.+ if not settings.AI_GATEWAY_REDIS_URL or _LOADED_TEAM_API_TOKEN_ATTR in instance.__dict__:+ return+ if not instance.pk or instance._state.adding:+ return+ row = Team.objects.filter(pk=instance.pk).values("api_token").first()+ if row is not None:+ instance.__dict__[_LOADED_TEAM_API_TOKEN_ATTR] = row["api_token"]+++def _reproject_team_on_api_token_change(sender: type[Team], instance: Team, created: bool, **kwargs: Any) -> None:+ # project_token in the blob is the team's api_token; a rotation leaves every+ # gateway credential blob on this team's gateways carrying the stale token.+ if not settings.AI_GATEWAY_REDIS_URL or created:+ return+ old_token = instance.__dict__.get(_LOADED_TEAM_API_TOKEN_ATTR)+ instance.__dict__[_LOADED_TEAM_API_TOKEN_ATTR] = instance.api_token+ if not old_token or old_token == instance.api_token:+ return++ from posthog.tasks.gateway_credential import reproject_team_gateway_credentials_task # noqa: PLC0415++ team_id = instance.pk+ transaction.on_commit(lambda: reproject_team_gateway_credentials_task.delay(team_id))+++def _capture_old_membership_level_if_deferred(+ sender: type[OrganizationMembership], instance: OrganizationMembership, **kwargs: Any+) -> None:+ # Sole snapshot source for OrganizationMembership: no post_init handler, since these+ # rows are loaded far more often than saved — one query per save beats a snapshot on+ # every load.+ if not settings.AI_GATEWAY_REDIS_URL or _LOADED_MEMBERSHIP_LEVEL_ATTR in instance.__dict__:+ return+ if not instance.pk or instance._state.adding:+ return+ row = OrganizationMembership.objects.filter(pk=instance.pk).values("level").first()+ if row is not None:+ instance.__dict__[_LOADED_MEMBERSHIP_LEVEL_ATTR] = row["level"]+++def _reproject_on_membership_save(+ sender: type[OrganizationMembership], instance: OrganizationMembership, created: bool, **kwargs: Any+) -> None:+ # level feeds the OAuth org-admin RBAC bypass, so a change can flip the policy.+ # Creation grants nothing on its own; deletion is handled separately.+ if not settings.AI_GATEWAY_REDIS_URL or created:+ return+ old_level = instance.__dict__.get(_LOADED_MEMBERSHIP_LEVEL_ATTR)+ instance.__dict__[_LOADED_MEMBERSHIP_LEVEL_ATTR] = instance.level+ if old_level is None or old_level == instance.level:+ return++ from posthog.tasks.gateway_credential import reproject_user_gateway_credentials_task # noqa: PLC0415++ user_id = instance.user_id+ transaction.on_commit(lambda: reproject_user_gateway_credentials_task.delay(user_id))+++def _reproject_on_access_control_change(sender: type, instance: Any, **kwargs: Any) -> None:+ # A project AC flips the OAuth RBAC check; the projection keys ACs by team_id, so+ # reproject the team's credentials and a revocation clears promptly.+ if not settings.AI_GATEWAY_REDIS_URL or instance.resource != "project" or instance.team_id is None:+ return+ from posthog.tasks.gateway_credential import reproject_team_gateway_credentials_task # noqa: PLC0415++ team_id = instance.team_id+ transaction.on_commit(lambda: reproject_team_gateway_credentials_task.delay(team_id))+++def _reproject_on_role_membership_change(sender: type, instance: Any, **kwargs: Any) -> None:+ # Role membership feeds role-scoped ACs, so a change can flip project access with no+ # AccessControl row changing. Per-user, so clear synchronously like the other+ # user-scoped revocations (unlike the team-wide access-control handler).+ if not settings.AI_GATEWAY_REDIS_URL or instance.user_id is None:+ return+ _reproject_user_sync_then_async(instance.user_id)+++def connect_signal_handlers() -> None:+ post_init.connect(_snapshot_secret_key, sender=ProjectSecretAPIKey)+ pre_save.connect(_capture_old_secret_key_if_deferred, sender=ProjectSecretAPIKey)+ post_save.connect(_update_secret_key_on_save, sender=ProjectSecretAPIKey)+ pre_delete.connect(_clear_secret_key_on_delete, sender=ProjectSecretAPIKey)++ post_init.connect(_snapshot_oauth, sender=OAuthAccessToken)+ pre_save.connect(_capture_old_oauth_if_deferred, sender=OAuthAccessToken)+ post_save.connect(_update_oauth_on_save, sender=OAuthAccessToken)+ pre_delete.connect(_clear_oauth_on_delete, sender=OAuthAccessToken)++ # Team / OrganizationMembership: pre_save fallback only (no post_init). These rows+ # are read far more than written, so paying one query per save beats snapshotting+ # every load.+ pre_save.connect(_capture_old_team_token_if_deferred, sender=Team)+ post_save.connect(_reproject_team_on_api_token_change, sender=Team)++ post_init.connect(_snapshot_user, sender=User)+ pre_save.connect(_capture_old_user_is_active_if_deferred, sender=User)+ post_save.connect(_reproject_user_on_save, sender=User)++ pre_save.connect(_capture_old_membership_level_if_deferred, sender=OrganizationMembership)+ post_save.connect(_reproject_on_membership_save, sender=OrganizationMembership)+ post_delete.connect(_reproject_on_membership_delete, sender=OrganizationMembership)++ # Project access controls live in ee, which isn't installed in FOSS. Connect+ # only when available; the projection's RBAC check default-allows there anyway.+ try:+ from ee.models.rbac.access_control import AccessControl+ from ee.models.rbac.role import RoleMembership++ post_save.connect(_reproject_on_access_control_change, sender=AccessControl)+ post_delete.connect(_reproject_on_access_control_change, sender=AccessControl)+ post_save.connect(_reproject_on_role_membership_change, sender=RoleMembership)+ post_delete.connect(_reproject_on_role_membership_change, sender=RoleMembership)+ except ImportError:+ passdiff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex e3644c7318d4..90f3b9870066 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -151,6 +151,7 @@ class HyperCache:value: str,load_fn: Callable[[KeyType], dict | HyperCacheStoreMissing],token_based: bool = False,+ hashed_credential_based: bool = False,cache_ttl: int = DEFAULT_CACHE_TTL,cache_miss_ttl: int = DEFAULT_CACHE_MISS_TTL,cache_alias: Optional[str] = None,@@ -159,10 +160,17 @@ class HyperCache:enable_etag: bool = False,expiry_sorted_set_key: Optional[str] = None,):+ if token_based and hashed_credential_based:+ raise ValueError("token_based and hashed_credential_based are mutually exclusive")+self.namespace = namespaceself.value = valueself.load_fn = load_fnself.token_based = token_based+ # Credential-centric mode: keys by an already-hashed credential string+ # (sha256$<hex>) rather than a team. Used by the gateway credential+ # policy cache, where one blob exists per phx_/pha_ credential.+ self.hashed_credential_based = hashed_credential_basedself.cache_ttl = cache_ttlself.cache_miss_ttl = cache_miss_ttlself.batch_load_fn = batch_load_fn@@ -203,6 +211,9 @@ class HyperCache:return team.api_token if self.token_based else team.iddef get_cache_key(self, key: KeyType) -> str:+ if self.hashed_credential_based:+ # key is the precomputed sha256$<hex> credential hash, never a Team.+ return f"cache/team_tokens_hashed/{key}/{self.namespace}/{self.value}"if self.token_based:if isinstance(key, Team):key = key.api_token@@ -464,8 +475,14 @@ class HyperCache:return self._set_cache_value_redis(key, data, ttl=ttl)def clear_cache(self, key: KeyType, kinds: Optional[list[str]] = None):- """- Only meant for use in tests+ """Test helper alias for delete_cache_entry."""+ return self.delete_cache_entry(key, kinds)++ def delete_cache_entry(self, key: KeyType, kinds: Optional[list[str]] = None):+ """Hard-delete an entry from the given tiers (default redis + s3).++ Production-safe: the gateway credential projection uses this to revoke a+ credential's blob immediately — a missing key fails closed at the gateway."""kinds = kinds or ["redis", "s3"]try:diff --git a/posthog/storage/test/test_gateway_credential_cache.py b/posthog/storage/test/test_gateway_credential_cache.pynew file mode 100644index 000000000000..eef95c3af7a9--- /dev/null+++ b/posthog/storage/test/test_gateway_credential_cache.py@@ -0,0 +1,649 @@+import json+from datetime import timedelta++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.conf import settings+from django.test import override_settings+from django.utils import timezone++from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.organization import OrganizationMembership+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.settings.utils import generate_rsa_private_key_pem+from posthog.storage.gateway_credential_cache import (+ GATEWAY_CREDENTIAL_FIELDS,+ GATEWAY_CREDENTIAL_SECRET_KEY_CACHE_TTL,+ clear_gateway_credential,+ credential_hash,+ gateway_credential_hypercache as hypercache,+ project_gateway_credential,+ refresh_all_gateway_credentials,+)+from posthog.tasks.gateway_credential import (+ refresh_gateway_credentials,+ reproject_team_gateway_credentials_task,+ reproject_user_gateway_credentials_task,+ update_gateway_credential_cache_task,+)++GATEWAY_SCOPE = "llm_gateway:read"+SECRET_KEY_KIND = "project_secret_api_key"+++@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_private_key_pem()})+class GatewayCredentialTestMixin(BaseTest):+ def setUp(self):+ super().setUp()+ # LocMemCache persists across tests in-process; isolate each test.+ hypercache.cache_client.clear()++ def _make_secret_key(self, scopes: list[str], token: str | None = None) -> tuple[ProjectSecretAPIKey, str]:+ token = token or generate_random_token_secret()+ key = ProjectSecretAPIKey.objects.create(+ label=f"sk {token[-12:]}", # unique_team_label requires a distinct label per team+ team=self.team,+ secure_value=hash_key_value(token),+ scopes=scopes,+ )+ return key, token++ def _make_oauth(+ self,+ scope: str,+ expires_in_hours: float = 1,+ token: str | None = None,+ user: User | None = None,+ ) -> OAuthAccessToken:+ token = token or f"pha_{generate_random_token()}"+ app = OAuthApplication.objects.create(+ name="PostHog Code",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ organization=self.organization,+ user=user or self.user,+ )+ return OAuthAccessToken.objects.create(+ user=user or self.user,+ application=app,+ token=token,+ expires=timezone.now() + timedelta(hours=expires_in_hours),+ scope=scope,+ )++ def _read_blob(self, cache_hash: str | None) -> dict | None:+ if cache_hash is None:+ return None+ raw = hypercache.cache_client.get(hypercache.get_cache_key(cache_hash))+ return None if raw is None or raw == "__missing__" else json.loads(raw)+++class TestGatewayCredentialWireShape(GatewayCredentialTestMixin):+ # Mirrors the ai-gateway gateway-credential wire-shape decode test (internal/auth):+ # the literal key path and JSON shape are the cross-service contract.+ @parameterized.expand(["phs", "pha"])+ def test_blob_key_and_shape(self, kind: str):+ if kind == "phs":+ credential, token = self._make_secret_key([GATEWAY_SCOPE])+ expected_hash = hash_key_value(token)+ self.assertEqual(credential.secure_value, expected_hash)+ else:+ credential = self._make_oauth(GATEWAY_SCOPE)+ token = credential.token+ expected_hash = f"{SHA256_HASH_PREFIX}{credential.token_checksum}"+ self.assertEqual(hash_key_value(token), expected_hash)++ cache_hash = credential_hash(credential)+ assert cache_hash is not None+ self.assertEqual(cache_hash, expected_hash)+ self.assertTrue(cache_hash.startswith(SHA256_HASH_PREFIX))++ project_gateway_credential(credential)++ self.assertEqual(+ hypercache.get_cache_key(cache_hash),+ f"cache/team_tokens_hashed/{cache_hash}/team_metadata/gateway_credential.json",+ )++ blob = self._read_blob(cache_hash)+ assert blob is not None+ self.assertEqual(set(blob.keys()), set(GATEWAY_CREDENTIAL_FIELDS))+ self.assertEqual(blob["team_id"], self.team.id)+ self.assertGreater(blob["team_id"], 0)+ self.assertEqual(blob["project_token"], self.team.api_token)+ self.assertEqual(blob["scopes"], [GATEWAY_SCOPE])+ self.assertEqual(blob["billing_mode"], "internal")+ self.assertIsNone(blob["revoked_at"])++ # Raw token never appears in the key (only its hash).+ self.assertNotIn(token, hypercache.get_cache_key(cache_hash))++ def test_team_without_api_token_fails_closed(self):+ # team_id resolves but the team has no phc_ token to stamp — fail closed.+ key, _ = self._make_secret_key([GATEWAY_SCOPE])+ Team.objects.filter(pk=self.team.pk).update(api_token="")+ fresh = ProjectSecretAPIKey.objects.get(pk=key.pk)+ project_gateway_credential(fresh)+ self.assertIsNone(self._read_blob(credential_hash(fresh)))++ def test_oauth_ambiguous_org_root_fails_closed(self):+ # An OAuth app's org has two project-root teams, so the attribution team is+ # ambiguous — fail closed rather than guess.+ Team.objects.create(organization=self.organization, name="second root")+ credential = self._make_oauth(GATEWAY_SCOPE)+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(credential_hash(credential)))++ def test_secret_key_in_child_env_attributes_to_parent(self):+ # An environment is a child of its project; a key minted there bills the+ # parent (canonical) project, carrying the parent's id and api_token.+ child = Team.objects.create(organization=self.organization, name="child env", parent_team=self.team)+ token = generate_random_token_secret()+ key = ProjectSecretAPIKey.objects.create(+ label="child key", team=child, secure_value=hash_key_value(token), scopes=[GATEWAY_SCOPE]+ )+ project_gateway_credential(key)+ blob = self._read_blob(credential_hash(key))+ assert blob is not None+ self.assertEqual(blob["team_id"], self.team.id)+ self.assertEqual(blob["project_token"], self.team.api_token)+++class TestGatewayCredentialScopeGating(GatewayCredentialTestMixin):+ @parameterized.expand(+ [+ ("secret_key_no_scope", ["feature_flag:read"], False),+ ("secret_key_wildcard_does_not_subsume", ["*"], False),+ ("secret_key_write_only_not_projected", ["llm_gateway:write"], False),+ ("secret_key_has_scope", [GATEWAY_SCOPE], True),+ ]+ )+ def test_secret_key_scope_gating(self, _name: str, scopes: list[str], should_write: bool):+ credential, _ = self._make_secret_key(scopes)+ project_gateway_credential(credential)+ self.assertEqual(self._read_blob(credential_hash(credential)) is not None, should_write)++ @parameterized.expand(+ [+ # "*" must NOT subsume the privileged gateway scope (RFC #1103); the+ # gateway rejects a "*" blob and the legacy wildcard is being retired.+ ("oauth_wildcard_does_not_subsume", "*", False),+ ("oauth_literal_scope", GATEWAY_SCOPE, True),+ ("oauth_no_scope", "feature_flag:read", False),+ ("oauth_write_only_not_projected", "llm_gateway:write", False),+ ("oauth_read_and_write_projected", "llm_gateway:read llm_gateway:write", True),+ ]+ )+ def test_oauth_scope_gating(self, _name: str, scope: str, should_write: bool):+ credential = self._make_oauth(scope)+ project_gateway_credential(credential)+ self.assertEqual(self._read_blob(credential_hash(credential)) is not None, should_write)+++class TestGatewayCredentialFailClosed(GatewayCredentialTestMixin):+ def test_clear_removes_blob(self):+ credential, _ = self._make_secret_key([GATEWAY_SCOPE])+ project_gateway_credential(credential)+ cache_hash = credential_hash(credential)+ assert self._read_blob(cache_hash) is not None++ clear_gateway_credential(credential)+ self.assertIsNone(self._read_blob(cache_hash))++ def test_scope_removal_clears_blob(self):+ credential, _ = self._make_secret_key([GATEWAY_SCOPE])+ project_gateway_credential(credential)+ cache_hash = credential_hash(credential)+ assert self._read_blob(cache_hash) is not None++ credential.scopes = ["feature_flag:read"]+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(cache_hash))++ def test_expired_oauth_token_clears(self):+ credential = self._make_oauth(GATEWAY_SCOPE, expires_in_hours=-1)+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(credential_hash(credential)))++ # The user / scope-narrowing / membership / RBAC enforcement only applies to OAuth+ # — project secret keys carry no user, no scoped_*, and no membership. These cases+ # exercise the surviving OAuth authorization path.+ def test_inactive_user_clears(self):+ credential = self._make_oauth(GATEWAY_SCOPE)+ project_gateway_credential(credential)+ cache_hash = credential_hash(credential)+ assert self._read_blob(cache_hash) is not None++ self.user.is_active = False+ self.user.save()+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(cache_hash))++ def test_oauth_scoped_team_outside_fails_closed(self):+ other = Team.objects.create(organization=self.organization, name="other")+ credential = self._make_oauth(GATEWAY_SCOPE)+ credential.scoped_teams = [other.id]+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(credential_hash(credential)))++ def test_oauth_scoped_team_including_team_writes(self):+ credential = self._make_oauth(GATEWAY_SCOPE)+ credential.scoped_teams = [self.team.id]+ project_gateway_credential(credential)+ self.assertIsNotNone(self._read_blob(credential_hash(credential)))++ def test_oauth_scoped_to_child_environment_fails_closed(self):+ # The gateway is bound to the canonical (project root) team, and the Go+ # gateway authenticates at project level — it can't honor a per-environment+ # narrowing. A credential scoped only to a child environment of this project+ # deliberately fails closed rather than being silently widened to the whole+ # project. self.team is canonical (parent_team_id IS NULL); child is one of+ # its environments.+ child = Team.objects.create(organization=self.organization, name="child env", parent_team=self.team)+ credential = self._make_oauth(GATEWAY_SCOPE)+ credential.scoped_teams = [child.id]+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(credential_hash(credential)))++ def test_oauth_scoped_org_outside_fails_closed(self):+ credential = self._make_oauth(GATEWAY_SCOPE)+ credential.scoped_organizations = ["00000000-0000-0000-0000-000000000000"]+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(credential_hash(credential)))++ def test_oauth_scoped_org_matching_writes(self):+ credential = self._make_oauth(GATEWAY_SCOPE)+ credential.scoped_organizations = [str(self.organization.id)]+ project_gateway_credential(credential)+ self.assertIsNotNone(self._read_blob(credential_hash(credential)))++ def test_oauth_non_member_user_fails_closed(self):+ # A user removed from the billed team's org loses gateway access even+ # though the token, gateway, and is_active are untouched.+ credential = self._make_oauth(GATEWAY_SCOPE)+ project_gateway_credential(credential)+ cache_hash = credential_hash(credential)+ assert self._read_blob(cache_hash) is not None++ self.organization_membership.delete()+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(cache_hash))++ @pytest.mark.ee+ def test_project_access_control_revoked_fails_closed(self):+ # A real access control revoking a member's access to the bound project+ # fails closed, even though org membership is intact. Uses a real+ # AccessControl (not a mock) so it also covers that a Team resolves to the+ # "project" resource and the access-control keying matches.+ from ee.models.rbac.access_control import AccessControl++ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()++ member = User.objects.create_and_join(self.organization, "[email protected]", "password")+ membership = OrganizationMembership.objects.get(organization=self.organization, user=member)+ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ organization_member=membership,+ access_level="none",+ )+ credential = self._make_oauth(GATEWAY_SCOPE, user=member)+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(credential_hash(credential)))+++class TestGatewayCredentialTTL(GatewayCredentialTestMixin):+ def test_secret_key_written_with_capped_ttl(self):+ # Secret keys never expire, so the blob is capped at the short secret-key TTL the+ # hourly refresh keeps warm — not the 7-day default.+ key, _ = self._make_secret_key([GATEWAY_SCOPE])+ with patch.object(hypercache, "set_cache_value_redis_only") as mock_set:+ project_gateway_credential(key)+ self.assertEqual(mock_set.call_args.kwargs["ttl"], GATEWAY_CREDENTIAL_SECRET_KEY_CACHE_TTL)++ def test_oauth_blob_ttl_tracks_remaining_lifetime(self):+ # OAuth blobs live only as long as the token, so the gateway can't authenticate a+ # token past its expiry off a stale blob.+ credential = self._make_oauth(GATEWAY_SCOPE, expires_in_hours=2)+ with patch.object(hypercache, "set_cache_value_redis_only") as mock_set:+ project_gateway_credential(credential)+ ttl = mock_set.call_args.kwargs["ttl"]+ self.assertGreater(ttl, 2 * 60 * 60 - 60)+ self.assertLessEqual(ttl, 2 * 60 * 60)+++class TestGatewayCredentialRefresh(GatewayCredentialTestMixin):+ def test_refresh_projects_eligible_credentials(self):+ # Many keys share the team's one gateway; secret_key, oauth, and ignored all resolve by team.+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])+ oauth = self._make_oauth(GATEWAY_SCOPE)+ ignored, _ = self._make_secret_key(["feature_flag:read"])++ projected = refresh_all_gateway_credentials()++ self.assertGreaterEqual(projected, 2)+ self.assertIsNotNone(self._read_blob(credential_hash(secret_key)))+ self.assertIsNotNone(self._read_blob(credential_hash(oauth)))+ self.assertIsNone(self._read_blob(credential_hash(ignored)))+++class TestGatewayCredentialTasks(GatewayCredentialTestMixin):+ def test_update_task_projects_secret_key(self):+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])+ update_gateway_credential_cache_task(SECRET_KEY_KIND, str(secret_key.pk))+ self.assertIsNotNone(self._read_blob(credential_hash(secret_key)))++ def test_update_task_missing_credential_is_noop(self):+ update_gateway_credential_cache_task(SECRET_KEY_KIND, "does_not_exist")+ update_gateway_credential_cache_task("unknown_kind", "x")++ def test_reproject_user_task_projects_oauth(self):+ # reproject_user is user-scoped, so it covers OAuth only; secret keys have no user.+ oauth = self._make_oauth(GATEWAY_SCOPE)+ reproject_user_gateway_credentials_task(self.user.pk)+ self.assertIsNotNone(self._read_blob(credential_hash(oauth)))++ def test_reproject_team_task_projects_secret_keys_including_child_envs(self):+ # The team reproject catches secret keys on the team and its child environments;+ # a child-env key bills the canonical parent project.+ child = Team.objects.create(organization=self.organization, name="child env", parent_team=self.team)+ parent_key, _ = self._make_secret_key([GATEWAY_SCOPE])+ child_token = generate_random_token_secret()+ child_key = ProjectSecretAPIKey.objects.create(+ label="child key", team=child, secure_value=hash_key_value(child_token), scopes=[GATEWAY_SCOPE]+ )+ hypercache.cache_client.clear()++ reproject_team_gateway_credentials_task(self.team.pk)++ self.assertIsNotNone(self._read_blob(credential_hash(parent_key)))+ self.assertIsNotNone(self._read_blob(credential_hash(child_key)))++ def test_reproject_team_task_projects_org_oauth_tokens(self):+ # An OAuth token resolves by its application's org, so the team reproject catches+ # every gateway token in the team's organization.+ oauth = self._make_oauth(GATEWAY_SCOPE)+ hypercache.cache_client.clear()++ reproject_team_gateway_credentials_task(self.team.pk)++ self.assertIsNotNone(self._read_blob(credential_hash(oauth)))++ @patch("posthog.tasks.gateway_credential.settings")+ def test_refresh_task_noop_without_redis_url(self, mock_settings):+ mock_settings.AI_GATEWAY_REDIS_URL = None+ refresh_gateway_credentials()+++class TestGatewayCredentialSignals(GatewayCredentialTestMixin):+ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.update_gateway_credential_cache_task.delay")+ def test_secret_key_save_enqueues_update(self, mock_delay, mock_settings, mock_transaction):+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])++ mock_delay.assert_called_with(SECRET_KEY_KIND, str(secret_key.pk))++ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.update_gateway_credential_cache_task.delay")+ def test_secret_key_save_noop_without_redis_url(self, mock_delay, mock_settings):+ mock_settings.AI_GATEWAY_REDIS_URL = None+ self._make_secret_key([GATEWAY_SCOPE])+ mock_delay.assert_not_called()++ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.update_gateway_credential_cache_task.delay")+ def test_non_gateway_credential_save_does_not_enqueue(self, mock_delay, mock_settings, mock_transaction):+ # The hot path: ordinary credentials without the gateway scope must not+ # enqueue work, even when the gateway Redis is configured.+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ self._make_secret_key(["feature_flag:read"])++ mock_delay.assert_not_called()++ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.update_gateway_credential_cache_task.delay")+ def test_secret_key_rotation_clears_old_hash(self, mock_delay, mock_settings, mock_transaction):+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ old_token = generate_random_token_secret()+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE], token=old_token)+ old_hash = hash_key_value(old_token)+ project_gateway_credential(secret_key)+ assert self._read_blob(old_hash) is not None++ new_token = generate_random_token_secret()+ secret_key.secure_value = hash_key_value(new_token)+ secret_key.save()++ self.assertIsNone(self._read_blob(old_hash))++ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.update_gateway_credential_cache_task.delay")+ @patch("posthog.storage.gateway_credential_signal_handlers.clear_gateway_credential")+ def test_revoke_falls_back_to_async_when_sync_clear_fails(+ self, mock_clear, mock_delay, mock_settings, mock_transaction+ ):+ # Scope removed but the synchronous clear fails (e.g. transient Redis): queue the+ # task so the revoke self-heals instead of waiting out the blob TTL.+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])+ mock_clear.side_effect = Exception("redis down")+ secret_key.scopes = ["feature_flag:read"]+ secret_key.save()++ mock_delay.assert_called_with(SECRET_KEY_KIND, str(secret_key.pk))++ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task.delay")+ def test_user_team_change_does_not_reproject(self, mock_delay, mock_settings, mock_transaction):+ # team_id comes from the bound gateway now, so a current-team switch+ # doesn't affect any blob — no reprojection.+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ other_team = Team.objects.create(organization=self.organization, name="Other team")+ user = User.objects.get(pk=self.user.pk)+ user.current_team = other_team+ user.save()++ mock_delay.assert_not_called()++ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ def test_secret_key_delete_clears_cache(self, mock_settings):+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])+ project_gateway_credential(secret_key)+ cache_hash = credential_hash(secret_key)+ assert self._read_blob(cache_hash) is not None++ secret_key.delete()+ self.assertIsNone(self._read_blob(cache_hash))++ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task")+ def test_reproject_retries_async_only_when_sync_fails(self, mock_task, mock_settings, mock_transaction):+ # A successful sync reprojection needs no retry; a sync failure (e.g. transient+ # Redis) must fall back to an async retry so a revoked blob can't outlive the TTL.+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ user = User.objects.get(pk=self.user.pk)+ user.is_active = False+ user.save()+ mock_task.assert_called_with(user.pk) # synchronous attempt+ mock_task.delay.assert_not_called() # succeeded — no retry queued++ mock_task.reset_mock()+ mock_task.side_effect = Exception("redis down")+ user.is_active = True+ user.save()+ mock_task.assert_called_with(user.pk) # synchronous attempt+ mock_task.delay.assert_called_with(user.pk) # failed — retry queued++ def test_user_deactivation_clears_blob_synchronously(self):+ # The on_commit invalidation reprojects synchronously, so a deactivated user's+ # blob is gone without waiting for the Celery task; .delay fires only if the sync+ # reprojection raises.+ oauth = self._make_oauth(GATEWAY_SCOPE)+ project_gateway_credential(oauth)+ cache_hash = credential_hash(oauth)+ assert self._read_blob(cache_hash) is not None++ with (+ patch("posthog.storage.gateway_credential_signal_handlers.settings") as mock_settings,+ patch("posthog.storage.gateway_credential_signal_handlers.transaction") as mock_transaction,+ patch("posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task.delay") as mock_delay,+ ):+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()+ user = User.objects.get(pk=self.user.pk)+ user.is_active = False+ user.save()++ self.assertIsNone(self._read_blob(cache_hash))+ mock_delay.assert_not_called() # sync clear succeeded, no async retry needed++ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task.delay")+ def test_membership_delete_reprojects(self, mock_delay, mock_settings, mock_transaction):+ # Losing org membership clears the user's OAuth blob synchronously; .delay is the+ # retry path and fires only if the sync reprojection raises.+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ oauth = self._make_oauth(GATEWAY_SCOPE)+ project_gateway_credential(oauth)+ cache_hash = credential_hash(oauth)+ assert self._read_blob(cache_hash) is not None++ self.organization_membership.delete()++ self.assertIsNone(self._read_blob(cache_hash))+ mock_delay.assert_not_called()++ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task.delay")+ def test_membership_level_change_reprojects_user(self, mock_delay, mock_settings, mock_transaction):+ # A level change flips the OAuth RBAC admin-bypass without touching the credential.+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ membership = OrganizationMembership.objects.get(pk=self.organization_membership.pk) # snapshot level+ membership.level = (+ OrganizationMembership.Level.ADMIN+ if membership.level != OrganizationMembership.Level.ADMIN+ else OrganizationMembership.Level.MEMBER+ )+ membership.save()++ mock_delay.assert_called_with(membership.user_id)++ def test_reproject_task_clears_inactive_user_blobs(self):+ oauth = self._make_oauth(GATEWAY_SCOPE)+ project_gateway_credential(oauth)+ cache_hash = credential_hash(oauth)+ assert self._read_blob(cache_hash) is not None++ self.user.is_active = False+ self.user.save()+ reproject_user_gateway_credentials_task(self.user.pk)+ self.assertIsNone(self._read_blob(cache_hash))++ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.update_gateway_credential_cache_task.delay")+ def test_deferred_load_rotation_clears_old_hash(self, mock_delay, mock_settings, mock_transaction):+ # Secret key loaded with secure_value/scopes deferred: the post_init snapshot+ # is skipped, so the pre_save fallback must re-read the old hash to clear it.+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ old_token = generate_random_token_secret()+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE], token=old_token)+ old_hash = hash_key_value(old_token)+ project_gateway_credential(secret_key)+ assert self._read_blob(old_hash) is not None++ deferred = ProjectSecretAPIKey.objects.only("id").get(pk=secret_key.pk)+ deferred.secure_value = hash_key_value(generate_random_token_secret())+ deferred.save()++ self.assertIsNone(self._read_blob(old_hash))++ @pytest.mark.ee+ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.reproject_team_gateway_credentials_task.delay")+ def test_project_access_control_change_reprojects_team(self, mock_delay, mock_settings, mock_transaction):+ from ee.models.rbac.access_control import AccessControl++ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ AccessControl.objects.create(+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"+ )++ mock_delay.assert_called_with(self.team.id)++ @pytest.mark.ee+ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task")+ def test_role_membership_change_reprojects_synchronously(self, mock_task, mock_settings, mock_transaction):+ # Role membership is per-user, so it reprojects synchronously, unlike the+ # team-wide access-control handler. The async retry fires only on sync failure.+ from ee.models.rbac.role import Role, RoleMembership++ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ role = Role.objects.create(name="engineers", organization=self.organization)+ RoleMembership.objects.create(user=self.user, role=role)++ mock_task.assert_called_with(self.user.pk) # synchronous reprojection+ mock_task.delay.assert_not_called() # sync succeeded — no retry queued++ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")+ @patch("posthog.tasks.gateway_credential.reproject_team_gateway_credentials_task.delay")+ def test_team_api_token_rotation_reprojects(self, mock_delay, mock_settings, mock_transaction):+ # project_token in the blob is the team's api_token; rotation makes it stale.+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"+ mock_transaction.on_commit.side_effect = lambda fn: fn()++ team = Team.objects.get(pk=self.team.pk) # snapshot api_token under patched setting+ team.api_token = "phc_rotated_for_test"+ team.save()++ mock_delay.assert_called_with(self.team.id)diff --git a/posthog/tasks/gateway_credential.py b/posthog/tasks/gateway_credential.pynew file mode 100644index 000000000000..5860513af990--- /dev/null+++ b/posthog/tasks/gateway_credential.py@@ -0,0 +1,118 @@+"""+Celery tasks for the gateway credential cache.++Independent of the team_metadata / team-llm-gateway pipelines so the caches can+fail or roll back without affecting each other. The signal handlers that drive+these tasks live in+posthog/storage/gateway_credential_signal_handlers.py.+"""++import time++from django.conf import settings+from django.db.models import Q++import structlog+from celery import shared_task++from posthog.celery_queues import CeleryQueue+from posthog.models.oauth import OAuthAccessToken+from posthog.models.project_secret_api_key import ProjectSecretAPIKey+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,+ project_gateway_credential,+ refresh_all_gateway_credentials,+)+from posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTER++logger = structlog.get_logger(__name__)++_NAMESPACE = "gateway_credential"+_SECRET_KEY_KIND = "project_secret_api_key"+_OAUTH_KIND = "oauth_access_token"+++@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_audit+def update_gateway_credential_cache_task(credential_kind: str, credential_id: str) -> None:+ if credential_kind == _SECRET_KEY_KIND:+ credential = ProjectSecretAPIKey.objects.select_related("team").filter(pk=credential_id).first()+ elif credential_kind == _OAUTH_KIND:+ credential = OAuthAccessToken.objects.select_related("user", "application").filter(pk=credential_id).first()+ else:+ logger.warning("Unknown credential kind for gateway credential update", kind=credential_kind)+ return++ if credential is None:+ # Deleted between enqueue and run; pre_delete already cleared the entry.+ logger.debug("Credential gone for gateway credential update", kind=credential_kind)+ return++ project_gateway_credential(credential)+ HYPERCACHE_SIGNAL_UPDATE_COUNTER.labels(namespace=_NAMESPACE, operation="update", result="success").inc()+++@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_audit+def reproject_user_gateway_credentials_task(user_id: int) -> None:+ """Re-project a user's OAuth credentials after a user/membership/RBAC change.+ Project secret keys have no user, so they're unaffected and not touched here."""+ for token in OAuthAccessToken.objects.select_related("user", "application").filter(+ scope__iregex=r"(^|\s)llm_gateway:read(\s|$)", user_id=user_id, application_id__isnull=False+ ):+ project_gateway_credential(token)+++@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_audit+def reproject_team_gateway_credentials_task(team_id: int) -> None:+ """Re-project every credential resolving to a team's gateway, after its slug or+ api_token changed (project_token / $ai_gateway_slug) or a project access-control change.++ No FK binding any more: a secret key resolves by its canonical (project-root) team, so+ catch the team and its child envs; an OAuth token resolves by its application's org, so+ catch every token in the team's organization (all resolve to this same gateway)."""+ for secret_key in ProjectSecretAPIKey.objects.select_related("team").filter(+ Q(team_id=team_id) | Q(team__parent_team_id=team_id),+ scopes__contains=[GATEWAY_CREDENTIAL_REQUIRED_SCOPE],+ ):+ project_gateway_credential(secret_key)++ organization_id = Team.objects.filter(pk=team_id).values_list("organization_id", flat=True).first()+ if organization_id is None:+ return+ for token in OAuthAccessToken.objects.select_related("user", "application").filter(+ application__organization_id=organization_id,+ scope__iregex=r"(^|\s)llm_gateway:read(\s|$)",+ application_id__isnull=False,+ ):+ project_gateway_credential(token)+++@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+ stays warm. This only refreshes still-eligible credentials, so it heals missed+ *additions*, not removals — a revoked credential is cleared by its signal or,+ failing that, by blob TTL expiry."""+ if not settings.AI_GATEWAY_REDIS_URL:+ logger.info("AI gateway Redis URL not set, skipping gateway credential refresh")+ return++ start_time = time.time()+ try:+ projected = refresh_all_gateway_credentials()+ logger.info(+ "Completed gateway credential refresh",+ projected=projected,+ duration_seconds=time.time() - start_time,+ )+ except Exception as e:+ logger.exception(+ "Failed to complete gateway credential refresh",+ error=str(e),+ duration_seconds=time.time() - start_time,+ )+ raisediff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 627196cc9721..03c0f0568b12 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -17,6 +17,7 @@ from posthog.tasks.email import (send_hog_functions_daily_digest,send_matview_failure_digest,)+from posthog.tasks.gateway_credential import refresh_gateway_credentialsfrom posthog.tasks.hypercache_verification import (verify_and_fix_flag_definitions_cache_task,verify_and_fix_flag_definitions_without_cohorts_cache_task,@@ -213,6 +214,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="llm-gateway policy cache sync",)+ # Gateway credential cache sync - hourly at :10 to stagger from the others+ sender.add_periodic_task(+ crontab(hour="*", minute="10"),+ refresh_gateway_credentials.s(),+ name="gateway credential cache sync",+ )+# Stale QUEUED task run cleanup - hourlyadd_periodic_task_with_expiry(sender,diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex d0bf93b03571..87eacfc88790 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -58,6 +58,10 @@'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.refresh_gateway_credentials',+ 'posthog.tasks.gateway_credential.reproject_team_gateway_credentials_task',+ 'posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task',+ 'posthog.tasks.gateway_credential.update_gateway_credential_cache_task','posthog.tasks.health_checks.evaluate_health_check_for_team','posthog.tasks.hypercache_verification.verify_and_fix_flag_definitions_cache_task','posthog.tasks.hypercache_verification.verify_and_fix_flag_definitions_without_cohorts_cache_task',diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex bdb42f1829f0..723936249742 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -51,6 +51,9 @@ post_delete:posthog.models.product_intent.product_intent._invalidate_product_intpost_delete:posthog.models.remote_config.product_tour_deletedpost_delete:posthog.models.remote_config.site_function_changedpost_delete:posthog.models.team.team.delete_team_in_cache_on_delete+post_delete:posthog.storage.gateway_credential_signal_handlers._reproject_on_access_control_change+post_delete:posthog.storage.gateway_credential_signal_handlers._reproject_on_membership_delete+post_delete:posthog.storage.gateway_credential_signal_handlers._reproject_on_role_membership_changepost_delete:posthog.storage.team_access_cache_signal_handlers.organization_membership_deletedpost_delete:posthog.storage.team_access_cache_signal_handlers.personal_api_key_deletedpost_delete:posthog.storage.team_access_cache_signal_handlers.project_secret_api_key_deleted@@ -78,6 +81,9 @@ post_delete:products.feature_flags.backend.local_evaluation.feature_flag_changedpost_delete:products.feature_flags.backend.models.feature_flag.refresh_flag_cache_on_updatespost_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_changepost_delete:products.surveys.backend.models.survey_changed+post_init:posthog.storage.gateway_credential_signal_handlers._snapshot_oauth+post_init:posthog.storage.gateway_credential_signal_handlers._snapshot_secret_key+post_init:posthog.storage.gateway_credential_signal_handlers._snapshot_userpost_init:posthog.storage.team_llm_gateway_policy_signal_handlers._snapshot_loaded_statepost_save:ee.models.license.license_savedpost_save:ee.vercel.integration.sync_experiment_experimentation_item@@ -104,6 +110,13 @@ post_save:posthog.models.remote_config.team_savedpost_save:posthog.models.team.extensions.register_team_extension_signal.<locals>.receiver_funcpost_save:posthog.models.team.team.put_team_in_cache_on_savepost_save:posthog.models.team.team.reevaluate_authorized_urls_health+post_save:posthog.storage.gateway_credential_signal_handlers._reproject_on_access_control_change+post_save:posthog.storage.gateway_credential_signal_handlers._reproject_on_membership_save+post_save:posthog.storage.gateway_credential_signal_handlers._reproject_on_role_membership_change+post_save:posthog.storage.gateway_credential_signal_handlers._reproject_team_on_api_token_change+post_save:posthog.storage.gateway_credential_signal_handlers._reproject_user_on_save+post_save:posthog.storage.gateway_credential_signal_handlers._update_oauth_on_save+post_save:posthog.storage.gateway_credential_signal_handlers._update_secret_key_on_savepost_save:posthog.storage.team_access_cache_signal_handlers.organization_membership_savedpost_save:posthog.storage.team_access_cache_signal_handlers.personal_api_key_savedpost_save:posthog.storage.team_access_cache_signal_handlers.project_secret_api_key_saved@@ -167,6 +180,8 @@ pre_delete:posthog.models.activity_logging.signal_handlers.handle_personal_api_kpre_delete:posthog.models.activity_logging.signal_handlers.handle_project_secret_api_key_deletepre_delete:posthog.models.organization.ensure_organization_membership_consistencypre_delete:posthog.models.organization_invite._unsuppress_delegator_onboarding_on_invite_delete+pre_delete:posthog.storage.gateway_credential_signal_handlers._clear_oauth_on_delete+pre_delete:posthog.storage.gateway_credential_signal_handlers._clear_secret_key_on_deletepre_delete:posthog.storage.team_access_cache_signal_handlers.clear_project_secret_api_key_cache_on_deletepre_delete:posthog.storage.team_llm_gateway_policy_signal_handlers._clear_cache_on_deletepre_delete:products.alerts.backend.activity_logging.cleanup_alert_hog_functions@@ -176,6 +191,11 @@ pre_save:posthog.models.event_ingestion_restriction_config.capture_old_restrictipre_save:posthog.models.organization.organization_about_to_be_createdpre_save:posthog.models.organization.organization_membership_savedpre_save:posthog.models.product_intent.product_intent._capture_original_team_id+pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_membership_level_if_deferred+pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_oauth_if_deferred+pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_secret_key_if_deferred+pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_team_token_if_deferred+pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_user_is_active_if_deferredpre_save:posthog.storage.team_access_cache_signal_handlers.personal_api_key_pre_savepre_save:posthog.storage.team_access_cache_signal_handlers.project_secret_api_key_pre_savepre_save:posthog.storage.team_access_cache_signal_handlers.team_pre_save_auth_cache