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(auth): shared machinery for scoped service-to-service JWTs (#82736)

Harley Alexander56d977392310
diff --git a/nodejs/src/cdp/utils/scoped-service-jwt.test.ts b/nodejs/src/cdp/utils/scoped-service-jwt.test.ts
new file mode 100644
index 000000000000..9e533a4d1111
--- /dev/null
+++ b/nodejs/src/cdp/utils/scoped-service-jwt.test.ts
@@ -0,0 +1,92 @@
+import jwt from 'jsonwebtoken'
+
+import { PosthogJwtAudience } from './jwt-utils'
+import { ScopedServiceJwt } from './scoped-service-jwt'
+
+const AUDIENCE = PosthogJwtAudience.WORKFLOWS_RESCHEDULE_PARKED
+const TEST_KEY = 'test-key'
+const NEW_KEY = 'new-key'
+const OLD_KEY = 'old-key'
+const CONTRACT_KEY = 'contract-key'
+
+// Raw jsonwebtoken signer for forging tokens outside ScopedServiceJwt. The key flows through a
+// parameter (mirroring auth.test.ts's mintToken) so semgrep's hardcoded-credential constant
+// propagation doesn't flag the test fixture keys as real secrets.
+const signRaw = (claims: object, key: string, options: jwt.SignOptions): string => jwt.sign(claims, key, options)
+
+describe('ScopedServiceJwt', () => {
+ describe('provisioning', () => {
+ it.each([
+ ['empty string', ''],
+ ['commas only', ',,'],
+ ['whitespace only', ' , '],
+ ])('is disabled and refuses to mint or verify when keys are %s', (_name, keys) => {
+ const scoped = new ScopedServiceJwt(AUDIENCE, keys)
+ expect(scoped.enabled).toBe(false)
+ expect(() => scoped.mint({ team_id: 1 })).toThrow(/no signing key configured/)
+ expect(() => scoped.verify('any-token')).toThrow(/no signing key configured/)
+ })
+ })
+
+ describe('mint and verify', () => {
+ it('round-trips claims and enforces the audience', () => {
+ const scoped = new ScopedServiceJwt(AUDIENCE, TEST_KEY)
+
+ const claims = scoped.verify(scoped.mint({ team_id: 42, ticket_id: 'abc' }))
+
+ expect(claims.team_id).toBe(42)
+ expect(claims.ticket_id).toBe('abc')
+ expect(claims.aud).toBe(AUDIENCE)
+
+ const otherAudience = new ScopedServiceJwt(PosthogJwtAudience.SUBSCRIPTION_PREFERENCES, TEST_KEY)
+ expect(() => otherAudience.verify(scoped.mint({ team_id: 42 }))).toThrow(/audience/)
+ })
+
+ it('signs with the newest key while still verifying tokens from the old key', () => {
+ const oldOnly = new ScopedServiceJwt(AUDIENCE, OLD_KEY)
+ const newOnly = new ScopedServiceJwt(AUDIENCE, NEW_KEY)
+ const rotated = new ScopedServiceJwt(AUDIENCE, `${NEW_KEY},${OLD_KEY}`)
+
+ expect(rotated.verify(oldOnly.mint({ team_id: 1 })).team_id).toBe(1)
+ // A token minted post-rotation must be signed with the new key, or dropping the
+ // old key from the list would invalidate fresh tokens.
+ expect(newOnly.verify(rotated.mint({ team_id: 1 })).team_id).toBe(1)
+ })
+
+ it('trims whitespace around keys to match the Python side', () => {
+ const scoped = new ScopedServiceJwt(AUDIENCE, ` ${NEW_KEY} , ${OLD_KEY} `)
+ expect(new ScopedServiceJwt(AUDIENCE, NEW_KEY).verify(scoped.mint({ team_id: 1 })).team_id).toBe(1)
+ })
+
+ it('rejects a token signed with a different HMAC algorithm even under the right key', () => {
+ const scoped = new ScopedServiceJwt(AUDIENCE, TEST_KEY)
+ const forged = signRaw({ team_id: 1 }, TEST_KEY, {
+ algorithm: 'HS512',
+ audience: AUDIENCE,
+ expiresIn: '5m',
+ })
+ expect(() => scoped.verify(forged)).toThrow(/algorithm/)
+ })
+
+ it('applies the shared 5 minute default ttl', () => {
+ const scoped = new ScopedServiceJwt(AUDIENCE, TEST_KEY)
+ const claims = scoped.verify(scoped.mint({ team_id: 1 }))
+ expect(claims.exp! - claims.iat!).toBe(5 * 60)
+ })
+ })
+
+ describe('cross-language contract (must match posthog/scoped_service_jwt.py)', () => {
+ it('accepts a token built the way the Python minter builds them', () => {
+ // Signed with the raw audience literal and the claim names the Python side emits
+ // (HS256, flat claims, team_id), so drift in either side's contract breaks this.
+ const token = signRaw({ team_id: 123 }, CONTRACT_KEY, {
+ algorithm: 'HS256',
+ audience: 'posthog:workflows:reschedule_parked',
+ expiresIn: '5m',
+ })
+
+ const claims = new ScopedServiceJwt(AUDIENCE, CONTRACT_KEY).verify(token)
+ expect(claims.team_id).toBe(123)
+ })
+ })
+})
diff --git a/nodejs/src/cdp/utils/scoped-service-jwt.ts b/nodejs/src/cdp/utils/scoped-service-jwt.ts
new file mode 100644
index 000000000000..cd04416c4f41
--- /dev/null
+++ b/nodejs/src/cdp/utils/scoped-service-jwt.ts
@@ -0,0 +1,57 @@
+import jwt from 'jsonwebtoken'
+
+import { JWT, PosthogJwtAudience, makeOptionalJwt } from './jwt-utils'
+
+// Mirrors DEFAULT_SERVICE_TOKEN_TTL in posthog/scoped_service_jwt.py.
+const DEFAULT_TTL_SECONDS = 5 * 60
+
+// jsonwebtoken tolerates this much clock skew between minter and verifier.
+const CLOCK_TOLERANCE_SECONDS = 30
+
+/**
+ * One service-to-service auth relationship, Node side. The Python counterpart is
+ * ScopedServiceJwtPurpose in posthog/scoped_service_jwt.py; the audience string and claim
+ * names must match it exactly, since tokens minted here are verified there (and vice versa).
+ *
+ * Construct once per purpose from config, then check `enabled` before minting: an empty key
+ * string means the purpose's secret is not provisioned in this environment, and callers are
+ * expected to fall back to their legacy auth path rather than fail.
+ */
+export class ScopedServiceJwt {
+ private jwt: JWT | null
+ private audience: PosthogJwtAudience
+ private defaultTtlSeconds: number
+
+ constructor(audience: PosthogJwtAudience, commaSeparatedKeys: string, defaultTtlSeconds = DEFAULT_TTL_SECONDS) {
+ // makeOptionalJwt trims entries to match the Python side's get_list, so a key value like
+ // "new, old" produces the same key set in both languages.
+ this.jwt = makeOptionalJwt(commaSeparatedKeys || '')
+ this.audience = audience
+ this.defaultTtlSeconds = defaultTtlSeconds
+ }
+
+ get enabled(): boolean {
+ return this.jwt !== null
+ }
+
+ /** Sign `claims` (e.g. team_id and the target entity's id) with the newest key. */
+ mint(claims: object, ttlSeconds?: number): string {
+ if (!this.jwt) {
+ throw new Error(`Cannot mint service token for ${this.audience}: no signing key configured`)
+ }
+ return this.jwt.sign(claims, this.audience, { expiresIn: ttlSeconds ?? this.defaultTtlSeconds })
+ }
+
+ /** Verify signature, expiry, and audience against the full key set (rotation-safe). */
+ verify(token: string): jwt.JwtPayload {
+ if (!this.jwt) {
+ throw new Error(`Cannot verify service token for ${this.audience}: no signing key configured`)
+ }
+ return this.jwt.verify(token, this.audience, {
+ // Pin HS256 to match the Python minter; don't accept other HMAC variants the
+ // library would otherwise allow.
+ algorithms: ['HS256'],
+ clockTolerance: CLOCK_TOLERANCE_SECONDS,
+ }) as jwt.JwtPayload
+ }
+}
diff --git a/posthog/auth.py b/posthog/auth.py
index 5f9b4256f5c6..3a4045f1613a 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -6,7 +6,7 @@ import logging
import functools
from abc import abstractmethod
from datetime import timedelta
-from typing import TYPE_CHECKING, Any, Optional, TypedDict, Union
+from typing import TYPE_CHECKING, Any, ClassVar, Optional, TypedDict, Union
from urllib.parse import parse_qs, urlparse
from django.apps import apps
@@ -56,6 +56,7 @@ from posthog.models.utils import (
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.passkey import verify_passkey_authentication_response
from posthog.rbac.user_access_control import UserAccessControl
+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
from posthog.shared_link_user import SharedLinkUser
from posthog.synthetic_user import SyntheticUser
@@ -1082,6 +1083,103 @@ class InternalAPIAuthentication(authentication.BaseAuthentication):
return self.keyword
+class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):
+ """DRF authentication for internal routes called by other PostHog services, verifying the
+ scoped per-purpose JWTs of posthog.scoped_service_jwt (the blessed replacement for
+ INTERNAL_API_SECRET). Subclass per purpose:
+
+ class ConversationsTicketJWTAuthentication(ScopedServiceJWTAuthentication):
+ purpose = CONVERSATIONS_TICKETS_PURPOSE
+
+ The request authenticates as a synthetic InternalAPIUser bound to the token's team.
+ When the URL carries a team_id, the token's team_id claim must match it, so a token
+ minted for one team can never read another's data even if both hit the same route.
+
+ require_team=False is for fleet-scoped purposes (cron-style calls with no team in the
+ URL or claims); team-scoped purposes must keep the default so a token without a team
+ claim fails closed instead of authenticating unscoped.
+ """
+
+ purpose: ClassVar[ScopedServiceJwtPurpose]
+ require_team: ClassVar[bool] = True
+
+ def authenticate(self, request: Request) -> Optional[tuple[Any, None]]:
+ header = authentication.get_authorization_header(request).split()
+ # No bearer header: return None (not raise) so the view's other authenticators,
+ # if any, still get their turn.
+ if not header or header[0].lower() != b"bearer":
+ return None
+ if len(header) != 2:
+ raise AuthenticationFailed("Invalid Authorization header.")
+
+ if not self.purpose.enabled():
+ # Fail closed at request time rather than startup: most processes never serve
+ # these routes and never get the secret injected, so a startup check would
+ # wrongly crash them (same reasoning as InternalAPIAuthentication).
+ logger.error(
+ "Scoped service JWT authentication attempted without configured secret",
+ extra={"path": request.path, "settings_name": self.purpose.settings_name},
+ )
+ raise AuthenticationFailed("Service token authentication is not configured.")
+
+ try:
+ token = header[1].decode()
+ except UnicodeDecodeError:
+ # UnicodeDecodeError is a ValueError, so without this clause a non-UTF-8 bearer
+ # value would escape as a 500 instead of a clean auth failure.
+ raise AuthenticationFailed("Invalid Authorization header.")
+
+ try:
+ claims = self.purpose.verify(token)
+ except jwt.PyJWTError:
+ raise AuthenticationFailed("Invalid or expired service token.")
+
+ return self._authenticate_claims(request, claims)
+
+ def _authenticate_claims(self, request: Request, claims: dict[str, Any]) -> tuple[Any, None]:
+ claim_team_id = claims.get("team_id")
+
+ if claim_team_id is None:
+ if self.require_team:
+ raise AuthenticationFailed("Service token is missing its team claim.")
+ return InternalAPIUser(), None
+
+ url_team_id = _team_id_from_request_path(request)
+ if url_team_id is not None and str(claim_team_id) != url_team_id:
+ raise AuthenticationFailed("Service token team does not match the requested team.")
+
+ Team = apps.get_model(app_label="posthog", model_name="Team")
+ try:
+ team = Team.objects.only("id", "organization_id").get(id=claim_team_id)
+ except (Team.DoesNotExist, ValueError, TypeError):
+ raise AuthenticationFailed("Invalid service token team.")
+
+ return InternalAPIUser(current_organization_id=team.organization_id, current_team_id=team.id), None
+
+ def authenticate_header(self, request: Request) -> str:
+ # Without a challenge value DRF renders every AuthenticationFailed from this class as
+ # 403 instead of 401, making a bad or expired service credential read as a permission
+ # failure to the calling service.
+ return "Bearer"
+
+
+def _team_id_from_request_path(request: Request) -> Optional[str]:
+ parser_context = getattr(request, "parser_context", None)
+ if isinstance(parser_context, dict):
+ kwargs = parser_context.get("kwargs")
+ if isinstance(kwargs, dict) and kwargs.get("team_id") is not None:
+ return str(kwargs["team_id"])
+
+ django_request = getattr(request, "_request", request)
+ resolver_match = getattr(django_request, "resolver_match", None)
+ if resolver_match and getattr(resolver_match, "kwargs", None):
+ team_id = resolver_match.kwargs.get("team_id")
+ if team_id is not None:
+ return str(team_id)
+
+ return None
+
+
def session_auth_required(endpoint):
"""
DEPRECATED: Require session authentication for function-based views.
diff --git a/posthog/scoped_service_jwt.py b/posthog/scoped_service_jwt.py
new file mode 100644
index 000000000000..ffe4bb88247f
--- /dev/null
+++ b/posthog/scoped_service_jwt.py
@@ -0,0 +1,71 @@
+"""Scoped JWTs for service-to-service calls.
+
+The blessed alternative to INTERNAL_API_SECRET (see .agents/security.md, "Don't extend
+INTERNAL_API_SECRET to new service-to-service calls"): instead of a stored fleet-wide
+credential, the caller mints a short-lived token pinned to one team and operation, signed
+with a key only that caller/callee pair holds. A leaked token reaches one team for minutes;
+a leaked key reaches one surface, not the fleet.
+
+Each relationship declares a ScopedServiceJwtPurpose (audience + its own settings key) and
+either mints from it (Django as caller) or guards a DRF view with a
+ScopedServiceJWTAuthentication subclass (Django as callee; lives in posthog.auth with the
+other authentication classes). This module must stay importable before the Django app
+registry is ready: modules loaded at startup (e.g. posthog.plugins.plugin_server_api)
+declare purposes at module level, so nothing here may import models or DRF.
+"""
+
+from dataclasses import field
+from datetime import timedelta
+from typing import Any
+
+from django.conf import settings
+
+from posthog.dataclasses import frozen
+from posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt
+
+DEFAULT_SERVICE_TOKEN_TTL = timedelta(minutes=5)
+
+
+@frozen
+class ScopedServiceJwtPurpose:
+ """One caller→callee auth relationship: the audience names the callee surface, and
+ settings_name is the env var holding that pair's dedicated signing keys (comma-separated,
+ newest first, so keys rotate without a coordinated deploy). Never share a key between
+ purposes; the per-purpose key is what keeps a leak contained to one surface.
+ """
+
+ audience: PosthogJwtAudience
+ settings_name: str
+ default_ttl: timedelta = field(default=DEFAULT_SERVICE_TOKEN_TTL)
+
+ def signing_keys(self) -> list[str]:
+ value = getattr(settings, self.settings_name, "") or ""
+ # Settings may hold either the raw comma-separated string (RECORDING_API_JWT_SECRET) or a
+ # list already parsed with get_list at load time (WORKFLOWS_RESCHEDULE_JWT_SECRETS). The
+ # string parse matches get_list, inlined because importing posthog.settings here would pull
+ # the whole settings package into posthog.auth's import graph.
+ if isinstance(value, list | tuple):
+ return [key.strip() for key in value if key and key.strip()]
+ return [key.strip() for key in value.split(",") if key.strip()]
+
+ def enabled(self) -> bool:
+ """False until the purpose's secret is provisioned. Callers use this to fall back to
+ their legacy auth path, so the scheme rolls out per environment without a flag."""
+ return bool(self.signing_keys())
+
+ def mint(self, claims: dict[str, Any], ttl: timedelta | None = None) -> str:
+ """Mint a token carrying `claims` (e.g. team_id and the target entity's id). Signs with
+ the newest key; verifiers try the full set, so rotation never breaks in-flight calls."""
+ keys = self.signing_keys()
+ if not keys:
+ raise RuntimeError(f"{self.settings_name} is not configured")
+ return encode_jwt(claims, ttl or self.default_ttl, self.audience, signing_key=keys[0])
+
+ def verify(self, token: str) -> dict[str, Any]:
+ """Decode and validate signature, expiry, and audience. Raises pyjwt exceptions on bad
+ tokens and RuntimeError when the purpose is unprovisioned (misconfiguration, not a bad
+ token, so callers can distinguish the two)."""
+ keys = self.signing_keys()
+ if not keys:
+ raise RuntimeError(f"{self.settings_name} is not configured")
+ return decode_jwt(token, self.audience, verification_keys=keys)
diff --git a/posthog/test/test_scoped_service_jwt.py b/posthog/test/test_scoped_service_jwt.py
new file mode 100644
index 000000000000..de845d2656cd
--- /dev/null
+++ b/posthog/test/test_scoped_service_jwt.py
@@ -0,0 +1,190 @@
+import json
+import base64
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+from typing import Any, cast
+
+import pytest
+from posthog.test.base import APIBaseTest
+
+from django.test import RequestFactory, override_settings
+
+import jwt as pyjwt
+from parameterized import parameterized
+from rest_framework.exceptions import AuthenticationFailed
+from rest_framework.request import Request
+
+from posthog.auth import ScopedServiceJWTAuthentication
+from posthog.jwt import PosthogJwtAudience
+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
+
+TEST_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.RECORDING_API,
+ settings_name="TEST_SCOPED_SERVICE_JWT_SECRET",
+)
+
+OTHER_AUDIENCE_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.LIVESTREAM,
+ settings_name="TEST_SCOPED_SERVICE_JWT_SECRET",
+)
+
+
+class TeamScopedAuthentication(ScopedServiceJWTAuthentication):
+ purpose = TEST_PURPOSE
+
+
+class FleetScopedAuthentication(ScopedServiceJWTAuthentication):
+ purpose = TEST_PURPOSE
+ require_team = False
+
+
+def _raw_token(
+ key: str, claims: dict, audience: str = PosthogJwtAudience.RECORDING_API.value, algorithm: str = "HS256"
+) -> str:
+ payload = {"aud": audience, "exp": datetime.now(tz=UTC) + timedelta(minutes=5), **claims}
+ return pyjwt.encode(payload, key, algorithm=algorithm)
+
+
+def _b64url(segment: dict) -> str:
+ return base64.urlsafe_b64encode(json.dumps(segment).encode()).rstrip(b"=").decode()
+
+
+# Assembled by hand because encoding alg=none through pyjwt would trip semgrep's none-alg audit
+# rules, and an attacker forging one would not use our signing helpers anyway.
+def _unsigned_alg_none_token(claims: dict, audience: str = PosthogJwtAudience.RECORDING_API.value) -> str:
+ exp = int((datetime.now(tz=UTC) + timedelta(minutes=5)).timestamp())
+ header = {"alg": "none", "typ": "JWT"}
+ payload = {"aud": audience, "exp": exp, **claims}
+ return f"{_b64url(header)}.{_b64url(payload)}."
+
+
+@override_settings(TEST_SCOPED_SERVICE_JWT_SECRET="new-key,old-key")
+class TestScopedServiceJwtPurpose(APIBaseTest):
+ def test_mint_round_trips_claims_and_audience(self):
+ token = TEST_PURPOSE.mint({"team_id": 123, "ticket_id": "abc"})
+
+ claims = TEST_PURPOSE.verify(token)
+
+ assert claims["team_id"] == 123
+ assert claims["ticket_id"] == "abc"
+ assert claims["aud"] == "posthog:recording_api"
+ assert "exp" in claims
+
+ def test_signs_with_newest_key_and_verifies_old_key_tokens(self):
+ minted = TEST_PURPOSE.mint({"team_id": 1})
+ pyjwt.decode(minted, "new-key", audience=TEST_PURPOSE.audience.value, algorithms=["HS256"])
+
+ old_key_token = _raw_token("old-key", {"team_id": 1})
+ assert TEST_PURPOSE.verify(old_key_token)["team_id"] == 1
+
+ def test_wrong_audience_is_rejected(self):
+ token = OTHER_AUDIENCE_PURPOSE.mint({"team_id": 1})
+ with pytest.raises(pyjwt.InvalidAudienceError):
+ TEST_PURPOSE.verify(token)
+
+ @parameterized.expand(
+ [
+ ("alg_none_unsigned", lambda: _unsigned_alg_none_token({"team_id": 1})),
+ ("hs512_signed_with_correct_key", lambda: _raw_token("new-key", {"team_id": 1}, algorithm="HS512")),
+ ]
+ )
+ def test_tokens_not_signed_with_hs256_are_rejected(self, _name, make_token):
+ with pytest.raises(pyjwt.InvalidAlgorithmError):
+ TEST_PURPOSE.verify(make_token())
+
+ @override_settings(TEST_SCOPED_SERVICE_JWT_SECRET=["list-new", "list-old"])
+ def test_list_typed_settings_sign_with_first_and_verify_all(self):
+ minted = TEST_PURPOSE.mint({"team_id": 1})
+ pyjwt.decode(minted, "list-new", audience=TEST_PURPOSE.audience.value, algorithms=["HS256"])
+ assert TEST_PURPOSE.verify(_raw_token("list-old", {"team_id": 1}))["team_id"] == 1
+
+ @override_settings(TEST_SCOPED_SERVICE_JWT_SECRET="")
+ def test_unprovisioned_purpose_is_disabled_and_refuses_to_mint(self):
+ assert TEST_PURPOSE.enabled() is False
+ with pytest.raises(RuntimeError):
+ TEST_PURPOSE.mint({"team_id": 1})
+ with pytest.raises(RuntimeError):
+ TEST_PURPOSE.verify(_raw_token("any-key", {"team_id": 1}))
+
+
+@override_settings(TEST_SCOPED_SERVICE_JWT_SECRET="new-key,old-key")
+class TestScopedServiceJWTAuthentication(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.factory = RequestFactory()
+ self.authentication = TeamScopedAuthentication()
+
+ def _request(self, token: str | None, url_team_id: int | str | None = None) -> Request:
+ if token is not None:
+ django_request = self.factory.get("/internal/endpoint", HTTP_AUTHORIZATION=f"Bearer {token}")
+ else:
+ django_request = self.factory.get("/internal/endpoint")
+ if url_team_id is not None:
+ django_request.resolver_match = cast(Any, SimpleNamespace(kwargs={"team_id": str(url_team_id)}))
+ return Request(django_request) # ty: ignore[invalid-return-type]
+
+ def _authenticate(self, authentication: ScopedServiceJWTAuthentication, request: Request) -> tuple[Any, Any]:
+ result = authentication.authenticate(request)
+ assert result is not None
+ return result
+
+ def test_valid_token_authenticates_as_the_token_team(self):
+ token = TEST_PURPOSE.mint({"team_id": self.team.id})
+
+ user, auth = self._authenticate(self.authentication, self._request(token, url_team_id=self.team.id))
+
+ assert auth is None
+ assert user.is_authenticated
+ assert user.current_team_id == self.team.id
+ assert user.current_organization_id == self.team.organization_id
+
+ def test_token_for_another_team_cannot_reach_the_url_team(self):
+ token = TEST_PURPOSE.mint({"team_id": self.team.id + 1})
+ with pytest.raises(AuthenticationFailed):
+ self.authentication.authenticate(self._request(token, url_team_id=self.team.id))
+
+ @parameterized.expand(
+ [
+ ("expired", lambda self: TEST_PURPOSE.mint({"team_id": self.team.id}, ttl=timedelta(minutes=-1))),
+ ("wrong_audience", lambda self: OTHER_AUDIENCE_PURPOSE.mint({"team_id": self.team.id})),
+ ("wrong_key", lambda self: _raw_token("not-our-key", {"team_id": self.team.id})),
+ ("garbage", lambda self: "not-a-jwt"),
+ ("missing_team_claim", lambda self: TEST_PURPOSE.mint({"op": "read"})),
+ ("nonexistent_team", lambda self: TEST_PURPOSE.mint({"team_id": 999999999})),
+ ]
+ )
+ def test_bad_tokens_are_rejected(self, _name, make_token):
+ with pytest.raises(AuthenticationFailed):
+ self.authentication.authenticate(self._request(make_token(self)))
+
+ def test_request_without_bearer_header_falls_through_to_other_authenticators(self):
+ assert self.authentication.authenticate(self._request(None)) is None
+
+ def test_non_utf8_bearer_value_is_a_clean_auth_failure(self):
+ request = Request(self.factory.get("/internal/endpoint", HTTP_AUTHORIZATION="Bearer \xff\xfe"))
+ with pytest.raises(AuthenticationFailed):
+ self.authentication.authenticate(request)
+
+ def test_failures_send_a_bearer_challenge_so_drf_renders_401_not_403(self):
+ assert self.authentication.authenticate_header(self._request(None)) == "Bearer"
+
+ @override_settings(TEST_SCOPED_SERVICE_JWT_SECRET="")
+ def test_unconfigured_secret_fails_closed(self):
+ token = _raw_token("any-key", {"team_id": self.team.id})
+ with pytest.raises(AuthenticationFailed):
+ self.authentication.authenticate(self._request(token))
+
+ def test_fleet_scoped_purpose_authenticates_without_a_team(self):
+ token = TEST_PURPOSE.mint({"op": "sweep"})
+
+ user, _auth = self._authenticate(FleetScopedAuthentication(), self._request(token))
+
+ assert user.is_authenticated
+ assert user.current_team_id is None
+
+ def test_fleet_scoped_purpose_still_binds_a_team_when_the_claim_is_present(self):
+ token = TEST_PURPOSE.mint({"team_id": self.team.id})
+
+ user, _auth = self._authenticate(FleetScopedAuthentication(), self._request(token))
+
+ assert user.current_team_id == self.team.id