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(oauth): exchange workload oidc tokens for short-lived project tokens (#127785)

Rafael Audibertfb31cfc53a4c
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.md
index c40311e6045a..7ab1476ae60a 100644
--- a/docs/internal/activity-logging.md
+++ b/docs/internal/activity-logging.md
@@ -234,29 +234,30 @@ The session also applies only while `request.user` is still the session's user:
The values come from the authenticated object, never from a request header, so a caller cannot choose them.
Unlike `client`, they are evidence of which credential made a change.
-| `credential_type` | user | `credential_id` |
-| ------------------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
-| `session` | the session user | the session's public id, from `session_public_id` |
-| `personal_api_key` | the key owner | the key id |
-| `oauth` | the token user | the OAuth application UUID |
-| `project_secret_key` | none | the key id |
-| `team_secret_token` | none | none |
-| `id_jag` | the token user | the `client_id` claim |
-| `internal_jwt` | the token user | none |
-| `service_jwt` | none | the audience of the scoped service JWT |
-| `internal_api_secret` | none | none |
-| `scim` | none | the SCIM identity provider config id |
-| `vercel` | none | the Vercel installation id |
-| `partner` | none | the partner's OAuth application UUID when it proved itself with a secret or a signed assertion, none for a public client |
-| `sharing_access_token` | none | the sharing configuration id |
-| `sharing_password` | none | the share password id |
-| `widget_token` | none | none |
-| `billing_service` | none | none |
-| `gateway_agent` | none | the gateway agent's service account id |
-| `export_renderer` | the export's creator | the exported asset id |
-| `webhook` | none | none |
-| `cross_region_signature` | none | none |
-| `unattributed` | the session user, if any | none |
+| `credential_type` | user | `credential_id` |
+| ------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
+| `session` | the session user | the session's public id, from `session_public_id` |
+| `personal_api_key` | the key owner | the key id |
+| `oauth` | the token user | the OAuth application UUID |
+| `project_secret_key` | none | the key id |
+| `team_secret_token` | none | none |
+| `id_jag` | the token user | the `client_id` claim |
+| `oidc_workload` | the owner the token acts as | the workload trust policy id |
+| `internal_jwt` | the token user | none |
+| `service_jwt` | none | the audience of the scoped service JWT |
+| `internal_api_secret` | none | none |
+| `scim` | none | the SCIM identity provider config id |
+| `vercel` | none | the Vercel installation id |
+| `partner` | none | the partner's OAuth application UUID when it proved itself with a secret or a signed assertion, none for a public client |
+| `sharing_access_token` | none | the sharing configuration id |
+| `sharing_password` | none | the share password id |
+| `widget_token` | none | none |
+| `billing_service` | none | none |
+| `gateway_agent` | none | the gateway agent's service account id |
+| `export_renderer` | the export's creator | the exported asset id |
+| `webhook` | none | none |
+| `cross_region_signature` | none | none |
+| `unattributed` | the session user, if any | none |
- A credential without a user clears any user the middleware took from a session cookie. The row has `user=None` and `is_system=True`, and it keeps the credential.
- `impersonated_by_id` holds the staff user behind an impersonated session or an OAuth token minted during impersonation.
diff --git a/frontend/src/scenes/audit-logs/credentialTypeLabel.ts b/frontend/src/scenes/audit-logs/credentialTypeLabel.ts
index 9d1f46de2c29..2a1efd316760 100644
--- a/frontend/src/scenes/audit-logs/credentialTypeLabel.ts
+++ b/frontend/src/scenes/audit-logs/credentialTypeLabel.ts
@@ -9,6 +9,7 @@ const CREDENTIAL_TYPE_LABELS: Record<ActivityLogCredentialTypeEnumApi, string> =
project_secret_key: 'Project secret API key',
team_secret_token: 'Legacy secret key',
id_jag: 'Cross-app access (XAA)',
+ oidc_workload: 'Trusted workload',
scim: 'SCIM',
vercel: 'Vercel',
partner: 'Partner app',
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.py
index ba81e865df84..ac6c0191528d 100644
--- a/posthog/api/id_jag.py
+++ b/posthog/api/id_jag.py
@@ -538,7 +538,7 @@ def _get_signing_key() -> str:
return key
-def _construct_access_token(payload: dict[str, Any]) -> str:
+def _construct_access_token(payload: dict[str, Any], token_type: str = ACCESS_TOKEN_TYPE) -> str:
signing_key = _get_signing_key()
# `kid` matches the thumbprint published in `/.well-known/jwks.json`, so a
# resource server can pick the right key once a rotation publishes more than one.
@@ -546,14 +546,15 @@ def _construct_access_token(payload: dict[str, Any]) -> str:
payload,
signing_key,
algorithm="RS256",
- headers={"typ": ACCESS_TOKEN_TYPE, "kid": jwk_from_pem(signing_key).thumbprint()},
+ headers={"typ": token_type, "kid": jwk_from_pem(signing_key).thumbprint()},
)
-def sign_access_token(payload: dict[str, Any]) -> str:
- """Sign an `at+jwt` access token with the OIDC key. Shared by the ID-JAG token endpoint and
- the billing token PostHog mints server-side, so both verify against the same JWKS."""
- return _construct_access_token(payload)
+def sign_access_token(payload: dict[str, Any], token_type: str = ACCESS_TOKEN_TYPE) -> str:
+ """Sign an access token with the OIDC key. Shared by the ID-JAG token endpoint, the billing
+ token PostHog mints server-side and the workload token exchange, so all verify against the same JWKS.
+ A token type other than `at+jwt` keeps a token from being accepted where an ID-JAG one is."""
+ return _construct_access_token(payload, token_type)
def _parse_scope_list(value: str | list[str] | None) -> list[str]:
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index a470bd3f0b0f..3199d1155d26 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -146,6 +146,7 @@ from posthog.models.user_integration import UserIntegration
from posthog.permissions import (
AccessControlPermission,
APIScopePermission,
+ DenyWorkloadAccessToken,
TeamMemberAccessPermission,
TeamMemberLightManagementPermission,
TeamMemberStrictManagementPermission,
@@ -1602,6 +1603,23 @@ class PersonalConnectionRecentAuthPermission(BasePermission):
return True
+_GITHUB_LINKING_ACTIONS = frozenset(
+ {"github_available_installations", "github_link_existing", "github_oauth_authorize"}
+)
+
+
+class DenyWorkloadTokenGitHubLinking(DenyWorkloadAccessToken):
+ """Linking reuses a GitHub installation from another project, or one the creator's personal GitHub
+ access can see. A workload token is confined to one project and has no personal access to lend."""
+
+ message = "Workload tokens can't link GitHub installations."
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ if getattr(view, "action", None) not in _GITHUB_LINKING_ACTIONS:
+ return True
+ return super().has_permission(request, view)
+
+
class IntegrationFilterSet(filters.FilterSet):
kind = filters.ChoiceFilter(choices=PUBLIC_INTEGRATION_KIND_CHOICES)
@@ -1660,7 +1678,11 @@ class IntegrationViewSet(
"request_access",
"push_tokens",
]
- permission_classes = [IntegrationManagementPermission, PersonalConnectionRecentAuthPermission]
+ permission_classes = [
+ IntegrationManagementPermission,
+ PersonalConnectionRecentAuthPermission,
+ DenyWorkloadTokenGitHubLinking,
+ ]
# LimitOffsetPagination needs a total order, or Postgres can return a row on neither side of a
# page boundary. Clients page this list to find one kind, so a dropped row reads as
# "not configured". Order oldest-first: several clients take the first row of a kind as their
@@ -1701,6 +1723,7 @@ class IntegrationViewSet(
AccessControlPermission(),
TeamMemberAccessPermission(),
PersonalConnectionRecentAuthPermission(),
+ DenyWorkloadTokenGitHubLinking(),
]
# Adding an integration only requires project membership. Every edit and removal uses the
# viewset permission class, including the creator exception for Google account removal.
diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.py
index 8d3efacd1bd8..b5b560e83b54 100644
--- a/posthog/api/oauth/client_assertion.py
+++ b/posthog/api/oauth/client_assertion.py
@@ -82,6 +82,10 @@ class UnknownSigningKeyError(ClientAssertionError):
"""The assertion names a ``kid`` that the client's cached key set does not contain."""
+class JWKSUnavailableError(ClientAssertionError):
+ """The key set could not be fetched, so the assertion was never checked and a retry may succeed."""
+
+
def _request_field(request: Any, name: str) -> str:
"""Read a field from the request body, where RFC 7523 section 2.2 sends it as a form parameter."""
from_body = request.data.get(name) if hasattr(request, "data") else None
@@ -187,7 +191,7 @@ def load_jwks(jwks_uri: str, *, force_refresh: bool = False) -> PyJWKSet:
cached = None if force_refresh else cache.get(cache_key)
if cached is not None:
if cached == "error":
- raise ClientAssertionError("Client keys could not be retrieved")
+ raise JWKSUnavailableError("Client keys could not be retrieved")
return PyJWKSet.from_dict(cached)
try:
@@ -213,7 +217,7 @@ def _fetch_jwks_document(jwks_uri: str) -> dict:
)
except (CIMDFetchError, CIMDValidationError) as e:
logger.warning("client_assertion_jwks_fetch_failed", jwks_uri=jwks_uri, error=str(e))
- raise ClientAssertionError("Client keys could not be retrieved") from e
+ raise JWKSUnavailableError("Client keys could not be retrieved") from e
# Capping the key count keeps a hostile JWKS from making each verification walk a huge
# set. Everything else about the document's shape is PyJWKSet's own validation.
@@ -254,7 +258,7 @@ def _select_key(key_set: PyJWKSet, assertion: str) -> PyJWK:
raise ClientAssertionError("Client assertion must carry a kid when the JWKS holds several keys")
-def _select_key_allowing_rotation(jwks_uri: str, assertion: str) -> PyJWK:
+def select_signing_key(jwks_uri: str, assertion: str) -> PyJWK:
"""Select the assertion's signing key, re-fetching the JWKS once when the key is unknown.
A client that rotates keys signs with the new ``kid`` while our cached copy of its key
@@ -298,7 +302,7 @@ def verify_client_assertion(app: OAuthApplication, assertion: str, *, audiences:
if not app.jwks_uri:
raise ClientAssertionError("This client is not registered for private_key_jwt authentication")
- key = _select_key_allowing_rotation(app.jwks_uri, assertion)
+ key = select_signing_key(app.jwks_uri, assertion)
# The selected key's own algorithm is held to the list too, because PyJWT verifies with it.
if key.algorithm_name not in ASYMMETRIC_SIGNING_ALGORITHMS or not isinstance(
key.key, (RSAPublicKey, EllipticCurvePublicKey)
diff --git a/posthog/api/oauth/metadata.py b/posthog/api/oauth/metadata.py
index c4934aef9aba..ec269c71b8ef 100644
--- a/posthog/api/oauth/metadata.py
+++ b/posthog/api/oauth/metadata.py
@@ -11,6 +11,7 @@ from posthog.api.oauth.claims import OIDC_CLAIMS
from posthog.dataclasses import frozen
from posthog.models.oauth import TokenEndpointAuthMethod
from posthog.scopes import get_oauth_scopes_supported, get_scope_descriptions
+from posthog.workload_identity.token_exchange import TOKEN_EXCHANGE_GRANT_TYPE
type Document = dict[str, object]
@@ -18,6 +19,7 @@ SUPPORTED_GRANT_TYPES = [
"authorization_code",
"refresh_token",
id_jag.JWT_BEARER_GRANT_TYPE,
+ TOKEN_EXCHANGE_GRANT_TYPE,
AbstractApplication.GRANT_DEVICE_CODE,
]
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 729ac648414e..fa64cbcc6b50 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -5821,6 +5821,7 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):
"authorization_code",
"refresh_token",
"urn:ietf:params:oauth:grant-type:jwt-bearer",
+ "urn:ietf:params:oauth:grant-type:token-exchange",
"urn:ietf:params:oauth:grant-type:device_code",
],
)
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 660e6fc8a578..dbe26bc1f05c 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -112,6 +112,7 @@ from posthog.security.url_validation import has_ambiguous_authority
from posthog.user_permissions import UserPermissions
from posthog.utils import absolute_uri, get_instance_region, get_trusted_client_ip, render_template
from posthog.views import login_required
+from posthog.workload_identity import token_exchange as workload_token_exchange
from products.access_control.backend.facade.api import user_organizations_use_access_controls
from products.security.backend.facade.api import access_refused as security_access_refused
@@ -2266,6 +2267,46 @@ class OAuthTokenView(TokenView):
}
)
+ def _handle_token_exchange_grant(self, request) -> JsonResponse:
+ """Workload OIDC token exchange (RFC 8693). A workload has no client registration, so the grant takes
+ no client authentication: the OIDC token, checked against a trust policy, is the only credential."""
+ grant_type = workload_token_exchange.TOKEN_EXCHANGE_GRANT_TYPE
+ try:
+ issued = workload_token_exchange.exchange_workload_token(
+ subject_token=request.POST.get("subject_token") or "",
+ subject_token_type=request.POST.get("subject_token_type") or "",
+ resource=request.POST.get("resource") or "",
+ )
+ except workload_token_exchange.WorkloadExchangeError as e:
+ logger.info("workload_token_exchange_rejected", error_code=e.code.value)
+ self._capture_token_rejected(grant_type, "", e.code.value)
+ return JsonResponse(e.body(), status=e.http_status)
+ except (OperationalError, RedisError) as e:
+ logger.warning("workload_token_exchange_unavailable", error=str(e))
+ return _temporarily_unavailable_response()
+
+ posthoganalytics.capture(
+ distinct_id=f"workload_trust_policy:{issued.policy_id}",
+ event="oauth_token_issued",
+ properties={
+ "grant_type": grant_type,
+ "granted_scope_count": len(issued.scopes),
+ "$process_person_profile": False,
+ **(get_region_info() or {}),
+ },
+ )
+ # RFC 6749 section 5.1: a response that carries a token must not be cached.
+ return JsonResponse(
+ {
+ "access_token": issued.access_token,
+ "issued_token_type": workload_token_exchange.ISSUED_TOKEN_TYPE,
+ "token_type": "Bearer",
+ "expires_in": issued.expires_in_seconds,
+ "scope": " ".join(issued.scopes),
+ },
+ headers={"Cache-Control": "no-store", "Pragma": "no-cache"},
+ )
+
def post(self, request, *args, **kwargs):
if request.content_type == "application/json" and request.body:
try:
@@ -2304,6 +2345,8 @@ class OAuthTokenView(TokenView):
if grant_type == id_jag.JWT_BEARER_GRANT_TYPE:
return self._handle_jwt_bearer_grant(request)
+ if grant_type == workload_token_exchange.TOKEN_EXCHANGE_GRANT_TYPE:
+ return self._handle_token_exchange_grant(request)
# DOT reads `device_code` with a bare subscript, which turns a missing one into a 500.
if grant_type == DEVICE_CODE_GRANT_TYPE and not request.POST.get("device_code"):
diff --git a/posthog/api/posthog_connection.py b/posthog/api/posthog_connection.py
index 8a4664145209..dec63f6e47ff 100644
--- a/posthog/api/posthog_connection.py
+++ b/posthog/api/posthog_connection.py
@@ -43,7 +43,7 @@ from posthog.exceptions import InsufficientScope
from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationRecord
from posthog.models.integration import posthog_connect_base_url
from posthog.oauth_provenance import SANDBOX_ORIGIN_HEADER, is_sandbox_origin_request
-from posthog.permissions import get_authenticator_scopes
+from posthog.permissions import DenyWorkloadAccessToken, get_authenticator_scopes
from posthog.rate_limit import PostHogConnectionForwardThrottle
from posthog.scopes import scopes_covered_by_legacy_fallback
@@ -295,6 +295,8 @@ class PostHogConnectionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
scope_object = "integration"
serializer_class = PostHogConnectionForwardSerializer
+ # A connection replays requests with its creator's own grant, which a workload token must not borrow.
+ permission_classes = [DenyWorkloadAccessToken]
def get_throttles(self) -> list[BaseThrottle]:
if self.action in ("forward", "target"):
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 1ca419f82dd1..94d815590ad5 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -70,6 +70,7 @@ from posthog.api.team.team_serializer import (
EvaluationContextSuggestionRequestSerializer,
EvaluationContextSuggestionResponseSerializer,
TeamSerializer,
+ hide_team_secrets_from_workload_tokens,
)
from posthog.api.team.viewsets import EventIngestionRestrictionSerializer, team_event_ingestion_restrictions_view
from posthog.api.utils import validate_authorized_url_wildcards
@@ -1026,7 +1027,7 @@ class ProjectBackwardCompatSerializer(
if not instance.organization.is_feature_available(AvailableFeature.DATA_COLOR_THEMES):
representation["default_data_theme"] = _default_data_color_theme_id()
hide_secret_api_tokens_from_unscoped_caller(representation, self.context.get("request"))
- return representation
+ return hide_team_secrets_from_workload_tokens(representation, self.context.get("request"))
def get_user_access_level(self, obj: Model | ObjectAccessRef) -> Optional[str]:
if isinstance(obj, ObjectAccessRef):
diff --git a/posthog/api/routing.py b/posthog/api/routing.py
index 5d5b1da1b08c..2f91cd446ad6 100644
--- a/posthog/api/routing.py
+++ b/posthog/api/routing.py
@@ -27,6 +27,7 @@ from posthog.auth import (
SessionAuthentication,
SharingAccessTokenAuthentication,
SharingPasswordProtectedAuthentication,
+ WorkloadAccessTokenAuthentication,
)
from posthog.clickhouse.query_tagging import get_team_query_tags, tag_queries
from posthog.dataclasses import frozen
@@ -387,10 +388,19 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
except NotImplementedError:
pass
else:
+ # A workload token acts as an owner, who may pass a view's own checks, so its policy's scopes and
+ # project are enforced whatever chain the view builds.
+ workload_token_boundary = (
+ [APIScopePermission()]
+ if isinstance(self.request.successful_authenticator, WorkloadAccessTokenAuthentication)
+ else []
+ )
+
# These are tenant boundaries, not authorization levels. Views that shape their own
# permission chain cannot remove them.
return [
*dangerously_defined,
+ *workload_token_boundary,
VerifiedDomainEnforcementPermission(),
MCPAccessPermission(),
ActiveOrganizationPermission(),
@@ -446,6 +456,8 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
# rejected before its own authenticator could run. IDJagAccessTokenAuthentication
# has a strict `typ == "at+jwt"` precheck and cleanly defers for other JWTs.
IDJagAccessTokenAuthentication,
+ # Same reason as ID-JAG: a workload access token is an RS256 JWT that JwtAuthentication would reject.
+ WorkloadAccessTokenAuthentication,
DelegatedPersonalAPIKeyAuthentication,
DelegatedOAuthAccessTokenAuthentication,
JwtAuthentication,
diff --git a/posthog/api/team/live_events.py b/posthog/api/team/live_events.py
index 2abfcf221b98..3a5a4e07d50a 100644
--- a/posthog/api/team/live_events.py
+++ b/posthog/api/team/live_events.py
@@ -6,6 +6,7 @@ from django.conf import settings
from rest_framework.request import Request
+from posthog.auth import WorkloadAccessTokenAuthentication
from posthog.jwt import PosthogJwtAudience, encode_jwt, signing_key_fingerprint
from posthog.models import Team
from posthog.models.data_color_theme import DataColorTheme
@@ -86,7 +87,13 @@ def get_or_mint_live_events_token(team: Team, user_id: int | None) -> str:
def live_events_token_for_request(team: Team, request: Request | None) -> str | None:
if request is None or not request.user.is_authenticated:
return None
- scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
+
+ # A workload token acts as the owner, and this 7-day token would outlive it.
+ authenticator = getattr(request, "successful_authenticator", None)
+ if isinstance(authenticator, WorkloadAccessTokenAuthentication):
+ return None
+
+ scopes = get_authenticator_scopes(authenticator)
if scopes is not None and "*" not in scopes and scopes_not_covered(scopes, ["query:read"]):
return None
return get_or_mint_live_events_token(team, request.user.id)
diff --git a/posthog/api/team/team_serializer.py b/posthog/api/team/team_serializer.py
index 2009c3e479ca..1e7bd9198b58 100644
--- a/posthog/api/team/team_serializer.py
+++ b/posthog/api/team/team_serializer.py
@@ -8,10 +8,12 @@ from django.utils import timezone
from drf_spectacular.utils import extend_schema_field
from opentelemetry import trace
from rest_framework import exceptions, serializers
+from rest_framework.request import Request
from posthog import cloud_utils
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.utils import validate_authorized_url_wildcards
+from posthog.auth import WorkloadAccessTokenAuthentication
from posthog.constants import AvailableFeature
from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import is_impersonated
@@ -61,6 +63,26 @@ from . import (
tracer = trace.get_tracer(__name__)
+# Credentials a project response carries that outlive a workload token: the project secret token and its backup,
+# the heatmaps screenshot secret, and the 7-day live events token. A workload token acts as the organization owner,
+# so without this a workload could read one and keep access after its token expires. The public project token
+# (`api_token`) stays.
+TEAM_SECRET_FIELDS_HIDDEN_FROM_WORKLOAD_TOKENS = (
+ "secret_api_token",
+ "secret_api_token_backup",
+ "heatmaps_screenshot_secret",
+ "live_events_token",
+)
+
+
+def hide_team_secrets_from_workload_tokens(representation: dict[str, Any], request: Request | None) -> dict[str, Any]:
+ # The page-load path passes a plain Django request, which has no authenticator.
+ if isinstance(getattr(request, "successful_authenticator", None), WorkloadAccessTokenAuthentication):
+ for field in TEAM_SECRET_FIELDS_HIDDEN_FROM_WORKLOAD_TOKENS:
+ representation.pop(field, None)
+ return representation
+
+
class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin, UserAccessControlSerializerMixin):
instance: Team | None
_group_types_cache: list[dict[str, Any]] | None = None
@@ -185,7 +207,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
representation["default_data_theme"] = live_events._default_data_color_theme_id()
settings_validation.hide_secret_api_tokens_from_unscoped_caller(representation, self.context.get("request"))
- return representation
+ return hide_team_secrets_from_workload_tokens(representation, self.context.get("request"))
@tracer.start_as_current_span("team_serializer.effective_membership_level")
def get_effective_membership_level(self, team: Team) -> OrganizationMembership.Level | None:
diff --git a/posthog/auth.py b/posthog/auth.py
index 530cbbbfea33..9817ebee51b3 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -24,7 +24,7 @@ from loginas.utils import is_impersonated_session
from opentelemetry import trace
from prometheus_client import Counter
from rest_framework import authentication
-from rest_framework.exceptions import AuthenticationFailed
+from rest_framework.exceptions import AuthenticationFailed, PermissionDenied
from rest_framework.request import Request
from webauthn.helpers import base64url_to_bytes
from zxcvbn import zxcvbn
@@ -32,6 +32,7 @@ from zxcvbn import zxcvbn
from posthog.clickhouse.query_tagging import AccessMethod, tag_authentication, tag_queries
from posthog.constants import AvailableFeature
from posthog.dataclasses import frozen
+from posthog.exceptions import InsufficientScope
from posthog.exceptions_capture import capture_exception
from posthog.helpers.two_factor_session import enforce_two_factor
from posthog.helpers.verified_domain_enforcement import enforce_verified_domain
@@ -63,12 +64,19 @@ from posthog.models.utils import (
hash_key_value,
)
from posthog.models.webauthn_credential import WebauthnCredential
+from posthog.models.workload_trust_policy import (
+ WorkloadTrustPolicy,
+ workload_trust_policies_settings_url,
+ workload_trust_policy_active_cache_key,
+ workload_trust_policy_grantable_scopes,
+ workload_trust_policy_version,
+)
from posthog.passkey import verify_passkey_authentication_response
from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
from posthog.scopes import LEGACY_SCOPE_FALLBACKS
from posthog.shared_link_user import SharedLinkUser
from posthog.synthetic_user import SyntheticUser
-from posthog.utils import get_trusted_client_ip
+from posthog.utils import get_safe_cache, get_trusted_client_ip, safe_cache_set
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.exports.backend.facade.auth import get_export_renderer_asset_context
@@ -616,6 +624,28 @@ class JwtAuthentication(ActivityCredentialMixin, authentication.BaseAuthenticati
return cls.keyword
+def _bearer_token(request: Union[HttpRequest, Request]) -> Optional[str]:
+ auth_header = request.headers.get("authorization")
+ if not auth_header:
+ return None
+ match = re.match(r"^Bearer\s+(\S.+)$", auth_header)
+ return match.group(1).strip() if match else None
+
+
+def _is_signed_jwt_of_type(token: str, token_type: str) -> bool:
+ """Whether a bearer token is a JWT whose `typ` header names one of PostHog's own stateless token
+ types. Personal API key, OAuth and secret token prefixes are reserved for their own backends."""
+ if token.startswith((PERSONAL_API_KEY_PREFIX, OAUTH_ACCESS_TOKEN_PREFIX, SECRET_API_TOKEN_PREFIX)):
+ return False
+ if token.count(".") != 2:
+ return False
+ try:
+ header = jwt.get_unverified_header(token)
+ except jwt.PyJWTError:
+ return False
+ return header.get("typ") == token_type
+
+
@frozen
class VerifiedIdJagAccessToken:
user: User
@@ -647,31 +677,9 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
scopes: list[str]
organization_id: str
- @classmethod
- def _extract_token(cls, request: Union[HttpRequest, Request]) -> Optional[str]:
- auth_header = request.headers.get("authorization")
- if not auth_header:
- return None
- match = re.match(rf"^{cls.keyword}\s+(\S.+)$", auth_header)
- if not match:
- return None
- token = match.group(1).strip()
-
- return token
-
@classmethod
def is_id_jag_token(cls, token: str) -> bool:
- # Personal/OAuth API key prefixes are reserved for those auth backends.
- if token.startswith((PERSONAL_API_KEY_PREFIX, OAUTH_ACCESS_TOKEN_PREFIX, SECRET_API_TOKEN_PREFIX)):
- return False
-
- if token.count(".") != 2:
- return False
- try:
- header = jwt.get_unverified_header(token)
- except jwt.PyJWTError:
- return False
- return header.get("typ") == cls._ID_JAG_ACCESS_TOKEN_TYPE
+ return _is_signed_jwt_of_type(token, cls._ID_JAG_ACCESS_TOKEN_TYPE)
@classmethod
def verify_access_token(cls, token: str) -> VerifiedIdJagAccessToken:
@@ -767,7 +775,7 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
with tracer.start_as_current_span("posthog.auth.id_jag"):
- token = self._extract_token(request)
+ token = _bearer_token(request)
if not token:
return None
if not self.is_id_jag_token(token):
@@ -794,6 +802,184 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
return self.keyword
+# The `typ` header of a workload access token. A distinct value keeps the ID-JAG authenticator, which
+# only takes `at+jwt`, from ever accepting one, and lets this class skip every other JWT.
+WORKLOAD_ACCESS_TOKEN_TYPE = "posthog-workload+jwt"
+WORKLOAD_TRUST_POLICY_ACTIVE_CACHE_SECONDS = 10
+
+
+@frozen
+class VerifiedWorkloadAccessToken:
+ user: User
+ organization_id: str
+ team_id: int
+ policy_id: str
+ policy_name: str
+ scopes: list[str]
+ workload_provider: str
+ workload_subject_name: str
+ # The claims the provider's registry entry records, as the exchange read them from the OIDC token.
+ workload_claims: dict[str, str]
+
+
+class WorkloadAccessTokenAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
+ """
+ Authenticates API requests made with the short-lived token a workload gets by exchanging its
+ provider's OIDC token under a workload trust policy (`posthog.workload_identity.token_exchange`).
+
+ The token is a stateless JWT signed with the OIDC key. It acts as the organization owner the
+ exchange resolved, pinned to one project and to the policy's scope ceiling. Every request checks
+ that the owner is still an owner and that the policy is still enabled and unchanged since the token
+ was minted, so disabling or editing a policy cuts its tokens off within
+ `WORKLOAD_TRUST_POLICY_ACTIVE_CACHE_SECONDS`.
+ """
+
+ keyword = "Bearer"
+ activity_credential_type = "oidc_workload"
+
+ scopes: list[str]
+ organization_id: str
+ team_id: int
+ policy_id: str
+
+ @classmethod
+ def is_workload_token(cls, token: str) -> bool:
+ return _is_signed_jwt_of_type(token, WORKLOAD_ACCESS_TOKEN_TYPE)
+
+ def insufficient_scope_error(self, view: Any, required_scopes: list[str], missing_scopes: list[str]) -> Exception:
+ """What `APIScopePermission` raises when this token lacks a scope. A workload token always gets the
+ standard challenge, because hog reads the scopes from it to tell the user what to add to the
+ trust policy. A scope no policy may grant gets a plain 403 instead, so the user is never told to
+ add something an admin cannot add."""
+ not_grantable = set(missing_scopes) - workload_trust_policy_grantable_scopes()
+ if not_grantable:
+ return PermissionDenied(
+ f"Workload tokens can't use this endpoint: it needs {', '.join(sorted(not_grantable))}, "
+ "which a workload trust policy can't grant."
+ )
+ return InsufficientScope(
+ required_scopes,
+ detail=f"This workload token's trust policy doesn't grant {', '.join(missing_scopes)}. "
+ "Ask an organization admin to add the missing scopes to the policy.",
+ extra={"missing_scopes": missing_scopes, "policy_url": workload_trust_policies_settings_url(self.team_id)},
+ )
+
+ @staticmethod
+ def _active_policy_version(team_id: int, policy_id: str) -> str:
+ """The enabled policy's version, or an empty string when it is disabled or gone."""
+ cache_key = workload_trust_policy_active_cache_key(policy_id)
+ # The cache only spares a query, so a cache outage falls back to the database.
+ cached = get_safe_cache(cache_key)
+ if cached is not None:
+ return cached
+ # The exchange only mints tokens for a project's own team, so the id is already canonical.
+ policy = (
+ WorkloadTrustPolicy.objects.for_team(team_id, canonical=True).filter(pk=policy_id, enabled=True).first()
+ )
+ version = workload_trust_policy_version(policy) if policy else ""
+ safe_cache_set(cache_key, version, WORKLOAD_TRUST_POLICY_ACTIVE_CACHE_SECONDS)
+ return version
+
+ @classmethod
+ def verify_access_token(cls, token: str) -> VerifiedWorkloadAccessToken:
+ verification_keys = get_oidc_verification_keys()
+ site_url = (settings.SITE_URL or "").rstrip("/")
+ if not verification_keys or not site_url:
+ raise AuthenticationFailed(detail="Workload access tokens are not configured on this server.")
+
+ claims = None
+ for verification_key in verification_keys:
+ try:
+ claims = jwt.decode(
+ token,
+ verification_key,
+ algorithms=["RS256"],
+ audience=site_url,
+ issuer=site_url,
+ # The exchange and the API can run on servers whose clocks differ a little.
+ leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,
+ options={
+ "require": ["iss", "aud", "exp", "iat", "user_uuid", "org_id", "team_id", "policy_id", "scope"],
+ },
+ )
+ break
+ except jwt.InvalidSignatureError:
+ continue
+ except jwt.ExpiredSignatureError:
+ raise AuthenticationFailed(detail="Workload access token has expired. Exchange a new OIDC token.")
+ except jwt.PyJWTError:
+ raise AuthenticationFailed(detail="Workload access token is invalid.")
+ if claims is None:
+ raise AuthenticationFailed(detail="Workload access token is invalid.")
+
+ team_id = claims["team_id"]
+ if not isinstance(team_id, int):
+ raise AuthenticationFailed(detail="Workload access token is invalid.")
+ policy_id = str(claims["policy_id"])
+ active_version = cls._active_policy_version(team_id, policy_id)
+ if not active_version or active_version != str(claims.get("policy_version") or ""):
+ raise AuthenticationFailed(
+ detail="The workload trust policy behind this token was changed, disabled or deleted. Exchange a new OIDC token."
+ )
+
+ # The token acts as an owner, so it stops working as soon as that user leaves the
+ # organization or is no longer an owner.
+ membership = (
+ OrganizationMembership.objects.filter(
+ organization_id=str(claims["org_id"]),
+ user__uuid=str(claims["user_uuid"]),
+ user__is_active=True,
+ level=OrganizationMembership.Level.OWNER,
+ )
+ .select_related("user")
+ .first()
+ )
+ if membership is None:
+ raise AuthenticationFailed(
+ detail="The organization owner this workload token acts as is no longer an owner."
+ )
+
+ raw_workload = claims.get("workload")
+ workload = raw_workload if isinstance(raw_workload, dict) else {}
+ raw_recorded_claims = workload.get("claims")
+ recorded_claims = raw_recorded_claims if isinstance(raw_recorded_claims, dict) else {}
+ return VerifiedWorkloadAccessToken(
+ user=membership.user,
+ organization_id=str(claims["org_id"]),
+ team_id=team_id,
+ policy_id=policy_id,
+ policy_name=str(claims.get("policy_name") or ""),
+ scopes=str(claims["scope"]).split(),
+ workload_provider=str(workload.get("provider") or ""),
+ workload_subject_name=str(workload.get("subject_name") or ""),
+ workload_claims={str(key): str(value) for key, value in recorded_claims.items()},
+ )
+
+ def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
+ with tracer.start_as_current_span("posthog.auth.oidc_workload"):
+ token = _bearer_token(request)
+ if not token or not self.is_workload_token(token):
+ return None
+
+ verified = self.verify_access_token(token)
+ refuse_blocked_account(request, verified.user, call_site="oidc_workload_token", impersonated=False)
+ # The owner the token acts as never minted it, so the owner's staff rights don't carry over.
+ verified.user.withhold_staff_rights()
+ self.scopes = verified.scopes
+ self.organization_id = verified.organization_id
+ self.team_id = verified.team_id
+ self.policy_id = verified.policy_id
+
+ tag_authentication(
+ user_id=verified.user.pk, team_id=verified.team_id, access_method=AccessMethod.OIDC_WORKLOAD
+ )
+ self.record_activity_actor(verified.user, verified.policy_id)
+ return verified.user, None
+
+ def authenticate_header(self, request) -> str:
+ return self.keyword
+
+
EXPORT_RENDERER_SCOPES = frozenset({"heatmap:read", "session_recording:read"})
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index e448cc2e3cc3..dbea48b162e9 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -28,6 +28,7 @@ class AccessMethod(StrEnum):
OAUTH = "oauth"
SHARING_TOKEN = "sharing_token"
ID_JAG = "id_jag"
+ OIDC_WORKLOAD = "oidc_workload"
PROJECT_SECRET_API_KEY = "project_secret_api_key"
TEAM_SECRET_TOKEN = "team_secret_token"
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 0a7f96b133fd..8848417edd66 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -85,9 +85,14 @@ class InsufficientScope(PermissionDenied):
them with the scopes it holds, so a check that guards one extra scope can name only that scope.
"""
- def __init__(self, required_scopes: Sequence[str], detail: str | None = None) -> None:
+ def __init__(
+ self, required_scopes: Sequence[str], detail: str | None = None, extra: dict[str, Any] | None = None
+ ) -> None:
super().__init__(detail=detail or f"API key missing required scope '{required_scopes[0]}'")
self.required_scopes = list(required_scopes)
+ # drf-exceptions-hog adds `extra` to the error body, for example the scopes a workload token misses.
+ if extra:
+ self.extra = extra
class Conflict(APIException):
@@ -276,9 +281,15 @@ def exception_handler(exc: Exception, context: ExceptionContext) -> Optional[Res
def _insufficient_scope_challenge(request: object, required_scopes: Sequence[str]) -> str | None:
"""Only tokens from step-up apps get the challenge. Every other caller gets the same 403 without it."""
- from posthog.auth import OAuthAccessTokenAuthentication # noqa: PLC0415 - posthog.auth needs the app registry
+ from posthog.auth import ( # noqa: PLC0415 - posthog.auth needs the app registry
+ OAuthAccessTokenAuthentication,
+ WorkloadAccessTokenAuthentication,
+ )
authenticator = getattr(request, "successful_authenticator", None)
+ # hog reads the scopes from a workload token's challenge to tell the user what to add to the trust policy.
+ if isinstance(authenticator, WorkloadAccessTokenAuthentication):
+ return f'Bearer error="insufficient_scope", scope="{" ".join(required_scopes)}"'
if not isinstance(authenticator, OAuthAccessTokenAuthentication) or not authenticator.access_token.supports_step_up:
return None
# Internal scopes cannot be granted at consent, so a challenge naming one could never succeed.
diff --git a/posthog/jwt.py b/posthog/jwt.py
index 8b4a1c9e2f11..6e41684c9058 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -100,8 +100,22 @@ def get_oidc_verification_keys() -> list[Any]:
in the JWKS). A token minted under a key being rotated out keeps verifying until
it expires, instead of breaking the moment the active key is swapped.
"""
- pems = [
+ pems = (
getattr(settings, "OIDC_RSA_PRIVATE_KEY", None),
*(getattr(settings, "OIDC_RSA_PRIVATE_KEYS_INACTIVE", None) or []),
- ]
- return [serialization.load_pem_private_key(pem.encode(), password=None).public_key() for pem in pems if pem]
+ )
+ return list(_public_keys_from_pems(tuple(pem for pem in pems if pem)))
+
+
+# Parsing a private key validates it, which is slow enough to matter on every request a stateless
+# token authenticates, so the keys are parsed once. The PEMs they came from are kept to notice a change
+# of settings, such as a key rotation or a test that overrides the keys.
+_loaded_public_keys: tuple[tuple[str, ...], tuple[Any, ...]] | None = None
+
+
+def _public_keys_from_pems(pems: tuple[str, ...]) -> tuple[Any, ...]:
+ global _loaded_public_keys
+ if _loaded_public_keys is None or _loaded_public_keys[0] != pems:
+ keys = tuple(serialization.load_pem_private_key(pem.encode(), password=None).public_key() for pem in pems)
+ _loaded_public_keys = (pems, keys)
+ return _loaded_public_keys[1]
diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.py
index b975855c5450..ce9dc06be77f 100644
--- a/posthog/models/activity_logging/utils.py
+++ b/posthog/models/activity_logging/utils.py
@@ -44,6 +44,7 @@ DeclaredCredentialType = Literal[
"project_secret_key",
"team_secret_token",
"id_jag",
+ "oidc_workload",
"internal_jwt",
"service_jwt",
"internal_api_secret",
diff --git a/posthog/models/test/test_user_model.py b/posthog/models/test/test_user_model.py
index fee45b10fbe7..5db6eb6c675f 100644
--- a/posthog/models/test/test_user_model.py
+++ b/posthog/models/test/test_user_model.py
@@ -161,6 +161,19 @@ class TestUser(BaseTest):
self.assertFalse(loaded._original_is_active)
self.assertEqual(loaded._original_is_active, loaded.is_active)
+ def test_saving_a_user_with_withheld_staff_rights_keeps_the_stored_value(self):
+ user = User.objects.create(email="[email protected]", is_staff=True)
+ loaded = User.objects.get(pk=user.pk)
+ loaded.withhold_staff_rights()
+
+ loaded.first_name = "Changed"
+ loaded.save()
+
+ assert loaded.is_staff is False
+ stored = User.objects.get(pk=user.pk)
+ assert stored.is_staff is True
+ assert stored.first_name == "Changed"
+
def test_get_by_natural_key_exact_match(self):
user = User.objects.create(email="[email protected]")
self.assertEqual(User.objects.get_by_natural_key("[email protected]"), user)
diff --git a/posthog/models/user.py b/posthog/models/user.py
index a606855b3881..e17213202287 100644
--- a/posthog/models/user.py
+++ b/posthog/models/user.py
@@ -391,6 +391,25 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignore
instance._original_is_active = instance.is_active
return instance
+ # The stored `is_staff` of an instance whose staff rights are withheld, or None when nothing is withheld.
+ _withheld_is_staff: bool | None = None
+
+ def withhold_staff_rights(self) -> None:
+ """Make this instance act as non-staff without changing the stored value."""
+ self._withheld_is_staff = self.is_staff
+ self.is_staff = False
+
+ def save(self, *args: Any, **kwargs: Any) -> None:
+ if self._withheld_is_staff is None:
+ super().save(*args, **kwargs)
+ return
+ # Write the stored value back, so a save neither drops the person's staff rights nor logs a change.
+ self.is_staff = self._withheld_is_staff
+ try:
+ super().save(*args, **kwargs)
+ finally:
+ self.is_staff = False
+
@property
def is_superuser(self) -> bool: # type: ignore[override]
return self.is_staff
diff --git a/posthog/models/workload_trust_policy.py b/posthog/models/workload_trust_policy.py
index 7a2da3bfbee0..ab2b68b6d9ea 100644
--- a/posthog/models/workload_trust_policy.py
+++ b/posthog/models/workload_trust_policy.py
@@ -2,16 +2,18 @@ from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime, timedelta
+from typing import Any
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
-from django.db import models
+from django.db import models, transaction
from django.utils import timezone
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import UUIDModel
from posthog.scopes import UNPRIVILEGED_SCOPES
+from posthog.utils import safe_cache_delete
# A policy can grant any unprivileged scope except the ones that let a workload token outlive itself or
# widen its own access. Risky scopes that stay grantable carry a warning from `RISKY_SCOPE_WARNINGS`.
@@ -78,6 +80,16 @@ def workload_trust_policy_request_url(team_id: int, request_id: str) -> str:
return f"{settings.SITE_URL}/project/{team_id}/workload-trust-policy-requests/{request_id}"
+def workload_trust_policy_version(policy: WorkloadTrustPolicy) -> str:
+ """Changes on every save, so a token minted before an admin narrowed or disabled the policy stops
+ matching it."""
+ return str(int(policy.updated_at.timestamp() * 1_000_000))
+
+
+def workload_trust_policy_active_cache_key(policy_id: str) -> str:
+ return f"workload_trust_policy_active:{policy_id}"
+
+
class WorkloadTrustPolicy(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
"""Lets a workload, such as a CI job, exchange its OIDC token for a short-lived project token. Azure
calls this a federated identity credential, AWS a role trust policy, Google Cloud a workload identity
@@ -116,6 +128,22 @@ class WorkloadTrustPolicy(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
),
]
+ def save(self, *args: Any, **kwargs: Any) -> None:
+ super().save(*args, **kwargs)
+ self._forget_active_state()
+
+ def delete(self, *args: Any, **kwargs: Any) -> tuple[int, dict[str, int]]:
+ policy_id = str(self.pk)
+ result = super().delete(*args, **kwargs)
+ self._forget_active_state(policy_id)
+ return result
+
+ def _forget_active_state(self, policy_id: str | None = None) -> None:
+ # Workload token authentication caches whether a policy is active. Dropping the entry after the commit
+ # makes a disable or delete take effect on the next request rather than when the entry expires.
+ key = workload_trust_policy_active_cache_key(policy_id or str(self.pk))
+ transaction.on_commit(lambda: safe_cache_delete(key))
+
def __str__(self) -> str:
return f"WorkloadTrustPolicy(team={self.team_id}, name={self.name!r})"
diff --git a/posthog/permissions.py b/posthog/permissions.py
index bb6e5705a092..4056d867bb9a 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -28,6 +28,7 @@ from posthog.auth import (
SharingAccessTokenAuthentication,
SharingPasswordProtectedAuthentication,
TeamSecretTokenAuthentication,
+ WorkloadAccessTokenAuthentication,
is_mcp_request,
)
from posthog.cloud_utils import is_cloud
@@ -745,7 +746,7 @@ def get_authenticator_scopes(authenticator) -> list[str] | None:
return list(authenticator.personal_api_key.scopes or [])
if isinstance(authenticator, OAuthAccessTokenAuthentication):
return str(authenticator.access_token.scope or "").split()
- if isinstance(authenticator, IDJagAccessTokenAuthentication):
+ if isinstance(authenticator, IDJagAccessTokenAuthentication | WorkloadAccessTokenAuthentication):
return list(authenticator.scopes or [])
if isinstance(authenticator, ProjectSecretAPIKeyAuthentication):
return list(authenticator.project_secret_api_key.scopes or [])
@@ -795,6 +796,8 @@ def get_authenticator_client(authenticator) -> dict[str, str]:
return {"credential_type": "project_secret_key", "client_id": "project_secret_key"}
if isinstance(authenticator, IDJagAccessTokenAuthentication):
return {"credential_type": "id_jag", "client_id": getattr(authenticator, "client_id", None) or "id_jag"}
+ if isinstance(authenticator, WorkloadAccessTokenAuthentication):
+ return {"credential_type": "oidc_workload", "client_id": "oidc_workload"}
if authenticator is None or isinstance(authenticator, SessionAuthentication):
return {"credential_type": "session", "client_id": CLIENT_ID_POSTHOG}
return {"credential_type": "other", "client_id": "other"}
@@ -832,6 +835,10 @@ def get_authenticator_scoped_organization_ids(authenticator) -> list[str] | None
# keeps it away from the other organizations the resolved user happens to belong to
# (cross-org confused-deputy defense).
return [authenticator.organization_id]
+ if isinstance(authenticator, WorkloadAccessTokenAuthentication):
+ # A workload token acts as an owner, who belongs to the whole organization. The trust policy only
+ # covers the project the exchange named, so the token is confined to that organization and project.
+ return [authenticator.organization_id]
return None
@@ -846,7 +853,7 @@ def get_authenticator_scoped_team_ids(authenticator) -> list[int] | None:
credential = get_authenticator_user_credential(authenticator)
if credential is not None:
return list(credential.scoped_teams or []) or None
- if isinstance(authenticator, ExportRendererAuthentication):
+ if isinstance(authenticator, ExportRendererAuthentication | WorkloadAccessTokenAuthentication):
return [authenticator.team_id]
return None
@@ -940,6 +947,9 @@ class APIScopePermission(ScopeBasePermission):
if isinstance(authenticator, IDJagAccessTokenAuthentication) and not key_scopes:
self.message = "ID-JAG access token has no scopes and cannot access this resource"
return False
+ if isinstance(authenticator, WorkloadAccessTokenAuthentication) and not key_scopes:
+ self.message = "Workload access token has no scopes and cannot access this resource"
+ return False
if is_psak:
psak_allowed_actions = getattr(view, "psak_allowed_actions", self.psak_allowed_actions)
if self._get_action(request, view) not in psak_allowed_actions:
@@ -977,6 +987,10 @@ class APIScopePermission(ScopeBasePermission):
missing_scopes = scopes_missing_after_legacy_fallback(request, view, key_scopes, required_scopes)
if missing_scopes:
+ # A token type can answer with its own error, such as the policy link a workload token gets.
+ insufficient_scope_error = getattr(type(authenticator), "insufficient_scope_error", None)
+ if insufficient_scope_error is not None:
+ raise insufficient_scope_error(authenticator, view, required_scopes, missing_scopes)
raise InsufficientScope(required_scopes, detail=f"API key missing required scope '{missing_scopes[0]}'")
return True
@@ -1045,6 +1059,7 @@ class APIScopePermission(ScopeBasePermission):
| PersonalAPIKeyAuthentication
| JwtAuthentication
| IDJagAccessTokenAuthentication
+ | WorkloadAccessTokenAuthentication
| ExportRendererAuthentication,
):
raise ValueError("Unexpected authentication type")
@@ -1552,3 +1567,13 @@ class DenyMCPBuiltInAgentOAuth(BasePermission):
def has_permission(self, request: Request, view: APIView) -> bool:
return not is_mcp_built_in_agent_oauth_request(request)
+
+
+class DenyWorkloadAccessToken(BasePermission):
+ """For views that act on a person's own connections to other accounts. A workload token acts as the
+ organization owner without the owner minting it, so it must not reach the owner's connections."""
+
+ message = "Workload tokens can't use this endpoint, because it acts on a person's own connections."
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ return not isinstance(request.successful_authenticator, WorkloadAccessTokenAuthentication)
diff --git a/posthog/workload_identity/test/test_token_exchange.py b/posthog/workload_identity/test/test_token_exchange.py
new file mode 100644
index 000000000000..bfda65f27618
--- /dev/null
+++ b/posthog/workload_identity/test/test_token_exchange.py
@@ -0,0 +1,463 @@
+import json
+import time
+from datetime import timedelta
+from typing import Any
+
+import time_machine
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import override_settings
+from django.utils import timezone
+
+import jwt
+from oauth2_provider.utils import jwk_from_pem
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.oauth.cimd import CIMDFetchError
+from posthog.auth import WorkloadAccessTokenAuthentication
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.user_integration import UserIntegration
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.models.workload_trust_policy import WorkloadTrustPolicy, WorkloadTrustPolicyRequest
+from posthog.settings.utils import generate_rsa_private_key_pem
+from posthog.test.authentication_checks import covers_authentication
+from posthog.workload_identity.test.fixtures import FAKE_WORKLOAD_ISSUER, with_fake_workload_provider
+from posthog.workload_identity.token_exchange import TOKEN_EXCHANGE_GRANT_TYPE
+
+from products.annotations.backend.models import Annotation
+from products.dashboards.backend.models.dashboard_templates import DashboardTemplate
+
+# RSA key generation is slow, so the keys are made once per module.
+_PROVIDER_KEY_PEM = generate_rsa_private_key_pem()
+_OTHER_KEY_PEM = generate_rsa_private_key_pem()
+_POSTHOG_KEY_PEM = generate_rsa_private_key_pem()
+_PROVIDER_KEY_ID = "ci-key-1"
+_SITE_URL = "https://posthog.test"
+
+
+def _jwks() -> dict[str, Any]:
+ public_jwk = json.loads(jwk_from_pem(_PROVIDER_KEY_PEM).export_public())
+ return {"keys": [{**public_jwk, "kid": _PROVIDER_KEY_ID, "alg": "RS256", "use": "sig"}]}
+
+
+def _oidc_token(*, signing_key: str = _PROVIDER_KEY_PEM, **overrides: Any) -> str:
+ now = int(time.time())
+ claims = {
+ "iss": FAKE_WORKLOAD_ISSUER,
+ "aud": _SITE_URL,
+ "iat": now,
+ "exp": now + 300,
+ "repository": "acme/web",
+ "repository_id": "1234",
+ "ref": "refs/heads/main",
+ "environment": "production",
+ "workflow": "deploy.yml",
+ "run_id": "987",
+ "sha": "abc123",
+ **overrides,
+ }
+ claims = {name: value for name, value in claims.items() if value is not None}
+ return jwt.encode(claims, signing_key, algorithm="RS256", headers={"kid": _PROVIDER_KEY_ID})
+
+
+@with_fake_workload_provider()
+@override_settings(SITE_URL=_SITE_URL, OIDC_RSA_PRIVATE_KEY=_POSTHOG_KEY_PEM)
+class TestWorkloadTokenExchange(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ jwks_patcher = patch(
+ "posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(_jwks(), None)
+ )
+ jwks_patcher.start()
+ self.addCleanup(jwks_patcher.stop)
+ self.organization_membership.level = OrganizationMembership.Level.OWNER
+ self.organization_membership.save()
+ self.policy = self._create_policy()
+
+ def _create_policy(self, team: Team | None = None, **overrides: Any) -> WorkloadTrustPolicy:
+ target = team or self.team
+ fields: dict[str, Any] = {
+ "name": "Production deploys",
+ "issuer": FAKE_WORKLOAD_ISSUER,
+ "subject_name": "acme/web",
+ "subject": "1234",
+ "conditions": {"ref": "refs/heads/main"},
+ "scopes": ["annotation:write"],
+ **overrides,
+ }
+ return WorkloadTrustPolicy.objects.for_team(target.id).create(team=target, **fields)
+
+ def _exchange(self, subject_token: str | None = None, **overrides: str) -> Any:
+ self.client.logout()
+ data = {
+ "grant_type": TOKEN_EXCHANGE_GRANT_TYPE,
+ "subject_token": subject_token or _oidc_token(),
+ "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
+ "resource": f"{_SITE_URL}/api/projects/{self.team.id}",
+ **overrides,
+ }
+ return self.client.post("/oauth/token/", data)
+
+ def _access_token(self) -> str:
+ response = self._exchange()
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return response.json()["access_token"]
+
+ def _call(self, method: str, path: str, token: str, data: dict[str, Any] | None = None) -> Any:
+ self.client.logout()
+ return getattr(self.client, method)(path, data or {}, format="json", HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ @covers_authentication(WorkloadAccessTokenAuthentication)
+ def test_token_acts_as_the_oldest_owner_with_the_policy_ceiling(self) -> None:
+ newer_owner = User.objects.create_and_join(
+ self.organization, "[email protected]", None, level=OrganizationMembership.Level.OWNER
+ )
+
+ response = self._exchange()
+ body = response.json()
+ created = self._call(
+ "post",
+ f"/api/projects/{self.team.id}/annotations/",
+ body["access_token"],
+ {"content": "Deployed", "date_marker": "2026-01-01T00:00:00Z", "scope": "project"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, body
+ assert (response["Cache-Control"], response["Pragma"]) == ("no-store", "no-cache")
+ assert body["token_type"] == "Bearer"
+ assert body["issued_token_type"] == "urn:ietf:params:oauth:token-type:access_token"
+ assert body["scope"] == "annotation:write"
+ assert 0 < body["expires_in"] <= 600
+ assert "refresh_token" not in body
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ annotation = Annotation.objects.get(pk=created.json()["id"], team_id=self.team.id)
+ assert annotation.created_by_id == self.user.id != newer_owner.id
+ entry = ActivityLog.objects.filter(scope="Annotation", item_id=str(annotation.pk)).get()
+ assert (entry.credential_type, entry.credential_id) == ("oidc_workload", str(self.policy.pk))
+
+ @parameterized.expand(
+ [
+ ("unknown_issuer", {"iss": "https://token.ci.example.org"}, {}, "workload_issuer_not_allowed"),
+ ("wrong_audience", {"aud": "https://other.example.com"}, {}, "workload_token_invalid"),
+ ("expired", {"exp": int(time.time()) - 120, "iat": int(time.time()) - 600}, {}, "workload_token_invalid"),
+ ("recreated_repository", {"repository_id": "5678"}, {}, "workload_no_matching_policy"),
+ ("renamed_repository", {"repository": "acme/other"}, {}, "workload_no_matching_policy"),
+ ("other_ref", {"ref": "refs/heads/feature"}, {}, "workload_no_matching_policy"),
+ ("missing_condition_claim", {"ref": None}, {}, "workload_no_matching_policy"),
+ ("empty_condition_claim", {"ref": ""}, {}, "workload_no_matching_policy"),
+ ("condition_claim_not_a_string", {"ref": ["refs/heads/main"]}, {}, "workload_no_matching_policy"),
+ ("condition_claim_with_a_nul_character", {"ref": "refs/heads/main\x00"}, {}, "workload_no_matching_policy"),
+ ("empty_subject", {"repository_id": ""}, {}, "workload_token_invalid"),
+ ("missing_subject_name", {"repository": None}, {}, "workload_token_invalid"),
+ (
+ "unknown_project",
+ {},
+ {"resource": f"{_SITE_URL}/api/projects/999999999"},
+ "workload_no_matching_policy",
+ ),
+ ("bad_resource", {}, {"resource": "https://evil.example.com/api/projects/1"}, "workload_invalid_request"),
+ (
+ "unsupported_token_type",
+ {},
+ {"subject_token_type": "urn:ietf:params:oauth:token-type:refresh_token"},
+ "workload_invalid_request",
+ ),
+ ]
+ )
+ def test_exchange_refuses(
+ self, _name: str, claim_overrides: dict[str, Any], request_overrides: dict[str, str], error_code: str
+ ) -> None:
+ response = self._exchange(_oidc_token(**claim_overrides), **request_overrides)
+
+ assert response.status_code >= 400
+ assert response.json()["error_code"] == error_code, response.json()
+ assert response.json()["error_uri"].endswith(f"#{error_code}")
+
+ def test_exchange_asks_for_a_retry_when_the_provider_keys_cannot_be_fetched(self) -> None:
+ cache.clear()
+ with patch(
+ "posthog.api.oauth.client_assertion.fetch_client_json_document",
+ side_effect=CIMDFetchError("connection timed out"),
+ ):
+ response = self._exchange()
+
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE, response.json()
+ assert response.json()["error"] == "temporarily_unavailable"
+ assert response.json()["error_code"] == "workload_provider_unavailable"
+
+ def test_exchange_refuses_a_token_signed_by_another_key(self) -> None:
+ response = self._exchange(_oidc_token(signing_key=_OTHER_KEY_PEM))
+
+ assert response.json()["error_code"] == "workload_token_invalid"
+
+ def test_exchange_matches_only_policies_of_the_named_project(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ self.policy.delete()
+ self._create_policy(team=other_team)
+
+ response = self._exchange()
+
+ assert response.json()["error_code"] == "workload_no_matching_policy"
+
+ def test_an_environment_id_reads_like_a_project_without_a_policy(self) -> None:
+ environment = Team.objects.create(organization=self.organization, project=self.project, name="Staging")
+
+ response = self._exchange(resource=f"{_SITE_URL}/api/projects/{environment.id}")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["error_code"] == "workload_no_matching_policy"
+
+ def test_exchange_points_to_a_pending_request(self) -> None:
+ self.policy.delete()
+ pending = WorkloadTrustPolicyRequest.objects.for_team(self.team.id).create(
+ team=self.team,
+ name="Production deploys",
+ issuer=FAKE_WORKLOAD_ISSUER,
+ subject_name="acme/web",
+ subject="1234",
+ conditions={"ref": "refs/heads/main"},
+ scopes=["annotation:write"],
+ )
+
+ body = self._exchange().json()
+
+ assert body["error_code"] == "workload_policy_request_pending"
+ assert body["approval_url"] == f"{_SITE_URL}/project/{self.team.id}/workload-trust-policy-requests/{pending.pk}"
+
+ @parameterized.expand(
+ [
+ (
+ "more_conditions_win",
+ {"environment": "production", "ref": "refs/heads/main"},
+ {},
+ "error_tracking:write",
+ ),
+ (
+ "a_condition_the_token_fails_never_matches",
+ {"environment": "staging", "ref": "refs/heads/main"},
+ {},
+ "annotation:write",
+ ),
+ (
+ "a_condition_whose_claim_the_token_lacks_never_matches",
+ {"environment": "production", "ref": "refs/heads/main"},
+ {"environment": None},
+ "annotation:write",
+ ),
+ (
+ "a_stored_condition_the_provider_does_not_allow_never_matches",
+ {"ref": "refs/heads/main", "sha": "abc123"},
+ {},
+ "annotation:write",
+ ),
+ ]
+ )
+ def test_the_most_specific_matching_policy_wins(
+ self, _name: str, conditions: dict[str, str], claim_overrides: dict[str, Any], expected_scope: str
+ ) -> None:
+ self._create_policy(conditions=conditions, scopes=["error_tracking:write"])
+
+ body = self._exchange(_oidc_token(**claim_overrides)).json()
+
+ assert body["scope"] == expected_scope, body
+
+ def test_token_never_outlives_the_oidc_token(self) -> None:
+ body = self._exchange(_oidc_token(exp=int(time.time()) + 90)).json()
+
+ assert 0 < body["expires_in"] <= 90
+
+ @parameterized.expand([("policy_disabled",), ("policy_narrowed",), ("policy_deleted",), ("owner_demoted",)])
+ def test_token_stops_working(self, case: str) -> None:
+ token = self._access_token()
+ path = f"/api/projects/{self.team.id}/annotations/"
+ assert self._call("get", path, token).status_code == status.HTTP_200_OK
+
+ with self.captureOnCommitCallbacks(execute=True):
+ if case == "policy_disabled":
+ self.policy.enabled = False
+ self.policy.save()
+ elif case == "policy_narrowed":
+ self.policy.conditions = {"ref": "refs/heads/release"}
+ self.policy.save()
+ elif case == "policy_deleted":
+ self.policy.delete()
+ else:
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ assert self._call("get", path, token).status_code == status.HTTP_401_UNAUTHORIZED
+
+ @parameterized.expand([("expired",), ("signed_by_another_key",)])
+ def test_api_refuses_an_expired_or_forged_token(self, case: str) -> None:
+ token = self._access_token()
+ path = f"/api/projects/{self.team.id}/annotations/"
+
+ if case == "expired":
+ with time_machine.travel(timezone.now() + timedelta(hours=1), tick=False):
+ response = self._call("get", path, token)
+ else:
+ claims = jwt.decode(token, options={"verify_signature": False})
+ forged = jwt.encode(
+ claims, generate_rsa_private_key_pem(), algorithm="RS256", headers=jwt.get_unverified_header(token)
+ )
+ response = self._call("get", path, forged)
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED, response.json()
+
+ def test_token_is_pinned_to_its_project(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_org = Organization.objects.create(name="Other org")
+ foreign_team = Team.objects.create(organization=other_org, name="Foreign")
+ OrganizationMembership.objects.create(
+ organization=other_org, user=self.user, level=OrganizationMembership.Level.OWNER
+ )
+ token = self._access_token()
+
+ same_org = self._call("get", f"/api/projects/{other_team.id}/annotations/", token)
+ other_org_response = self._call("get", f"/api/projects/{foreign_team.id}/annotations/", token)
+ organization_level = self._call("get", f"/api/organizations/{self.organization.id}/members/", token)
+ self.user.is_staff = True
+ self.user.save()
+ with override_settings(CLOUD_DEPLOYMENT="US"):
+ staff_bypass = self._call(
+ "get",
+ f"/api/organizations/{other_org.id}/legal_documents/00000000-0000-0000-0000-000000000000/download/",
+ token,
+ )
+
+ assert same_org.status_code == status.HTTP_403_FORBIDDEN
+ assert other_org_response.status_code == status.HTTP_403_FORBIDDEN
+ assert organization_level.status_code == status.HTTP_403_FORBIDDEN
+ assert staff_bypass.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_missing_scope_gets_the_insufficient_scope_challenge(self) -> None:
+ token = self._access_token()
+
+ response = self._call("get", f"/api/projects/{self.team.id}/insights/", token)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response["WWW-Authenticate"] == 'Bearer error="insufficient_scope", scope="insight:read"'
+ assert response.json()["extra"]["missing_scopes"] == ["insight:read"]
+
+ @parameterized.expand(
+ [
+ ("list_policies", "get", "workload_trust_policies/"),
+ ("list_providers", "get", "workload_trust_policies/providers/"),
+ ("create_policy", "post", "workload_trust_policies/"),
+ ("list_requests", "get", "workload_trust_policy_requests/"),
+ ("create_request", "post", "workload_trust_policy_requests/"),
+ ("approve_request", "post", "workload_trust_policy_requests/00000000-0000-0000-0000-000000000001/approve/"),
+ ]
+ )
+ def test_workload_tokens_cannot_reach_trust_policy_endpoints(self, _name: str, method: str, path: str) -> None:
+ token = self._access_token()
+
+ response = self._call(method, f"/api/projects/{self.team.id}/{path}", token)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert "WWW-Authenticate" not in response
+
+ def test_a_staff_owners_workload_token_does_not_get_the_mcp_registry_staff_tier(self) -> None:
+ self.user.is_staff = True
+ self.user.save()
+ self.policy.scopes = ["mcp_registry:read"]
+ self.policy.save()
+ token = self._access_token()
+
+ with patch(
+ "posthoganalytics.feature_enabled", side_effect=lambda flag_key, *_, **__: flag_key == "mcp-registry"
+ ):
+ response = self._call("get", f"/api/projects/{self.team.id}/mcp_registry/servers/measured_projects/", token)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+ @parameterized.expand(
+ [
+ ("mcp_server_installations", ["project:read"], "get", "mcp_server_installations/"),
+ # The view's own personal API key authenticator rejects the token before the permission runs.
+ (
+ "posthog_connection_forward",
+ ["integration:write", "project:read"],
+ "post",
+ "posthog_connections/1/forward/",
+ ),
+ ("github_link_existing", ["integration:write"], "post", "integrations/github/link_existing/"),
+ ]
+ )
+ def test_workload_tokens_cannot_use_the_owners_own_connections(
+ self, _name: str, scopes: list[str], method: str, path: str
+ ) -> None:
+ self.policy.scopes = scopes
+ self.policy.save()
+ token = self._access_token()
+
+ response = self._call(method, f"/api/environments/{self.team.id}/{path}", token)
+
+ assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN), response.json()
+
+ def test_workload_tokens_see_no_connection_state_in_the_canvas_connector_catalog(self) -> None:
+ UserIntegration.objects.create(
+ user=self.user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="12345",
+ config={"installation_id": "12345", "account": {"type": "User", "name": "octocat"}},
+ sensitive_config={"access_token": "ghs_test", "user_access_token": "ghu_test"},
+ )
+ self.policy.scopes = ["canvas:read"]
+ self.policy.save()
+ token = self._access_token()
+
+ with patch("products.canvas.backend.presentation.views.canvas_connectors_enabled", return_value=True):
+ response = self._call("get", f"/api/projects/{self.team.id}/canvases/connectors/", token)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ github = next(entry for entry in response.json()["connectors"] if entry["provider"] == "github")
+ assert github["connected"] is None
+
+ def test_a_staff_owners_workload_token_cannot_change_global_dashboard_templates(self) -> None:
+ self.user.is_staff = True
+ self.user.save()
+ self.policy.scopes = ["dashboard_template:write"]
+ self.policy.save()
+ template = DashboardTemplate.objects.create(template_name="Global", scope=DashboardTemplate.Scope.GLOBAL)
+ token = self._access_token()
+
+ response = self._call(
+ "patch",
+ f"/api/projects/{self.team.id}/dashboard_templates/{template.id}/",
+ token,
+ {"template_name": "Changed"},
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ template.refresh_from_db()
+ assert template.template_name == "Global"
+
+ def test_project_read_hides_secrets_from_workload_tokens_but_not_personal_api_keys(self) -> None:
+ self.team.secret_api_token = "phs_example_team_secret"
+ self.team.save()
+ self.policy.scopes = ["project:read"]
+ self.policy.save()
+ token = self._access_token()
+ personal_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user, label="pat", secure_value=hash_key_value(personal_key), scopes=["*"]
+ )
+
+ workload_body = self._call("get", f"/api/projects/{self.team.id}/", token).json()
+ pat_body = self._call("get", f"/api/projects/{self.team.id}/", personal_key).json()
+
+ assert workload_body["api_token"] == self.team.api_token
+ assert not {
+ "secret_api_token",
+ "secret_api_token_backup",
+ "heatmaps_screenshot_secret",
+ "live_events_token",
+ } & set(workload_body)
+ assert pat_body["secret_api_token"] == "phs_example_team_secret"
diff --git a/posthog/workload_identity/token_exchange.py b/posthog/workload_identity/token_exchange.py
new file mode 100644
index 000000000000..559450a9c6f2
--- /dev/null
+++ b/posthog/workload_identity/token_exchange.py
@@ -0,0 +1,440 @@
+"""RFC 8693 token exchange: a workload, such as a CI job, trades its provider's OIDC token for a short-lived
+project token. The incoming token is the subject token and PostHog acts as the security token service.
+IETF WIMSE and SPIFFE call the caller a workload.
+
+The workload names the project in `resource`. The exchange verifies the OIDC token against the issuer's
+keys from the workload provider registry, finds the project's trust policy that matches the token's claims,
+and mints a workload access token (`posthog.auth.WorkloadAccessTokenAuthentication`) that acts as the oldest
+owner of the project's organization and carries the policy's whole scope ceiling. No refresh token
+is issued: the workload exchanges again when it needs a new token.
+"""
+
+from __future__ import annotations
+
+import re
+import time
+import uuid
+from dataclasses import field
+from enum import StrEnum
+from typing import Any
+
+from django.conf import settings
+from django.utils import timezone
+
+import jwt
+import structlog
+from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey
+from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
+from jwt import PyJWK
+from rest_framework import status
+
+from posthog.api.id_jag import sign_access_token
+from posthog.api.oauth.client_assertion import ClientAssertionError, JWKSUnavailableError, select_signing_key
+from posthog.auth import WORKLOAD_ACCESS_TOKEN_TYPE
+from posthog.dataclasses import frozen
+from posthog.jwt import ASYMMETRIC_SIGNING_ALGORITHMS
+from posthog.models import OrganizationMembership, Team, User
+from posthog.models.workload_trust_policy import (
+ WorkloadTrustPolicy,
+ WorkloadTrustPolicyRequest,
+ workload_trust_policy_grantable_scopes,
+ workload_trust_policy_request_url,
+ workload_trust_policy_version,
+)
+from posthog.workload_identity.providers import (
+ AudienceCheck,
+ WorkloadClaim,
+ WorkloadProvider,
+ get_supported_workload_providers,
+ get_workload_provider_by_issuer,
+ normalize_issuer,
+)
+
+logger = structlog.get_logger(__name__)
+
+TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
+SUBJECT_TOKEN_TYPES = frozenset({"urn:ietf:params:oauth:token-type:jwt", "urn:ietf:params:oauth:token-type:id_token"})
+ISSUED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"
+
+WORKLOAD_ACCESS_TOKEN_MAX_LIFETIME_SECONDS = 600
+WORKLOAD_TOKEN_CLOCK_SKEW_SECONDS = 30
+WORKLOAD_IDENTITY_DOCS_URL = "https://posthog.com/docs/api/workload-identity"
+
+_RESOURCE_PATH = re.compile(r"^/api/projects/(\d+)/?$")
+
+
+class WorkloadExchangeErrorCode(StrEnum):
+ INVALID_REQUEST = "workload_invalid_request"
+ ISSUER_NOT_ALLOWED = "workload_issuer_not_allowed"
+ TOKEN_INVALID = "workload_token_invalid"
+ NO_MATCHING_POLICY = "workload_no_matching_policy"
+ POLICY_REQUEST_PENDING = "workload_policy_request_pending"
+ NO_USABLE_SCOPES = "workload_no_usable_scopes"
+ NO_OWNER = "workload_no_owner"
+ NOT_CONFIGURED = "workload_not_configured"
+ PROVIDER_UNAVAILABLE = "workload_provider_unavailable"
+
+
+class WorkloadExchangeError(Exception):
+ """A refused exchange. The body follows RFC 6749 section 5.2 and adds a stable `error_code` that hog
+ shows in agent mode, plus fields the error message needs, such as the approval link."""
+
+ def __init__(
+ self,
+ code: WorkloadExchangeErrorCode,
+ description: str,
+ *,
+ oauth_error: str = "invalid_grant",
+ http_status: int = status.HTTP_400_BAD_REQUEST,
+ details: dict[str, Any] | None = None,
+ ) -> None:
+ super().__init__(description)
+ self.code = code
+ self.description = description
+ self.oauth_error = oauth_error
+ self.http_status = http_status
+ self.details = details or {}
+
+ def body(self) -> dict[str, Any]:
+ return {
+ "error": self.oauth_error,
+ "error_description": self.description,
+ "error_code": self.code.value,
+ "error_uri": f"{WORKLOAD_IDENTITY_DOCS_URL}#{self.code.value}",
+ **self.details,
+ }
+
+
+@frozen
+class VerifiedWorkload:
+ """What a verified OIDC token says about the workload, read through its provider's registry entry."""
+
+ subject: str
+ subject_name: str
+ # The token's value for each condition claim the provider allows. A claim the token lacks, or holds
+ # as an empty or non-scalar value, is left out, so a policy that requires it never matches.
+ condition_claims: dict[str, str]
+ # The claims an activity log entry records, with the same rules.
+ recorded_claims: dict[str, str]
+
+ def match_filter(self, issuer: str) -> dict[str, Any]:
+ """The lookup a policy or a pending request must pass to match this workload.
+
+ `conditions <@ token claims` holds only when each stored key is present in the token with the same
+ string value, so a condition can never be skipped, and a token that lacks a condition claim matches
+ nothing that sets it."""
+ return {
+ "issuer": issuer,
+ "subject": self.subject,
+ "subject_name": self.subject_name,
+ "conditions__contained_by": self.condition_claims,
+ }
+
+ def claims_sent(self, provider: WorkloadProvider) -> dict[str, Any]:
+ """The claims an error echoes back, so the caller can see why no policy matched."""
+ return {
+ "provider": provider.key,
+ "subject": self.subject,
+ "subject_name": self.subject_name,
+ "conditions": self.condition_claims,
+ }
+
+
+@frozen
+class IssuedWorkloadAccessToken:
+ access_token: str = field(repr=False)
+ scopes: list[str]
+ expires_in_seconds: int
+ policy_id: str
+
+
+def _not_configured() -> WorkloadExchangeError:
+ return WorkloadExchangeError(
+ WorkloadExchangeErrorCode.NOT_CONFIGURED,
+ "Workload token exchange is not configured on this server.",
+ oauth_error="server_error",
+ http_status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+
+def _site_url() -> str:
+ site_url = (settings.SITE_URL or "").rstrip("/")
+ if not site_url:
+ raise _not_configured()
+ return site_url
+
+
+def _team_id_from_resource(resource: str) -> int:
+ site_url = _site_url()
+ resource = resource.strip()
+ match = _RESOURCE_PATH.match(resource[len(site_url) :]) if resource.startswith(f"{site_url}/") else None
+ if match is None:
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.INVALID_REQUEST,
+ f"Set resource to the project's API URL, for example {site_url}/api/projects/<project id>.",
+ oauth_error="invalid_target",
+ )
+ return int(match.group(1))
+
+
+def _provider_for(subject_token: str) -> WorkloadProvider:
+ try:
+ # The issuer picks which provider's keys verify the token, so it has to be read before the
+ # signature can be checked. Nothing else from this unverified read is trusted: the verified
+ # decode below checks the issuer again.
+ # nosemgrep: python.jwt.security.unverified-jwt-decode.unverified-jwt-decode
+ unverified = jwt.decode(subject_token, options={"verify_signature": False})
+ except jwt.PyJWTError:
+ raise WorkloadExchangeError(WorkloadExchangeErrorCode.TOKEN_INVALID, "subject_token is not a readable JWT.")
+ issuer = str(unverified.get("iss") or "")
+ provider = get_workload_provider_by_issuer(issuer)
+ if provider is None:
+ supported = [provider.name for provider in get_supported_workload_providers()]
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.ISSUER_NOT_ALLOWED,
+ f"PostHog doesn't trust OIDC tokens from issuer {issuer!r}. Only the supported providers are trusted.",
+ details={"issuer": issuer[:255], "supported_providers": supported},
+ )
+ return provider
+
+
+def _claim_string(value: Any) -> str | None:
+ """A claim value as the string a policy compares it with, or None when it can't equal any condition.
+ Policies store only non-empty strings, so an empty, null, list or object claim matches nothing. Postgres
+ refuses a NUL character in text and jsonb, so a value holding one is treated as absent too."""
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, int):
+ return str(value)
+ if isinstance(value, str) and value and "\x00" not in value:
+ return value
+ return None
+
+
+def _claims_by_name(token_claims: dict[str, Any], wanted: tuple[WorkloadClaim, ...]) -> dict[str, str]:
+ values = {claim.name: _claim_string(token_claims.get(claim.name)) for claim in wanted}
+ return {name: value for name, value in values.items() if value is not None}
+
+
+def _required_claim(token_claims: dict[str, Any], claim: WorkloadClaim) -> str:
+ value = _claim_string(token_claims.get(claim.name))
+ if value is None:
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.TOKEN_INVALID,
+ f"The OIDC token has no value for {claim.label} (claim {claim.name}).",
+ )
+ return value
+
+
+def _signing_key(provider: WorkloadProvider, subject_token: str) -> PyJWK:
+ try:
+ key = select_signing_key(provider.jwks_url, subject_token)
+ except JWKSUnavailableError:
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.PROVIDER_UNAVAILABLE,
+ f"Couldn't fetch {provider.name}'s signing keys. Try again in a minute.",
+ oauth_error="temporarily_unavailable",
+ http_status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ except ClientAssertionError as e:
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.TOKEN_INVALID, f"Couldn't find the key that signed the OIDC token: {e}"
+ )
+ if key.algorithm_name not in ASYMMETRIC_SIGNING_ALGORITHMS or not isinstance(
+ key.key, (RSAPublicKey, EllipticCurvePublicKey)
+ ):
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.TOKEN_INVALID, "The OIDC token's signing key isn't an RSA or EC key."
+ )
+ return key
+
+
+def _expected_audience(provider: WorkloadProvider) -> str:
+ match provider.audience_check:
+ case AudienceCheck.SITE_URL:
+ return _site_url()
+ case _:
+ raise _not_configured()
+
+
+def _verify_subject_token(subject_token: str, provider: WorkloadProvider) -> tuple[VerifiedWorkload, int]:
+ """Verify the OIDC token and return what it says about the workload and its expiry, or raise."""
+ key = _signing_key(provider, subject_token)
+ audience = _expected_audience(provider)
+ try:
+ claims = jwt.decode(
+ subject_token,
+ key=key,
+ algorithms=[key.algorithm_name],
+ audience=audience,
+ leeway=WORKLOAD_TOKEN_CLOCK_SKEW_SECONDS,
+ options={
+ "require": ["iss", "aud", "exp", "iat", provider.subject_claim.name, provider.subject_name_claim.name]
+ },
+ )
+ except jwt.ExpiredSignatureError:
+ raise WorkloadExchangeError(WorkloadExchangeErrorCode.TOKEN_INVALID, "The OIDC token has expired.")
+ except jwt.InvalidAudienceError:
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.TOKEN_INVALID,
+ f"The OIDC token's audience must be {audience}. Ask your provider for a token with that audience.",
+ )
+ except jwt.MissingRequiredClaimError as e:
+ raise WorkloadExchangeError(WorkloadExchangeErrorCode.TOKEN_INVALID, f"The OIDC token has no {e.claim} claim.")
+ except jwt.PyJWTError as e:
+ logger.info("workload_token_exchange_rejected", provider=provider.key, error_type=type(e).__name__)
+ raise WorkloadExchangeError(WorkloadExchangeErrorCode.TOKEN_INVALID, "The OIDC token could not be verified.")
+
+ if normalize_issuer(str(claims.get("iss") or "")) != normalize_issuer(provider.issuer):
+ raise WorkloadExchangeError(WorkloadExchangeErrorCode.TOKEN_INVALID, "The OIDC token could not be verified.")
+ expires_at = claims["exp"]
+ if not isinstance(expires_at, int | float):
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.TOKEN_INVALID, "The OIDC token's exp claim must be numeric."
+ )
+
+ workload = VerifiedWorkload(
+ subject=_required_claim(claims, provider.subject_claim),
+ subject_name=_required_claim(claims, provider.subject_name_claim),
+ condition_claims=_claims_by_name(claims, provider.condition_claims),
+ recorded_claims=_claims_by_name(claims, provider.recorded_claims),
+ )
+ return workload, int(expires_at)
+
+
+def find_matching_policy(team_id: int, issuer: str, workload: VerifiedWorkload) -> WorkloadTrustPolicy | None:
+ """The project's enabled policy for this subject whose every condition equals the token's claim.
+
+ When several match, the one with more conditions wins, then the oldest, so adding a broader policy
+ never changes which policy an existing workload runs under.
+ """
+ candidates = WorkloadTrustPolicy.objects.for_team(team_id).filter(**workload.match_filter(issuer), enabled=True)
+ matching = list(candidates)
+ matching.sort(key=lambda policy: (-len(policy.conditions), policy.created_at))
+ return matching[0] if matching else None
+
+
+def _pending_request_for(team_id: int, issuer: str, workload: VerifiedWorkload) -> WorkloadTrustPolicyRequest | None:
+ return (
+ WorkloadTrustPolicyRequest.objects.for_team(team_id)
+ .filter(
+ **workload.match_filter(issuer),
+ status=WorkloadTrustPolicyRequest.Status.PENDING,
+ expires_at__gt=timezone.now(),
+ )
+ .order_by("-created_at")
+ .first()
+ )
+
+
+def oldest_owner(organization_id: Any) -> User | None:
+ membership = (
+ OrganizationMembership.objects.filter(
+ organization_id=organization_id,
+ level=OrganizationMembership.Level.OWNER,
+ user__is_active=True,
+ )
+ .select_related("user")
+ .order_by("joined_at", "id")
+ .first()
+ )
+ return membership.user if membership else None
+
+
+def _sign(payload: dict[str, Any]) -> str:
+ if not getattr(settings, "OIDC_RSA_PRIVATE_KEY", None):
+ raise _not_configured()
+ return sign_access_token(payload, token_type=WORKLOAD_ACCESS_TOKEN_TYPE)
+
+
+def exchange_workload_token(*, subject_token: str, subject_token_type: str, resource: str) -> IssuedWorkloadAccessToken:
+ if not subject_token:
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.INVALID_REQUEST, "subject_token is required.", oauth_error="invalid_request"
+ )
+ if subject_token_type not in SUBJECT_TOKEN_TYPES:
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.INVALID_REQUEST,
+ f"subject_token_type must be one of: {', '.join(sorted(SUBJECT_TOKEN_TYPES))}.",
+ oauth_error="invalid_request",
+ )
+ team_id = _team_id_from_resource(resource)
+ provider = _provider_for(subject_token)
+ workload, oidc_expires_at = _verify_subject_token(subject_token, provider)
+
+ team = Team.objects.select_related("organization").filter(pk=team_id).first()
+ if team is not None and team.project_id != team.id:
+ # Policies live on a project's own team, so an environment id never has one.
+ team = None
+
+ issuer = normalize_issuer(provider.issuer)
+ # A project that doesn't exist, or an environment id, reads like a project without a matching policy,
+ # so the exchange can't be used to find out which ids exist.
+ policy = find_matching_policy(team.id, issuer, workload) if team is not None else None
+ if team is None or policy is None:
+ claims_sent = workload.claims_sent(provider)
+ pending = _pending_request_for(team.id, issuer, workload) if team is not None else None
+ if pending is not None:
+ approval_url = workload_trust_policy_request_url(team_id, str(pending.pk))
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.POLICY_REQUEST_PENDING,
+ f"A workload trust policy for this job is waiting for an admin to approve it: {approval_url}",
+ details={"approval_url": approval_url, "project_id": team_id, "claims": claims_sent},
+ )
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.NO_MATCHING_POLICY,
+ f"No workload trust policy in project {team_id} matches this workload. Run `hog ci setup` to request one.",
+ details={"project_id": team_id, "claims": claims_sent},
+ )
+
+ # Checked again at mint time so a scope that became ungrantable after the policy was saved is never issued.
+ grantable = workload_trust_policy_grantable_scopes()
+ scopes = sorted(scope for scope in policy.scopes if scope in grantable)
+ if not scopes:
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.NO_USABLE_SCOPES,
+ "The matching workload trust policy grants no scopes a workload token can use. Ask an admin to edit it.",
+ details={"policy_id": str(policy.pk)},
+ )
+
+ owner = oldest_owner(team.organization_id)
+ if owner is None:
+ raise WorkloadExchangeError(
+ WorkloadExchangeErrorCode.NO_OWNER,
+ "The project's organization has no active owner for workload tokens to act as.",
+ http_status=status.HTTP_403_FORBIDDEN,
+ oauth_error="access_denied",
+ )
+
+ now = int(time.time())
+ expires_at = min(now + WORKLOAD_ACCESS_TOKEN_MAX_LIFETIME_SECONDS, oidc_expires_at)
+ if expires_at <= now:
+ raise WorkloadExchangeError(WorkloadExchangeErrorCode.TOKEN_INVALID, "The OIDC token has expired.")
+ site_url = _site_url()
+ payload: dict[str, Any] = {
+ "iss": site_url,
+ "aud": site_url,
+ "sub": f"workload_trust_policy:{policy.pk}",
+ "user_uuid": str(owner.uuid),
+ "org_id": str(team.organization_id),
+ "team_id": team.id,
+ "policy_id": str(policy.pk),
+ "policy_name": policy.name,
+ "policy_version": workload_trust_policy_version(policy),
+ "scope": " ".join(scopes),
+ "workload": {
+ "provider": provider.key,
+ "subject": workload.subject,
+ "subject_name": workload.subject_name,
+ "claims": workload.recorded_claims,
+ },
+ "jti": str(uuid.uuid4()),
+ "iat": now,
+ "exp": expires_at,
+ }
+ return IssuedWorkloadAccessToken(
+ access_token=_sign(payload),
+ scopes=scopes,
+ expires_in_seconds=expires_at - now,
+ policy_id=str(policy.pk),
+ )
diff --git a/posthog/workload_identity/trust_policy.py b/posthog/workload_identity/trust_policy.py
index 86e0986a9d32..bb56c3d03c66 100644
--- a/posthog/workload_identity/trust_policy.py
+++ b/posthog/workload_identity/trust_policy.py
@@ -24,7 +24,7 @@ from rest_framework.views import APIView
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
-from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthentication
+from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthentication, WorkloadAccessTokenAuthentication
from posthog.helpers.impersonation import is_impersonated
from posthog.models import OrganizationMembership, Team, User
from posthog.models.oauth import OAuthApplication
@@ -333,6 +333,15 @@ def notify_admins_of_policy_change(
)
+class DenyWorkloadAccessToken(BasePermission):
+ """A workload token can never reach a policy or a request, not even to read, so it can't widen its own policy."""
+
+ message = "Workload tokens can't use workload trust policy endpoints."
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ return not isinstance(request.successful_authenticator, WorkloadAccessTokenAuthentication)
+
+
class NotImpersonatedWritePermission(BasePermission):
"""A policy is a standing credential that acts as the owner, so staff impersonating a member can read
policies but not change them, or ask for them."""
@@ -364,6 +373,7 @@ class WorkloadTrustPolicyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer_class = WorkloadTrustPolicySerializer
lookup_field = "id"
permission_classes = [
+ DenyWorkloadAccessToken,
BrowserSessionWritePermission,
NotImpersonatedWritePermission,
TimeSensitiveActionPermission,
@@ -575,6 +585,7 @@ class WorkloadTrustPolicyRequestViewSet(
serializer_class = WorkloadTrustPolicyRequestSerializer
lookup_field = "id"
permission_classes = [
+ DenyWorkloadAccessToken,
NotImpersonatedWritePermission,
TimeSensitiveActionPermission,
WorkloadTrustPolicyRequestResolutionPermission,
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index b8c25bb13c8a..f2560aacbce8 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -22,7 +22,7 @@ from rest_framework.utils.urls import replace_query_param
from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
-from posthog.auth import OAuthAccessTokenAuthentication
+from posthog.auth import OAuthAccessTokenAuthentication, WorkloadAccessTokenAuthentication
from posthog.event_usage import report_user_action
from posthog.helpers.impersonation import is_impersonated
from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
@@ -1791,8 +1791,11 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
def _connector_actor(self, request: Request) -> User | None:
"""The viewer whose third-party connections a connector call may use.
- A sandbox token acts for an agent, not a viewer, so it gets none."""
- if self._is_sandbox_authenticated(request):
+ A sandbox token acts for an agent, not a viewer, so it gets none. A workload token acts as the
+ organization owner without the owner minting it, so it gets none either."""
+ if self._is_sandbox_authenticated(request) or isinstance(
+ request.successful_authenticator, WorkloadAccessTokenAuthentication
+ ):
return None
return self._request_user()
@@ -1995,7 +1998,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
user = self._connector_actor(request)
if user is None:
return Response(
- {"detail": "Connector calls are made by viewers; sandbox tokens cannot use them."},
+ {"detail": "Connector calls are made by viewers; sandbox and workload tokens cannot use them."},
status=status.HTTP_403_FORBIDDEN,
)
if not canvas_connectors_enabled(self.team.uuid):
diff --git a/products/dashboards/backend/widget_access.py b/products/dashboards/backend/widget_access.py
index cd800ecd87ed..2907183068fd 100644
--- a/products/dashboards/backend/widget_access.py
+++ b/products/dashboards/backend/widget_access.py
@@ -5,7 +5,7 @@ from typing import cast
from rest_framework import exceptions
from rest_framework.request import Request
-from posthog.auth import IDJagAccessTokenAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.permissions import get_authenticator_scopes
from posthog.scopes import APIScopeObject
from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl
@@ -14,23 +14,11 @@ from products.dashboards.backend.widget_catalog import get_widget_product_access
from products.dashboards.backend.widget_registry import WidgetRegistryEntry, get_widget_registry_entry
-def _get_request_api_key_scopes(request: Request) -> list[str] | None:
- authenticator = request.successful_authenticator
- if isinstance(authenticator, PersonalAPIKeyAuthentication):
- return list(authenticator.personal_api_key.scopes or [])
- if isinstance(authenticator, OAuthAccessTokenAuthentication):
- token_scope_string = authenticator.access_token.scope
- return token_scope_string.split() if token_scope_string else []
- if isinstance(authenticator, IDJagAccessTokenAuthentication):
- return list(authenticator.scopes)
- return None
-
-
def get_widget_api_scope_error(
registry_entry: WidgetRegistryEntry,
request: Request,
) -> str | None:
- key_scopes = _get_request_api_key_scopes(request)
+ key_scopes = get_authenticator_scopes(request.successful_authenticator)
if key_scopes is None:
return None
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 115fc5cd727c..ad935fe6ac68 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -32,12 +32,7 @@ from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.tagged_item import TaggedItemViewSetMixin
from posthog.api.utils import action
-from posthog.auth import (
- IDJagAccessTokenAuthentication,
- OAuthAccessTokenAuthentication,
- PersonalAPIKeyAuthentication,
- ProjectSecretAPIKeyAuthentication,
-)
+from posthog.auth import ProjectSecretAPIKeyAuthentication
from posthog.helpers.impersonation import get_original_user_from_session
from posthog.models.activity_logging.activity_log import ActivityLog, get_activity_page
from posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_response
@@ -695,14 +690,8 @@ class EnterpriseExperimentsViewSet(
only experiment:write. Session and other non-token auth aren't scope-limited (gated by
access control instead), mirroring APIScopePermission.
"""
- authenticator = request.successful_authenticator
- if isinstance(authenticator, PersonalAPIKeyAuthentication):
- scopes = authenticator.personal_api_key.scopes or []
- elif isinstance(authenticator, OAuthAccessTokenAuthentication):
- scopes = (authenticator.access_token.scope or "").split()
- elif isinstance(authenticator, IDJagAccessTokenAuthentication):
- scopes = list(authenticator.scopes or [])
- else:
+ scopes = get_authenticator_scopes(request.successful_authenticator)
+ if scopes is None:
return True
return "*" in scopes or "feature_flag:write" in scopes
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index b05418cdc8bd..3e445a983aa0 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -63,6 +63,7 @@ from posthog.auth import (
PersonalAPIKeyAuthentication,
ProjectSecretAPIKeyAuthentication,
TeamSecretTokenAuthentication,
+ WorkloadAccessTokenAuthentication,
)
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.constants import FlagRequestType
@@ -445,6 +446,8 @@ def _scope_audit_identity(authenticator) -> tuple[list[str], str, str | None, st
return scopes, "oauth_access_token", str(raw_id) if raw_id is not None else None, None
if isinstance(authenticator, IDJagAccessTokenAuthentication):
return scopes, "id_jag_access_token", None, None
+ if isinstance(authenticator, WorkloadAccessTokenAuthentication):
+ return scopes, "workload_access_token", authenticator.policy_id, None
psak = authenticator.project_secret_api_key
return scopes, "project_secret_api_key", str(getattr(psak, "id", "")) or None, None
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index ee0fccbddc9d..63311aae687b 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -36,7 +36,7 @@ from posthog.cloud_utils import is_dev_mode
from posthog.event_usage import report_user_action
from posthog.models import User
from posthog.models.scoping.manager import resolve_effective_team_id
-from posthog.permissions import DenyMCPBuiltInAgentOAuth
+from posthog.permissions import DenyMCPBuiltInAgentOAuth, DenyWorkloadAccessToken
from posthog.rate_limit import (
MCPOAuthBurstThrottle,
MCPOAuthRedirectBurstThrottle,
@@ -748,7 +748,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
queryset = MCPServerInstallation.objects.all()
serializer_class = MCPServerInstallationSerializer
lookup_field = "id"
- permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth]
+ permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth, DenyWorkloadAccessToken]
# Installations are user-scoped or shared (safely_get_queryset returns both),
# so write actions don't need project admin access.
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 9ba13f4893b2..87581c500eea 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -896,6 +896,7 @@ export interface WelcomeResponseApi {
* * `project_secret_key` - project_secret_key
* * `team_secret_token` - team_secret_token
* * `id_jag` - id_jag
+ * * `oidc_workload` - oidc_workload
* * `internal_jwt` - internal_jwt
* * `service_jwt` - service_jwt
* * `internal_api_secret` - internal_api_secret
@@ -922,6 +923,7 @@ export const ActivityLogCredentialTypeEnumApi = {
ProjectSecretKey: 'project_secret_key',
TeamSecretToken: 'team_secret_token',
IdJag: 'id_jag',
+ OidcWorkload: 'oidc_workload',
InternalJwt: 'internal_jwt',
ServiceJwt: 'service_jwt',
InternalApiSecret: 'internal_api_secret',
@@ -971,6 +973,7 @@ export interface ActivityLogApi {
* * `project_secret_key` - project_secret_key
* * `team_secret_token` - team_secret_token
* * `id_jag` - id_jag
+ * * `oidc_workload` - oidc_workload
* * `internal_jwt` - internal_jwt
* * `service_jwt` - service_jwt
* * `internal_api_secret` - internal_api_secret
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bbff45726fad..fa67b4ab93a5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -5574,6 +5574,7 @@ export namespace Schemas {
* * `project_secret_key` - project_secret_key
* * `team_secret_token` - team_secret_token
* * `id_jag` - id_jag
+ * * `oidc_workload` - oidc_workload
* * `internal_jwt` - internal_jwt
* * `service_jwt` - service_jwt
* * `internal_api_secret` - internal_api_secret
@@ -5600,6 +5601,7 @@ export namespace Schemas {
ProjectSecretKey: 'project_secret_key',
TeamSecretToken: 'team_secret_token',
IdJag: 'id_jag',
+ OidcWorkload: 'oidc_workload',
InternalJwt: 'internal_jwt',
ServiceJwt: 'service_jwt',
InternalApiSecret: 'internal_api_secret',
@@ -5649,6 +5651,7 @@ export namespace Schemas {
* * `project_secret_key` - project_secret_key
* * `team_secret_token` - team_secret_token
* * `id_jag` - id_jag
+ * * `oidc_workload` - oidc_workload
* * `internal_jwt` - internal_jwt
* * `service_jwt` - service_jwt
* * `internal_api_secret` - internal_api_secret