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): add the device authorization grant (#127809)

Rafael Audibert6635f52d9821
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 00ca07c20a34..5adbe0f1b140 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -124,6 +124,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"LogEntry",
"OAuthAccessToken",
"OAuthApplication",
+ "OAuthDeviceGrant",
"OAuthGrant",
"OAuthIDToken",
"OAuthRefreshToken",
@@ -305,6 +306,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"Nonce",
"OAuthAccessToken",
"OAuthApplication",
+ "OAuthDeviceGrant",
"OAuthGrant",
"OAuthIDToken",
"OAuthRefreshToken",
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 6eaaf6ab525a..999fcd898e5e 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -31,6 +31,63 @@ export interface ConnectedAppApi {
is_self_registered: boolean
}
+export interface DeviceApprovalApi {
+ /**
+ * The code the device shows, as the person typed it. Case and dashes don't matter.
+ * @maxLength 20
+ */
+ user_code: string
+ /** The project the token is scoped to. */
+ project_id: number
+}
+
+/**
+ * * `authorized` - Authorized
+ * * `denied` - Denied
+ */
+export type DeviceDecisionEnumApi = (typeof DeviceDecisionEnumApi)[keyof typeof DeviceDecisionEnumApi]
+
+export const DeviceDecisionEnumApi = {
+ Authorized: 'authorized',
+ Denied: 'denied',
+} as const
+
+export interface DeviceDecisionApi {
+ /** The device grant's status after the decision.
+ *
+ * * `authorized` - Authorized
+ * * `denied` - Denied */
+ status: DeviceDecisionEnumApi
+}
+
+export interface DeviceUserCodeApi {
+ /**
+ * The code the device shows, as the person typed it. Case and dashes don't matter.
+ * @maxLength 20
+ */
+ user_code: string
+}
+
+export interface DeviceGrantDetailsApi {
+ /** The code, in the form the device shows it. */
+ user_code: string
+ /** The client that started the device grant. */
+ client_id: string
+ /** The client's display name. */
+ client_name: string
+ /**
+ * The client's logo, if it declared one.
+ * @nullable
+ */
+ logo_uri: string | null
+ /** Whether PostHog has verified the client. */
+ is_verified: boolean
+ /** The scopes the token will carry if the person approves. */
+ scopes: string[]
+ /** When the code expires. */
+ expires_at: string
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 506f944d6d3e..9c8e9e99eee8 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -21,6 +21,10 @@ import type {
DataDeletionRequestCreateApi,
DataDeletionRequestInputApi,
DataDeletionRequestsListParams,
+ DeviceApprovalApi,
+ DeviceDecisionApi,
+ DeviceGrantDetailsApi,
+ DeviceUserCodeApi,
DomainsListParams,
DomainsScimLogsRetrieveParams,
EmojiSearchResponseApi,
@@ -182,6 +186,63 @@ export const oauthConnectedAppsRevokeCreate = async (id: string, options?: Reque
})
}
+export const getOauthDeviceApproveCreateUrl = () => {
+ return `/api/oauth_device/approve/`
+}
+
+/**
+ * Approve a device grant for one project. The token gets the scopes `lookup` showed.
+ */
+export const oauthDeviceApproveCreate = async (
+ deviceApprovalApi: DeviceApprovalApi,
+ options?: RequestInit
+): Promise<DeviceDecisionApi> => {
+ return apiMutator<DeviceDecisionApi>(getOauthDeviceApproveCreateUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(deviceApprovalApi),
+ })
+}
+
+export const getOauthDeviceDenyCreateUrl = () => {
+ return `/api/oauth_device/deny/`
+}
+
+/**
+ * Refuse a device grant, so the client's next poll gets `access_denied`.
+ */
+export const oauthDeviceDenyCreate = async (
+ deviceUserCodeApi: DeviceUserCodeApi,
+ options?: RequestInit
+): Promise<DeviceDecisionApi> => {
+ return apiMutator<DeviceDecisionApi>(getOauthDeviceDenyCreateUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(deviceUserCodeApi),
+ })
+}
+
+export const getOauthDeviceLookupCreateUrl = () => {
+ return `/api/oauth_device/lookup/`
+}
+
+/**
+ * Show what a device code asks for, so the person can check it before approving.
+ */
+export const oauthDeviceLookupCreate = async (
+ deviceUserCodeApi: DeviceUserCodeApi,
+ options?: RequestInit
+): Promise<DeviceGrantDetailsApi> => {
+ return apiMutator<DeviceGrantDetailsApi>(getOauthDeviceLookupCreateUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(deviceUserCodeApi),
+ })
+}
+
export const getCimdVerificationTokensListUrl = (organizationId: string, params?: CimdVerificationTokensListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index ba01c7784d11..2b6007126f2d 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -9,6 +9,43 @@
*/
import * as zod from 'zod'
+/**
+ * Approve a device grant for one project. The token gets the scopes `lookup` showed.
+ */
+export const oauthDeviceApproveCreateBodyUserCodeMax = 20
+
+export const OauthDeviceApproveCreateBody = /* @__PURE__ */ zod.object({
+ user_code: zod
+ .string()
+ .max(oauthDeviceApproveCreateBodyUserCodeMax)
+ .describe("The code the device shows, as the person typed it. Case and dashes don't matter."),
+ project_id: zod.number().describe('The project the token is scoped to.'),
+})
+
+/**
+ * Refuse a device grant, so the client's next poll gets `access_denied`.
+ */
+export const oauthDeviceDenyCreateBodyUserCodeMax = 20
+
+export const OauthDeviceDenyCreateBody = /* @__PURE__ */ zod.object({
+ user_code: zod
+ .string()
+ .max(oauthDeviceDenyCreateBodyUserCodeMax)
+ .describe("The code the device shows, as the person typed it. Case and dashes don't matter."),
+})
+
+/**
+ * Show what a device code asks for, so the person can check it before approving.
+ */
+export const oauthDeviceLookupCreateBodyUserCodeMax = 20
+
+export const OauthDeviceLookupCreateBody = /* @__PURE__ */ zod.object({
+ user_code: zod
+ .string()
+ .max(oauthDeviceLookupCreateBodyUserCodeMax)
+ .describe("The code the device shows, as the person typed it. Case and dashes don't matter."),
+})
+
/**
* Manage CIMD verification tokens for an organization.
*
diff --git a/posthog/api/oauth/__init__.py b/posthog/api/oauth/__init__.py
index 919f842db91a..4f9a37a4c865 100644
--- a/posthog/api/oauth/__init__.py
+++ b/posthog/api/oauth/__init__.py
@@ -7,6 +7,7 @@ from posthog.api.oauth.dcr import (
DCRSustainedThrottle,
DynamicClientRegistrationView,
)
+from posthog.api.oauth.device import OAuthDeviceAuthorizationView, OAuthDeviceViewSet
from posthog.api.oauth.views import (
OAuthAuthorizationSerializer,
OAuthAuthorizationServerMetadataView,
@@ -36,6 +37,8 @@ __all__ = [
"OAuthJwksInfoView",
"OAuthUserInfoView",
"OAuthValidator",
+ "OAuthDeviceAuthorizationView",
+ "OAuthDeviceViewSet",
# dcr
"DCRBurstThrottle",
"DCRSustainedThrottle",
diff --git a/posthog/api/oauth/device.py b/posthog/api/oauth/device.py
new file mode 100644
index 000000000000..5770641141e6
--- /dev/null
+++ b/posthog/api/oauth/device.py
@@ -0,0 +1,544 @@
+"""RFC 8628 device authorization grant.
+
+A client without a browser, such as hog, gets a device code and a user code from
+`/oauth/device-authorization`. The person opens the approval page and enters or confirms the user code.
+Then the person selects a project and approves. The client polls `/oauth/token` with the device code.
+It gets a token for that project, with the scopes that the client asked for at the start.
+
+django-oauth-toolkit supplies the grant, but its token path is not safe:
+- It takes the scopes from the poll request.
+- It does not check expiry.
+- It does not bind the device code to the client that started the grant.
+- It lets a client use an approved code again.
+The token path in this module prevents each of these.
+"""
+
+import json
+import base64
+import hashlib
+import secrets
+from datetime import timedelta
+from typing import Any, cast
+from urllib.parse import unquote_plus
+
+from django.conf import settings
+from django.core.cache import cache
+from django.db import models, transaction
+from django.http import HttpRequest, HttpResponse, JsonResponse
+from django.utils import timezone
+from django.utils.decorators import method_decorator
+from django.views.decorators.csrf import csrf_exempt
+
+import structlog
+import posthoganalytics
+from drf_spectacular.utils import extend_schema
+from oauth2_provider.models import AbstractApplication
+from oauth2_provider.settings import oauth2_settings
+from oauth2_provider.views.device import DeviceAuthorizationView
+from oauthlib.common import Request as OAuthlibRequest
+from oauthlib.oauth2 import DeviceApplicationServer
+from oauthlib.oauth2.rfc6749 import errors as rfc6749_errors
+from oauthlib.oauth2.rfc8628 import errors as rfc8628_errors
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.throttling import UserRateThrottle
+
+from posthog.accessible_teams import AccessibleTeams, CredentialScopeDenied
+from posthog.api.oauth.client_assertion import resolve_client_assertion
+from posthog.auth import SessionAuthentication
+from posthog.helpers.two_factor_session import missing_two_factor_step
+from posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR
+from posthog.models import Team, User
+from posthog.models.oauth import OAuthApplication, OAuthDeviceGrant
+from posthog.models.organization_domain import OrganizationDomain
+from posthog.rate_limit import IPThrottle
+from posthog.scopes import clamp_scopes_to_ceiling, resolve_requested_scopes
+
+logger = structlog.get_logger(__name__)
+
+DEVICE_CODE_GRANT_TYPE = AbstractApplication.GRANT_DEVICE_CODE
+# The token endpoint's answers while the person hasn't decided yet (RFC 8628 section 3.5).
+DEVICE_POLL_WAITING_ERRORS = frozenset({"authorization_pending", "slow_down"})
+
+# RFC 8628 section 6.1: consonants only, so a code never spells a word or mixes up look-alikes.
+USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ"
+USER_CODE_LENGTH = 8
+
+# A poll that arrives this much earlier than the interval still counts as on time, so network
+# jitter doesn't earn a well-behaved client a slow_down.
+POLL_INTERVAL_TOLERANCE = timedelta(seconds=1)
+# RFC 8628 section 3.5: each `slow_down` adds 5 seconds to the interval the client must keep.
+SLOW_DOWN_INTERVAL_STEP = 5
+MAX_POLL_INTERVAL = 60
+
+# `OAuthApplication.allows_grant_type` refuses an unverified device client. This says why.
+UNVERIFIED_CLIENT_DESCRIPTION = (
+ "PostHog hasn't verified this app. Device login only works for apps PostHog has verified, "
+ "which are PostHog's own apps."
+)
+
+
+def generate_user_code() -> str:
+ code = "".join(secrets.choice(USER_CODE_ALPHABET) for _ in range(USER_CODE_LENGTH))
+ return f"{code[:4]}-{code[4:]}"
+
+
+def normalize_user_code(raw: str) -> str:
+ """Return the stored form of a code that a person typed: upper case, with the dash in its usual position."""
+ code = "".join(character for character in raw.upper() if character.isalnum())
+ return f"{code[:4]}-{code[4:]}" if len(code) == USER_CODE_LENGTH else code
+
+
+def verification_uri() -> str:
+ return f"{settings.SITE_URL}/device"
+
+
+def resolve_device_scopes(raw_scope: str | None, application: OAuthApplication) -> list[str]:
+ """Return the scopes that a device grant asks the person to approve.
+
+ The device grant does not accept `*`, which is different from `/authorize`.
+ The result always includes the application's required scopes. The device grant has no consent form,
+ so the person cannot remove them.
+ """
+ requested = resolve_requested_scopes((raw_scope or "").split(), application.ceiling_scopes)
+ return sorted({*requested, *(scope for scope in application.required_scopes if ":" in scope)})
+
+
+def _device_grant(request: OAuthlibRequest) -> OAuthDeviceGrant:
+ grant = getattr(request, "device_grant", None)
+ if not isinstance(grant, OAuthDeviceGrant):
+ raise rfc6749_errors.InvalidGrantError(request=request)
+ return grant
+
+
+def load_device_grant(request: OAuthlibRequest) -> None:
+ """oauthlib pre-token hook: copy the approved user and project onto the token request.
+
+ The token view locks the grant first, and checks that it is approved and not expired.
+ `_get_scoped_teams_and_organizations` reads the project from these request attributes.
+ """
+ device_code = getattr(request, "device_code", None)
+ grant = (
+ OAuthDeviceGrant.objects.select_related("user")
+ .filter(device_code=device_code, status=OAuthDeviceGrant.AUTHORIZED)
+ .first()
+ )
+ if grant is None or grant.user is None:
+ raise rfc6749_errors.InvalidGrantError(request=request)
+ request.device_grant = grant
+ request.user = grant.user
+ request.scoped_teams = list(grant.scoped_teams or [])
+ request.scoped_organizations = []
+
+
+def apply_device_grant(request: OAuthlibRequest) -> None:
+ """oauthlib post-token hook. It runs after the generic scope check.
+
+ Only the client that started the device grant can redeem it.
+ The token gets the scopes that the person approved, clamped to the client's current ceiling.
+ The `scope` parameter of the poll request has no effect.
+ """
+ grant = _device_grant(request)
+ if request.client.client_id != grant.client_id:
+ raise rfc6749_errors.InvalidGrantError(request=request)
+ request.scopes = clamp_scopes_to_ceiling(set((grant.scope or "").split()), request.client.ceiling_scopes)
+
+
+def token_server_kwargs() -> dict[str, Any]:
+ """Return the server kwargs for the token endpoint. They make the device code grant run the hooks above."""
+ return {
+ **oauth2_settings.server_kwargs,
+ "pre_token": [load_device_grant],
+ "post_token": [apply_device_grant],
+ }
+
+
+def _error_response(error: rfc6749_errors.OAuth2Error) -> JsonResponse:
+ return JsonResponse(json.loads(error.json), status=error.status_code)
+
+
+def _presented_client_id(request: HttpRequest) -> str | None:
+ """Return the client_id of a request. It can be in the body, in a client assertion, or in HTTP Basic auth.
+
+ Basic auth form-encodes the client_id (RFC 6749 section 2.3.1), so the colons in a CIMD URL arrive escaped.
+ This function decodes it in the same way as the toolkit.
+ """
+ if client_id := request.POST.get("client_id"):
+ return client_id
+ assertion = resolve_client_assertion(
+ request.POST.get("client_assertion", ""), request.POST.get("client_assertion_type", ""), ""
+ )
+ if assertion is not None:
+ return assertion.client_id
+ scheme, _, credentials = request.headers.get("Authorization", "").partition(" ")
+ if scheme.lower() != "basic":
+ return None
+ try:
+ return unquote_plus(base64.b64decode(credentials).decode().partition(":")[0]) or None
+ except (ValueError, UnicodeDecodeError):
+ return None
+
+
+def _pending_poll_error(grant: OAuthDeviceGrant) -> rfc6749_errors.OAuth2Error:
+ now = timezone.now()
+ too_early = grant.last_checked and now - grant.last_checked < timedelta(seconds=grant.interval) - (
+ POLL_INTERVAL_TOLERANCE
+ )
+ # `last_checked` is auto_now, so saving it records this poll.
+ if not too_early:
+ grant.save(update_fields=["last_checked"])
+ return rfc8628_errors.AuthorizationPendingError()
+ grant.interval = min(grant.interval + SLOW_DOWN_INTERVAL_STEP, MAX_POLL_INTERVAL)
+ grant.save(update_fields=["last_checked", "interval"])
+ return rfc8628_errors.SlowDownError()
+
+
+def device_token_response(create_token_response: Any, request: HttpRequest, device_code: str) -> HttpResponse:
+ """Return the token endpoint's response to a device code poll.
+
+ The grant row stays locked until the token exists and the grant is deleted.
+ Thus two polls cannot redeem one approval.
+ An app-wide session revoke deletes device grants first. Thus it either waits for this token and
+ revokes it, or deletes the grant before the token exists.
+ """
+ # The token endpoint needs no login, so this caps the row locks and writes one device code can
+ # cause at one per second, however fast its holder polls. The client is part of the key, so
+ # another client polling the same code can't use up the real client's second.
+ poller = f"{_presented_client_id(request) or ''}\n{device_code}"
+ poll_key = f"oauth_device_poll:{hashlib.sha256(poller.encode()).hexdigest()}"
+ if not cache.add(poll_key, True, timeout=1):
+ return _error_response(rfc8628_errors.SlowDownError())
+ with transaction.atomic():
+ grant = OAuthDeviceGrant.objects.select_for_update().filter(device_code=device_code).first()
+ # Checked before any status answer, so a poll by another client neither learns the status
+ # nor moves `last_checked`. The post-token hook checks the authenticated client again.
+ if grant is None or _presented_client_id(request) != grant.client_id:
+ return _error_response(rfc6749_errors.InvalidGrantError(description="The device code is not valid."))
+ if grant.status in (OAuthDeviceGrant.AUTHORIZATION_PENDING, OAuthDeviceGrant.AUTHORIZED) and (
+ timezone.now() >= grant.expires
+ ):
+ grant.status = OAuthDeviceGrant.EXPIRED
+ grant.save(update_fields=["status"])
+ if grant.status == OAuthDeviceGrant.EXPIRED:
+ return _error_response(rfc8628_errors.ExpiredTokenError())
+ if grant.status == OAuthDeviceGrant.DENIED:
+ return _error_response(rfc8628_errors.AccessDenied())
+ if grant.status == OAuthDeviceGrant.AUTHORIZATION_PENDING:
+ return _error_response(_pending_poll_error(grant))
+
+ _url, headers, body, status_code = create_token_response(request)
+ if status_code == 200:
+ grant.delete()
+
+ response = HttpResponse(content=body, status=status_code, content_type="application/json")
+ for key, value in headers.items():
+ response[key] = value
+ return response
+
+
+@method_decorator(csrf_exempt, name="dispatch")
+class OAuthDeviceAuthorizationView(DeviceAuthorizationView):
+ """`POST /oauth/device-authorization`: start a device grant (RFC 8628 section 3.1).
+
+ oauthlib checks the client and creates the codes. This view adds two checks that oauthlib does not do:
+ - The client must be registered for the device grant.
+ - The requested scopes are clamped to the client's ceiling and stored.
+ Thus the token can only get the scopes that the person saw and approved.
+ """
+
+ @classmethod
+ def get_server(cls) -> DeviceApplicationServer:
+ return DeviceApplicationServer(
+ cls.get_validator_class()(),
+ verification_uri=verification_uri(),
+ verification_uri_complete=f"{verification_uri()}?code={{user_code}}",
+ interval=oauth2_settings.DEVICE_FLOW_INTERVAL,
+ user_code_generator=generate_user_code,
+ )
+
+ def post(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
+ # Late import: the views module imports this one for the token endpoint.
+ from posthog.api.oauth.views import cimd_creation_throttled # noqa: PLC0415
+
+ # This endpoint needs no login and writes a row per call, so it is limited per IP. A CIMD
+ # client_id also makes PostHog fetch a document, so new CIMD clients get the same per-IP
+ # limit as on /oauth/authorize.
+ # The IP throttles read only `request.META`, which a Django request has too.
+ drf_request = cast(Request, request)
+ if not all(throttle().allow_request(drf_request, self) for throttle in DEVICE_AUTHORIZATION_THROTTLE_CLASSES):
+ return JsonResponse(
+ {"error": "slow_down", "error_description": "Too many login attempts. Try again in a minute."},
+ status=429,
+ )
+ if request.GET:
+ # oauthlib also reads parameters from the query string. A client_id there would skip the
+ # CIMD creation limit below, which reads only the body and the Authorization header.
+ return _error_response(
+ rfc6749_errors.InvalidRequestError(description="URL query parameters are not allowed.")
+ )
+ client_id = _presented_client_id(request) or ""
+ if client_id and "client_id" not in request.POST:
+ # RFC 8628 section 3.1 needs no client_id in the body from a client that authenticates,
+ # but oauthlib reads it only from there.
+ post = request.POST.copy()
+ post["client_id"] = client_id
+ request.POST = post # type: ignore[assignment] # ty: ignore[invalid-assignment]
+ if cimd_creation_throttled(request, self, client_id):
+ return JsonResponse(
+ {"error": "invalid_client", "error_description": "Too many new client registrations. Try again later."},
+ status=400,
+ )
+ headers, body, status_code = self.create_device_authorization_response(request)
+ if status_code != 200:
+ return JsonResponse(data=json.loads(body), status=status_code, headers=headers)
+
+ response = cast(dict[str, Any], body)
+ application = OAuthApplication.objects.filter(client_id=client_id).first()
+ if (
+ application is not None
+ and application.authorization_grant_type == AbstractApplication.GRANT_DEVICE_CODE
+ and not application.is_verified
+ ):
+ return _error_response(rfc6749_errors.UnauthorizedClientError(description=UNVERIFIED_CLIENT_DESCRIPTION))
+ if application is None or not application.allows_grant_type(AbstractApplication.GRANT_DEVICE_CODE):
+ return _error_response(
+ rfc6749_errors.UnauthorizedClientError(description="This client can't use the device grant.")
+ )
+
+ OAuthDeviceGrant.objects.create(
+ client_id=application.client_id,
+ device_code=response["device_code"],
+ user_code=response["user_code"],
+ scope=" ".join(resolve_device_scopes(request.POST.get("scope"), application)),
+ interval=response["interval"],
+ expires=timezone.now() + timedelta(seconds=response["expires_in"]),
+ )
+ return JsonResponse(data=response, status=status_code, headers={**headers, "Cache-Control": "no-store"})
+
+
+class OAuthDeviceAuthorizationBurstThrottle(IPThrottle):
+ scope = "oauth_device_authorization_burst"
+ rate = "5/minute"
+
+
+class OAuthDeviceAuthorizationSustainedThrottle(IPThrottle):
+ scope = "oauth_device_authorization_sustained"
+ rate = "30/hour"
+
+
+DEVICE_AUTHORIZATION_THROTTLE_CLASSES = (
+ OAuthDeviceAuthorizationBurstThrottle,
+ OAuthDeviceAuthorizationSustainedThrottle,
+)
+
+
+class OAuthDeviceCodeBurstThrottle(UserRateThrottle):
+ # A person enters a code once or twice per login, so anything faster is guessing.
+ scope = "oauth_device_code_burst"
+ rate = "10/minute"
+
+
+class OAuthDeviceCodeSustainedThrottle(UserRateThrottle):
+ scope = "oauth_device_code_sustained"
+ rate = "50/hour"
+
+
+class DeviceUserCodeSerializer(serializers.Serializer):
+ user_code = serializers.CharField(
+ max_length=20, help_text="The code the device shows, as the person typed it. Case and dashes don't matter."
+ )
+
+
+class DeviceApprovalSerializer(DeviceUserCodeSerializer):
+ project_id = serializers.IntegerField(help_text="The project the token is scoped to.")
+
+
+class DeviceGrantDetailsSerializer(serializers.Serializer):
+ user_code = serializers.CharField(help_text="The code, in the form the device shows it.")
+ client_id = serializers.CharField(help_text="The client that started the device grant.")
+ client_name = serializers.CharField(help_text="The client's display name.")
+ logo_uri = serializers.CharField(allow_null=True, help_text="The client's logo, if it declared one.")
+ is_verified = serializers.BooleanField(help_text="Whether PostHog has verified the client.")
+ scopes = serializers.ListField(
+ child=serializers.CharField(), help_text="The scopes the token will carry if the person approves."
+ )
+ expires_at = serializers.DateTimeField(help_text="When the code expires.")
+
+
+class DeviceDecision(models.TextChoices):
+ AUTHORIZED = OAuthDeviceGrant.AUTHORIZED, "Authorized"
+ DENIED = OAuthDeviceGrant.DENIED, "Denied"
+
+
+class DeviceDecisionSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=DeviceDecision.choices, help_text="The device grant's status after the decision."
+ )
+
+
+def _invalid_code() -> Response:
+ return Response(
+ {"error": "invalid_code", "error_description": "This code is wrong, expired or already used."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+
+def _unverified_client() -> Response:
+ return Response(
+ {"error": "unverified_client", "error_description": UNVERIFIED_CLIENT_DESCRIPTION},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+
+def _capture(request: Request, event: str, grant: OAuthDeviceGrant, **properties: object) -> None:
+ """Device approval events share the `oauth_*` client properties, so they line up with
+ `oauth_token_issued` for the same client."""
+ # Late import: the views module imports this one for the token endpoint.
+ from posthog.api.oauth.views import _oauth_app_event_properties # noqa: PLC0415
+
+ application = OAuthApplication.objects.filter(client_id=grant.client_id).first()
+ posthoganalytics.capture(
+ distinct_id=str(cast(User, request.user).distinct_id),
+ event=event,
+ properties={**(_oauth_app_event_properties(application) if application else {}), **properties},
+ )
+
+
+def _pending_grant(user_code: str, *, lock: bool = False) -> OAuthDeviceGrant | None:
+ queryset = OAuthDeviceGrant.objects.filter(
+ user_code=normalize_user_code(user_code),
+ status=OAuthDeviceGrant.AUTHORIZATION_PENDING,
+ expires__gt=timezone.now(),
+ )
+ if lock:
+ queryset = queryset.select_for_update()
+ return queryset.order_by("-created").first()
+
+
+# `x-internal` keeps the approval page's API out of the public docs, but in the codegen build that
+# gives the page its generated client.
+@extend_schema(tags=["oauth"], extensions={"x-product": "core", "x-internal": True})
+class OAuthDeviceViewSet(viewsets.ViewSet):
+ """The approval page's API for device grants. Session only: a token can never approve one."""
+
+ include_in_api_docs = True
+ authentication_classes = [SessionAuthentication]
+ permission_classes = [IsAuthenticated]
+ throttle_classes = [OAuthDeviceCodeBurstThrottle, OAuthDeviceCodeSustainedThrottle]
+
+ @extend_schema(request=DeviceUserCodeSerializer, responses={200: DeviceGrantDetailsSerializer})
+ @action(methods=["POST"], detail=False)
+ def lookup(self, request: Request) -> Response:
+ """Show what a device code asks for, so the person can check it before approving."""
+ serializer = DeviceUserCodeSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ grant = _pending_grant(serializer.validated_data["user_code"])
+ application = grant and OAuthApplication.objects.filter(client_id=grant.client_id).first()
+ if grant is None or application is None:
+ return _invalid_code()
+ # Staff can withdraw a verification while a grant is pending.
+ if not application.is_verified:
+ return _unverified_client()
+ # pinned: analytics event names, which dashboards depend on
+ _capture(request, "oauth_device_authorization_viewed", grant)
+ return Response(
+ DeviceGrantDetailsSerializer(
+ {
+ "user_code": grant.user_code,
+ "client_id": application.client_id,
+ "client_name": application.name,
+ "logo_uri": application.logo_uri or None,
+ "is_verified": application.is_verified,
+ "scopes": (grant.scope or "").split(),
+ "expires_at": grant.expires,
+ }
+ ).data
+ )
+
+ @extend_schema(request=DeviceApprovalSerializer, responses={200: DeviceDecisionSerializer})
+ @action(methods=["POST"], detail=False)
+ def approve(self, request: Request) -> Response:
+ """Approve a device grant for one project. The token gets the scopes `lookup` showed."""
+ # Late import: the views module imports this one for the token endpoint.
+ from posthog.api.oauth.views import _gateway_blocklist_block, _impersonator_id_for_request # noqa: PLC0415
+
+ serializer = DeviceApprovalSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ # An impersonated session must not hand a client a long-lived token in the user's name.
+ if _impersonator_id_for_request(request) is not None:
+ return Response(
+ {"error": "access_denied", "error_description": "You can't approve a device while impersonating."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+
+ team = Team.objects.select_related("organization").filter(id=serializer.validated_data["project_id"]).first()
+ if team is None:
+ return Response(
+ {"error": "invalid_project", "error_description": "Project not found."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ try:
+ AccessibleTeams.for_request(request, [team.id])
+ except CredentialScopeDenied:
+ return Response(
+ {"error": "access_denied", "error_description": "You don't have access to this project."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ # Session auth checks the 2FA policy of the current organization only, and the token never
+ # meets a 2FA check later, so the policy of the project's organization is checked here.
+ if missing_two_factor_step(request._request, cast(User, request.user), organization=team.organization):
+ return Response(
+ {
+ "error": "two_factor_required",
+ "error_description": "This project's organization requires two-factor authentication. Set it up, then try again.",
+ },
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ # The same gap for the verified-domain policy: session auth checks the current organization only.
+ if OrganizationDomain.objects.is_email_blocked_by_domain_enforcement(
+ cast(User, request.user).email, team.organization
+ ):
+ return Response(
+ {"error": "verified_domain_required", "error_description": VERIFIED_DOMAIN_REQUIRED_ERROR},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+
+ with transaction.atomic():
+ grant = _pending_grant(serializer.validated_data["user_code"], lock=True)
+ if grant is None:
+ return _invalid_code()
+ application = OAuthApplication.objects.filter(client_id=grant.client_id).first()
+ if application is None or not application.is_verified:
+ return _unverified_client()
+ if block := _gateway_blocklist_block(
+ request, grant.scope or "", access_level="team", scoped_team_ids=[team.id]
+ ):
+ return block
+ grant.user = cast(User, request.user)
+ grant.scoped_teams = [team.id]
+ grant.status = OAuthDeviceGrant.AUTHORIZED
+ grant.save(update_fields=["user", "scoped_teams", "status"])
+
+ logger.info("oauth_device_grant_approved", client_id=grant.client_id[:64], team_id=team.id)
+ _capture(request, "oauth_device_authorization_approved", grant, team_id=team.id)
+ return Response(DeviceDecisionSerializer({"status": grant.status}).data)
+
+ @extend_schema(request=DeviceUserCodeSerializer, responses={200: DeviceDecisionSerializer})
+ @action(methods=["POST"], detail=False)
+ def deny(self, request: Request) -> Response:
+ """Refuse a device grant, so the client's next poll gets `access_denied`."""
+ serializer = DeviceUserCodeSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ with transaction.atomic():
+ grant = _pending_grant(serializer.validated_data["user_code"], lock=True)
+ if grant is None:
+ return _invalid_code()
+ grant.user = cast(User, request.user)
+ grant.status = OAuthDeviceGrant.DENIED
+ grant.save(update_fields=["user", "status"])
+ _capture(request, "oauth_device_authorization_denied", grant)
+ return Response(DeviceDecisionSerializer({"status": grant.status}).data)
diff --git a/posthog/api/oauth/metadata.py b/posthog/api/oauth/metadata.py
index c59948029463..c4934aef9aba 100644
--- a/posthog/api/oauth/metadata.py
+++ b/posthog/api/oauth/metadata.py
@@ -4,6 +4,8 @@ Both documents describe one server, and a client reads whichever one its stack s
so they are built here rather than separately.
"""
+from oauth2_provider.models import AbstractApplication
+
from posthog.api import id_jag
from posthog.api.oauth.claims import OIDC_CLAIMS
from posthog.dataclasses import frozen
@@ -16,6 +18,7 @@ SUPPORTED_GRANT_TYPES = [
"authorization_code",
"refresh_token",
id_jag.JWT_BEARER_GRANT_TYPE,
+ AbstractApplication.GRANT_DEVICE_CODE,
]
# Every method a client can register under must appear here, or a client reads this
@@ -34,6 +37,7 @@ def _shared_metadata(base_url: str) -> Document:
"issuer": base_url,
"authorization_endpoint": f"{base_url}/oauth/authorize/",
"token_endpoint": f"{base_url}/oauth/token/",
+ "device_authorization_endpoint": f"{base_url}/oauth/device-authorization/",
"userinfo_endpoint": f"{base_url}/oauth/userinfo/",
"revocation_endpoint": f"{base_url}/oauth/revoke/",
"introspection_endpoint": f"{base_url}/oauth/introspect/",
diff --git a/posthog/api/oauth/test_device.py b/posthog/api/oauth/test_device.py
new file mode 100644
index 000000000000..951d67ea2479
--- /dev/null
+++ b/posthog/api/oauth/test_device.py
@@ -0,0 +1,488 @@
+import json
+import base64
+from datetime import UTC, datetime, timedelta
+from urllib.parse import quote_plus, urlencode
+
+import time_machine
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.conf import settings
+from django.test import override_settings
+from django.utils import timezone
+
+import jwt
+from cryptography.hazmat.primitives.asymmetric import rsa
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER
+from posthog.api.oauth.device import DEVICE_CODE_GRANT_TYPE
+from posthog.models import Organization, Team
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthDeviceGrant, revoke_oauth_session
+
+FORM = "application/x-www-form-urlencoded"
+START = "2026-03-02 10:00:00"
+
+
+class TestOAuthDeviceGrant(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.device_app = OAuthApplication.objects.create(
+ name="hog",
+ client_id="hog-device-client",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_DEVICE_CODE,
+ is_verified=True,
+ redirect_uris="",
+ algorithm="RS256",
+ )
+
+ def _start(self, client_id: str = "hog-device-client", **extra: str) -> dict:
+ body = {"client_id": client_id, "scope": "insight:read feature_flag:write llm_gateway:read", **extra}
+ response = self.client.post("/oauth/device-authorization/", urlencode(body), content_type=FORM)
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(response["Cache-Control"], "no-store")
+ return response.json()
+
+ def _poll(self, device_code: str, client_id: str = "hog-device-client", **extra: str):
+ body = {"grant_type": DEVICE_CODE_GRANT_TYPE, "device_code": device_code, "client_id": client_id, **extra}
+ return self.client.post("/oauth/token/", urlencode(body), content_type=FORM)
+
+ def _approve(self, user_code: str, project_id: int | None = None):
+ return self.client.post(
+ "/api/oauth_device/approve/", {"user_code": user_code, "project_id": project_id or self.team.id}
+ )
+
+ @patch("posthog.api.oauth.device.posthoganalytics.capture")
+ def test_a_person_approves_and_the_client_gets_a_project_token_once(self, capture) -> None:
+ with time_machine.travel(START, tick=False) as clock:
+ started = self._start()
+ self.assertTrue(started["verification_uri"].endswith("/device"))
+ self.assertTrue(started["verification_uri_complete"].endswith(f"/device?code={started['user_code']}"))
+
+ lookup = self.client.post("/api/oauth_device/lookup/", {"user_code": started["user_code"].lower()})
+ self.assertEqual(lookup.status_code, status.HTTP_200_OK)
+ # A scope outside the ceiling, like the gateway one, never reaches the page.
+ self.assertEqual(lookup.json()["scopes"], ["feature_flag:write", "insight:read"])
+ self.assertEqual(lookup.json()["client_name"], "hog")
+
+ self.assertEqual(self._approve(started["user_code"]).json(), {"status": "authorized"})
+ self.assertEqual(
+ [call.kwargs["event"] for call in capture.call_args_list],
+ ["oauth_device_authorization_viewed", "oauth_device_authorization_approved"],
+ )
+
+ clock.shift(timedelta(seconds=6))
+ # The scope sent with the poll doesn't count: the token gets what the person approved.
+ token = self._poll(started["device_code"], scope="dashboard:write insight:read")
+
+ self.assertEqual(token.status_code, status.HTTP_200_OK, token.content)
+ body = token.json()
+ self.assertEqual(body["scoped_teams"], [self.team.id])
+ self.assertEqual(sorted(body["scope"].split()), ["feature_flag:write", "insight:read"])
+ self.assertTrue(body["refresh_token"])
+ access_token = OAuthAccessToken.objects.get(token=body["access_token"])
+ self.assertEqual(access_token.user, self.user)
+ self.assertEqual(access_token.scoped_teams, [self.team.id])
+
+ clock.shift(timedelta(seconds=6))
+ self.assertEqual(self._poll(started["device_code"]).json()["error"], "invalid_grant")
+
+ @parameterized.expand(
+ [
+ ("pending", 6, None, "authorization_pending", False),
+ ("polled too fast", 1, None, "slow_down", False),
+ ("denied", 6, "deny", "access_denied", True),
+ ("expired while pending", 3600, None, "expired_token", True),
+ ("expired after approval", 3600, "approve", "expired_token", True),
+ ]
+ )
+ @patch("posthog.api.oauth.views.posthoganalytics.capture")
+ def test_a_poll_reports_the_grant_state(
+ self, _name: str, wait_seconds: int, decision: str | None, expected: str, counts_as_rejected: bool, capture
+ ) -> None:
+ with time_machine.travel(START, tick=False) as clock:
+ started = self._start()
+ if decision == "approve":
+ self._approve(started["user_code"])
+ elif decision == "deny":
+ self.client.post("/api/oauth_device/deny/", {"user_code": started["user_code"]})
+
+ clock.shift(timedelta(seconds=wait_seconds))
+ response = self._poll(started["device_code"])
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], expected)
+ rejected = [call for call in capture.call_args_list if call.kwargs.get("event") == "oauth_token_rejected"]
+ self.assertEqual(len(rejected), 1 if counts_as_rejected else 0)
+
+ def test_a_client_that_polls_too_fast_must_wait_longer(self) -> None:
+ with time_machine.travel(START, tick=False) as clock:
+ started = self._start()
+ clock.shift(timedelta(seconds=1))
+
+ too_fast = self._poll(started["device_code"])
+ same_second = self._poll(started["device_code"])
+ clock.shift(timedelta(seconds=10))
+ on_time = self._poll(started["device_code"])
+
+ self.assertEqual(too_fast.json()["error"], "slow_down")
+ self.assertEqual(same_second.json()["error"], "slow_down")
+ self.assertEqual(OAuthDeviceGrant.objects.get().interval, 10)
+ self.assertEqual(on_time.json()["error"], "authorization_pending")
+
+ @parameterized.expand(
+ [
+ ("an unknown device code", {"device_code": "not-a-real-code"}, "invalid_grant"),
+ ("no device code", {"device_code": ""}, "invalid_request"),
+ ]
+ )
+ def test_a_poll_with_a_bad_device_code_fails(self, _name: str, overrides: dict, expected: str) -> None:
+ body = {"grant_type": DEVICE_CODE_GRANT_TYPE, "client_id": "hog-device-client", **overrides}
+ response = self.client.post("/oauth/token/", urlencode(body), content_type=FORM)
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], expected)
+
+ def test_only_the_client_that_started_the_grant_can_redeem_it(self) -> None:
+ OAuthApplication.objects.create(
+ name="other",
+ client_id="other-device-client",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_DEVICE_CODE,
+ is_verified=True,
+ redirect_uris="",
+ algorithm="RS256",
+ )
+ with time_machine.travel(START, tick=False) as clock:
+ started = self._start()
+ clock.shift(timedelta(seconds=6))
+ # Before approval, another client learns nothing about the grant.
+ self.assertEqual(
+ self._poll(started["device_code"], client_id="other-device-client").json()["error"], "invalid_grant"
+ )
+ self._approve(started["user_code"])
+ clock.shift(timedelta(seconds=6))
+
+ stolen = self._poll(started["device_code"], client_id="other-device-client")
+
+ self.assertEqual(stolen.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(stolen.json()["error"], "invalid_grant")
+ clock.shift(timedelta(seconds=6))
+ self.assertEqual(self._poll(started["device_code"]).status_code, status.HTTP_200_OK)
+
+ @parameterized.expand(
+ [
+ ("registered for authorization code", OAuthApplication.GRANT_AUTHORIZATION_CODE, True, "can't use"),
+ ("PostHog hasn't verified", OAuthApplication.GRANT_DEVICE_CODE, False, "hasn't verified"),
+ ]
+ )
+ def test_a_client_cannot_start_a_device_grant_when(
+ self, _name: str, grant_type: str, is_verified: bool, description: str
+ ) -> None:
+ OAuthApplication.objects.create(
+ name="other app",
+ client_id="other-client",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=grant_type,
+ is_verified=is_verified,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ )
+ response = self.client.post(
+ "/oauth/device-authorization/", urlencode({"client_id": "other-client"}), content_type=FORM
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], "unauthorized_client")
+ self.assertIn(description, response.json()["error_description"])
+ self.assertFalse(OAuthDeviceGrant.objects.exists())
+
+ def test_a_client_that_loses_its_verification_stops_working(self) -> None:
+ with time_machine.travel(START, tick=False) as clock:
+ approved = self._start()
+ self._approve(approved["user_code"])
+ pending = self._start()
+ OAuthApplication.objects.filter(pk=self.device_app.pk).update(is_verified=False)
+ clock.shift(timedelta(seconds=6))
+
+ redeem = self._poll(approved["device_code"])
+ lookup = self.client.post("/api/oauth_device/lookup/", {"user_code": pending["user_code"]})
+ approve = self._approve(pending["user_code"])
+
+ self.assertEqual(redeem.json()["error"], "unauthorized_client")
+ self.assertFalse(OAuthAccessToken.objects.exists())
+ self.assertEqual(lookup.json()["error"], "unverified_client")
+ self.assertEqual(approve.json()["error"], "unverified_client")
+ self.assertEqual(
+ OAuthDeviceGrant.objects.get(device_code=pending["device_code"]).status,
+ OAuthDeviceGrant.AUTHORIZATION_PENDING,
+ )
+
+ def test_a_confidential_client_must_authenticate_even_when_it_names_the_device_grant(self) -> None:
+ OAuthApplication.objects.create(
+ name="confidential device client",
+ client_id="confidential-device-client",
+ client_secret="the-secret",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_DEVICE_CODE,
+ is_verified=True,
+ redirect_uris="",
+ algorithm="RS256",
+ )
+ response = self.client.post(
+ "/oauth/device-authorization/",
+ urlencode({"client_id": "confidential-device-client", "grant_type": DEVICE_CODE_GRANT_TYPE}),
+ content_type=FORM,
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.json()["error"], "invalid_client")
+
+ def test_a_confidential_client_logs_in_with_basic_auth(self) -> None:
+ client_id = "https://cli.example.com/oauth/client.json"
+ OAuthApplication.objects.create(
+ name="confidential device client",
+ client_id=client_id,
+ client_secret="the-secret",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_DEVICE_CODE,
+ is_verified=True,
+ redirect_uris="",
+ algorithm="RS256",
+ )
+ # The client names itself only in Basic auth, which form-encodes the client_id (RFC 6749 section 2.3.1).
+ basic = "Basic " + base64.b64encode(f"{quote_plus(client_id)}:the-secret".encode()).decode()
+
+ with time_machine.travel(START, tick=False) as clock:
+ started = self.client.post(
+ "/oauth/device-authorization/",
+ urlencode({"scope": "insight:read"}),
+ content_type=FORM,
+ HTTP_AUTHORIZATION=basic,
+ )
+ self.assertEqual(started.status_code, status.HTTP_200_OK, started.content)
+ self._approve(started.json()["user_code"])
+ clock.shift(timedelta(seconds=6))
+ token = self.client.post(
+ "/oauth/token/",
+ urlencode({"grant_type": DEVICE_CODE_GRANT_TYPE, "device_code": started.json()["device_code"]}),
+ content_type=FORM,
+ HTTP_AUTHORIZATION=basic,
+ )
+
+ self.assertEqual(token.status_code, status.HTTP_200_OK, token.content)
+
+ def test_a_private_key_jwt_client_logs_in(self) -> None:
+ client_id = "signing-device-client"
+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ OAuthApplication.objects.create(
+ name="signing device client",
+ client_id=client_id,
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_DEVICE_CODE,
+ is_verified=True,
+ redirect_uris="",
+ algorithm="RS256",
+ jwks_uri="https://cli.example.com/.well-known/jwks.json",
+ )
+ jwk = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key()))
+ jwk.update({"kid": "device-key-1", "use": "sig", "alg": "RS256"})
+
+ def assertion(jti: str) -> dict[str, str]:
+ # START, the frozen time the token endpoint checks the assertion against.
+ now = int(datetime(2026, 3, 2, 10, tzinfo=UTC).timestamp())
+ claims = {"iss": client_id, "sub": client_id, "aud": "http://testserver/oauth/token/", "jti": jti}
+ token = jwt.encode(
+ {**claims, "iat": now, "exp": now + 60}, private_key, algorithm="RS256", headers={"kid": "device-key-1"}
+ )
+ return {"client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER, "client_assertion": token}
+
+ with (
+ time_machine.travel(START, tick=False) as clock,
+ override_settings(SITE_URL="http://testserver"),
+ patch(
+ "posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=({"keys": [jwk]}, None)
+ ),
+ ):
+ started = self.client.post(
+ "/oauth/device-authorization/",
+ urlencode({"client_id": client_id, "scope": "insight:read", **assertion("start")}),
+ content_type=FORM,
+ )
+ self.assertEqual(started.status_code, status.HTTP_200_OK, started.content)
+ self._approve(started.json()["user_code"])
+ clock.shift(timedelta(seconds=6))
+ token = self._poll(started.json()["device_code"], client_id=client_id, **assertion("poll"))
+
+ self.assertEqual(token.status_code, status.HTTP_200_OK, token.content)
+
+ def test_a_forged_assertion_cannot_claim_it_was_verified(self) -> None:
+ OAuthApplication.objects.create(
+ name="signing device client",
+ client_id="signing-device-client",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_DEVICE_CODE,
+ is_verified=True,
+ redirect_uris="",
+ algorithm="RS256",
+ jwks_uri="https://cli.example.com/.well-known/jwks.json",
+ )
+ forged = jwt.encode(
+ {"iss": "signing-device-client", "sub": "signing-device-client", "jti": "forged"},
+ rsa.generate_private_key(public_exponent=65537, key_size=2048),
+ algorithm="RS256",
+ )
+ body = {
+ "client_id": "signing-device-client",
+ "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,
+ "client_assertion": forged,
+ # oauthlib answers a missing request attribute from the parameters, so a caller can send this.
+ "verified_client_assertion": forged,
+ }
+
+ with patch("posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=({"keys": []}, None)):
+ response = self.client.post("/oauth/device-authorization/", urlencode(body), content_type=FORM)
+
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)
+ self.assertFalse(OAuthDeviceGrant.objects.exists())
+
+ def test_approval_needs_access_to_the_project(self) -> None:
+ other_team = Team.objects.create(organization=Organization.objects.create(name="Elsewhere"), name="Theirs")
+ started = self._start()
+
+ response = self._approve(started["user_code"], project_id=other_team.id)
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(OAuthDeviceGrant.objects.get().status, OAuthDeviceGrant.AUTHORIZATION_PENDING)
+
+ @parameterized.expand(
+ [
+ ("2FA", {"enforce_2fa": True}, "two_factor_required"),
+ ("verified email domains", {"enforce_verified_domains": True}, "verified_domain_required"),
+ ]
+ )
+ def test_approval_follows_the_policy_of_the_projects_organization(
+ self, _name: str, policy: dict, error: str
+ ) -> None:
+ strict = Organization.objects.create(name="Strict", **policy)
+ strict_team = Team.objects.create(organization=strict, name="Strict project")
+ self.user.join(organization=strict)
+ self.user.current_organization = self.organization
+ self.user.save()
+ session = self.client.session
+ session[settings.SESSION_COOKIE_CREATED_AT_KEY] = 1_800_000_000
+ session.save()
+ started = self._start()
+
+ response = self._approve(started["user_code"], project_id=strict_team.id)
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ self.assertEqual(response.json()["error"], error)
+ self.assertEqual(OAuthDeviceGrant.objects.get().status, OAuthDeviceGrant.AUTHORIZATION_PENDING)
+
+ @parameterized.expand(
+ [
+ ("a wrong code", "BCDF-GHJK"),
+ ("an expired code", None),
+ ]
+ )
+ @time_machine.travel(START, tick=False)
+ def test_approval_refuses(self, _name: str, user_code: str | None) -> None:
+ started = self._start()
+ if user_code is None:
+ OAuthDeviceGrant.objects.update(expires=timezone.now() - timedelta(seconds=1))
+
+ response = self._approve(user_code or started["user_code"])
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], "invalid_code")
+
+ def test_a_personal_api_key_cannot_approve_a_device(self) -> None:
+ started = self._start()
+ self.client.logout()
+ key = self.create_personal_api_key_with_scopes(["*"])
+
+ response = self.client.post(
+ "/api/oauth_device/approve/",
+ {"user_code": started["user_code"], "project_id": self.team.id},
+ headers={"authorization": f"Bearer {key}"},
+ )
+
+ self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
+ self.assertEqual(OAuthDeviceGrant.objects.get().status, OAuthDeviceGrant.AUTHORIZATION_PENDING)
+
+ def test_entering_codes_is_throttled(self) -> None:
+ responses = [
+ self.client.post("/api/oauth_device/lookup/", {"user_code": "BCDF-GHJK"}).status_code for _ in range(11)
+ ]
+
+ self.assertEqual(responses[:10], [status.HTTP_400_BAD_REQUEST] * 10)
+ self.assertEqual(responses[10], status.HTTP_429_TOO_MANY_REQUESTS)
+
+ @parameterized.expand([("in the body", False, "invalid_client"), ("in the query string", True, "invalid_request")])
+ def test_a_new_cimd_client_gets_the_cimd_rate_limit(self, _name: str, in_query: bool, expected: str) -> None:
+ client_id = urlencode({"client_id": "https://new-client.example.com/.well-known/oauth-client-metadata.json"})
+ throttle = MagicMock(allow_request=MagicMock(return_value=False), wait=MagicMock(return_value=30))
+ with (
+ patch("posthog.api.oauth.views.CIMD_THROTTLE_CLASSES", new=[MagicMock(return_value=throttle)]),
+ patch("posthog.api.oauth.cimd.requests.Session.get") as fetch,
+ ):
+ if in_query:
+ response = self.client.post(f"/oauth/device-authorization/?{client_id}", "", content_type=FORM)
+ else:
+ response = self.client.post("/oauth/device-authorization/", client_id, content_type=FORM)
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], expected)
+ fetch.assert_not_called()
+
+ def test_a_device_grant_always_asks_for_the_scopes_the_client_requires(self) -> None:
+ OAuthApplication.objects.create(
+ name="required",
+ client_id="required-scopes-client",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_DEVICE_CODE,
+ is_verified=True,
+ redirect_uris="",
+ algorithm="RS256",
+ scopes=["insight:read"],
+ optional_scopes=["dashboard:write"],
+ )
+ started = self._start(client_id="required-scopes-client", scope="dashboard:write")
+
+ lookup = self.client.post("/api/oauth_device/lookup/", {"user_code": started["user_code"]})
+
+ self.assertEqual(lookup.json()["scopes"], ["dashboard:write", "insight:read"])
+
+ def test_disconnecting_the_app_drops_an_approved_device_grant_the_client_has_not_redeemed(self) -> None:
+ with time_machine.travel(START, tick=False) as clock:
+ started = self._start()
+ self._approve(started["user_code"])
+ existing = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=self.device_app,
+ token="pha_existing",
+ expires=timezone.now() + timedelta(hours=1),
+ scoped_teams=[self.team.id],
+ )
+
+ revoke_oauth_session(access_token=existing)
+ clock.shift(timedelta(seconds=6))
+
+ self.assertEqual(self._poll(started["device_code"]).json()["error"], "invalid_grant")
+
+ def test_starting_device_grants_is_limited_per_address(self) -> None:
+ throttle = MagicMock(allow_request=MagicMock(return_value=False))
+ with patch(
+ "posthog.api.oauth.device.DEVICE_AUTHORIZATION_THROTTLE_CLASSES", new=(MagicMock(return_value=throttle),)
+ ):
+ response = self.client.post(
+ "/oauth/device-authorization/", urlencode({"client_id": "hog-device-client"}), content_type=FORM
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+ self.assertFalse(OAuthDeviceGrant.objects.exists())
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 0fc11e2eb6ae..729ac648414e 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -5796,6 +5796,7 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):
"issuer",
"authorization_endpoint",
"token_endpoint",
+ "device_authorization_endpoint",
"revocation_endpoint",
"introspection_endpoint",
"userinfo_endpoint",
@@ -5816,7 +5817,12 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):
self.assertEqual(metadata["response_types_supported"], ["code"])
self.assertEqual(
metadata["grant_types_supported"],
- ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:jwt-bearer"],
+ [
+ "authorization_code",
+ "refresh_token",
+ "urn:ietf:params:oauth:grant-type:jwt-bearer",
+ "urn:ietf:params:oauth:grant-type:device_code",
+ ],
)
self.assertEqual(metadata["code_challenge_methods_supported"], ["S256"])
self.assertIn("none", metadata["token_endpoint_auth_methods_supported"])
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 77dfe10e09e9..6dc84db81e16 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -62,6 +62,12 @@ from posthog.api.oauth.client_assertion import (
verify_client_assertion,
)
from posthog.api.oauth.client_auth import verify_client_secret
+from posthog.api.oauth.device import (
+ DEVICE_CODE_GRANT_TYPE,
+ DEVICE_POLL_WAITING_ERRORS,
+ device_token_response,
+ token_server_kwargs,
+)
from posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_context, is_trusted_posthog_mcp_resource
from posthog.api.oauth.metadata import (
Document,
@@ -98,6 +104,7 @@ from posthog.scopes import (
is_truncated_scope_request,
narrow_scopes_to_ceiling,
resolve_ceiling,
+ resolve_requested_scopes,
scopes_outside_ceiling,
)
from posthog.security.url_validation import has_ambiguous_authority
@@ -674,6 +681,12 @@ class OAuthValidator(OAuth2Validator):
assertion = self._resolve_request_assertion(request)
if assertion is None:
return False
+ # oauthlib's device grant authenticates a confidential client twice per request. The first
+ # check spends the assertion's jti, so a second verification would reject it as a replay.
+ # Read from `__dict__` only: oauthlib's Request answers a missing attribute from the request
+ # parameters, so getattr would let a caller send the "verified" value itself.
+ if request.__dict__.get("verified_client_assertion") == assertion.client_assertion:
+ return True
app = self._load_application(assertion.client_id, request)
# jwks_uri alone gates this, not client_type: a public CIMD client may publish keys
@@ -696,6 +709,7 @@ class OAuthValidator(OAuth2Validator):
return False
request.client = app
+ request.verified_client_assertion = assertion.client_assertion
return True
# PostHog deliberately does NOT support OIDC silent authentication (`prompt=none`). Every
@@ -825,13 +839,11 @@ class OAuthValidator(OAuth2Validator):
their sign-in. A request with nothing grantable yields an identity-only
token whose resource calls 403; `oauth_scopes_clamped` is what surfaces it.
"""
- app_scopes = getattr(client, "ceiling_scopes", None) or []
- ordered = list(scopes or [])
- requested = set(ordered)
- if not requested or is_truncated_scope_request(ordered):
- request.scopes = sorted(effective_ceiling(app_scopes) | ALWAYS_ALLOWED_SCOPES)
- return True
- request.scopes = clamp_scopes_to_ceiling(requested, app_scopes, allow_wildcard_under_empty_ceiling=True)
+ request.scopes = resolve_requested_scopes(
+ list(scopes or []),
+ getattr(client, "ceiling_scopes", None) or [],
+ allow_wildcard_under_empty_ceiling=True,
+ )
return True
def get_original_scopes(self, refresh_token, request, *args, **kwargs):
@@ -2062,8 +2074,18 @@ class OAuthTokenView(TokenView):
of the code_verifier that was sent in the authorization request.
RFC 6749 requires x-www-form-urlencoded, but this endpoint also accepts application/json for convenience.
+
+ The RFC 8628 device code grant ("urn:ietf:params:oauth:grant-type:device_code") is served
+ here too: see `posthog.api.oauth.device`.
"""
+ @classmethod
+ def get_server(cls):
+ return cls.get_server_class()(cls.get_validator_class()(), **token_server_kwargs())
+
+ def device_flow_token_response(self, request, device_code, *args, **kwargs):
+ return device_token_response(self.create_token_response, request, device_code)
+
@staticmethod
def _request_client_auth_method(request) -> str:
"""Which client-authentication method the token request presented, regardless of
@@ -2263,6 +2285,12 @@ class OAuthTokenView(TokenView):
if grant_type == id_jag.JWT_BEARER_GRANT_TYPE:
return self._handle_jwt_bearer_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"):
+ return JsonResponse(
+ {"error": "invalid_request", "error_description": "Missing device_code parameter"}, status=400
+ )
+
client_id = request.POST.get("client_id", "")
client_id_prefix = client_id[:8] if client_id else "unknown"
client_auth_method = self._request_client_auth_method(request)
@@ -2391,7 +2419,8 @@ class OAuthTokenView(TokenView):
else:
response["Content-Type"] = "application/json"
- if response.status_code != 200:
+ # A device client polls until the person approves, so these answers are waiting, not rejections.
+ if response.status_code != 200 and _token_error_code(response) not in DEVICE_POLL_WAITING_ERRORS:
self._capture_token_rejected(grant_type, client_id, _token_error_code(response), client_auth_method)
return response
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 16750d511fbf..91c6c601849a 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -84,7 +84,7 @@ from .emoji_search import EmojiSearchViewSet
from .event_filter_config import EventFilterConfigViewSet
from .file_system import file_system, file_system_shortcut
from .llm_prompt import LLMPromptViewSet
-from .oauth import OrganizationOAuthApplicationViewSet
+from .oauth import OAuthDeviceViewSet, OrganizationOAuthApplicationViewSet
from .organization_notification_locks import OrganizationNotificationLockViewSet
from .session import SessionViewSet
from .taxonomic_search_intent import SearchIntentViewSet
@@ -417,6 +417,7 @@ router.register(r"personal_api_keys", personal_api_key.PersonalAPIKeyViewSet, "p
router.register(r"internal_feedback", internal_feedback.InternalFeedbackViewSet, "internal_feedback")
# nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
router.register(r"cli-auth", cli_auth.CLIAuthViewSet, "cli_auth")
+router.register(r"oauth_device", OAuthDeviceViewSet, "oauth_device")
router.register(r"instance_status", instance_status.InstanceStatusViewSet, "instance_status")
router.register(r"dead_letter_queue", dead_letter_queue.DeadLetterQueueViewSet, "dead_letter_queue")
router.register(r"async_migrations", async_migration.AsyncMigrationsViewset, "async_migrations")
diff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.py
index 964f88dbf1ee..52e79fc4ab23 100644
--- a/posthog/helpers/two_factor_session.py
+++ b/posthog/helpers/two_factor_session.py
@@ -22,6 +22,7 @@ from two_factor.utils import default_device
from posthog.cloud_utils import is_dev_mode
from posthog.email import is_email_available, is_http_email_service_available
from posthog.helpers.email_utils import ESPSuppressionReason, check_esp_suppression
+from posthog.models.organization import Organization
from posthog.models.user import User
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.redis import get_client
@@ -141,13 +142,17 @@ def enforce_two_factor(request, user):
raise PermissionDenied(detail="2FA verification required", code="two_factor_verification_required")
-def missing_two_factor_step(request: HttpRequest, user: User) -> Literal["setup", "verification"] | None:
+def missing_two_factor_step(
+ request: HttpRequest, user: User, organization: Organization | None = None
+) -> Literal["setup", "verification"] | None:
+ """`organization` defaults to the user's current organization. Pass another one to check its policy,
+ such as the organization of a project the user grants access to."""
# We currently don't enforce 2FA for any SSO-authenticated users, as we depend on the SSO provider to handle 2FA
# TODO: This will soon be made configurable
if is_sso_authentication_backend(request):
return None
- organization = getattr(user, "organization", None)
+ organization = organization or getattr(user, "organization", None)
if not organization or not organization.enforce_2fa:
return None
diff --git a/posthog/migrations/1422_oauth_device_grant.py b/posthog/migrations/1422_oauth_device_grant.py
new file mode 100644
index 000000000000..c5ef28e24ef7
--- /dev/null
+++ b/posthog/migrations/1422_oauth_device_grant.py
@@ -0,0 +1,87 @@
+# Generated by Django 6.1.2 on 2026-11-02 17:37
+
+import django.db.models.deletion
+import django.contrib.postgres.fields
+from django.conf import settings
+from django.db import migrations, models
+
+from posthog.migration_helpers import AddConstraintNotValid
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1421_oauth_supports_step_up"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="OAuthDeviceGrant",
+ fields=[
+ ("id", models.BigAutoField(primary_key=True, serialize=False)),
+ ("device_code", models.CharField(max_length=100, unique=True)),
+ ("interval", models.IntegerField(default=5)),
+ ("expires", models.DateTimeField()),
+ (
+ "status",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("authorized", "Authorized"),
+ ("authorization-pending", "Authorization pending"),
+ ("expired", "Expired"),
+ ("denied", "Denied"),
+ ],
+ default="authorization-pending",
+ max_length=64,
+ ),
+ ),
+ ("last_checked", models.DateTimeField(auto_now=True)),
+ ("client_id", models.CharField(db_index=True, max_length=2048)),
+ ("user_code", models.CharField(db_index=True, max_length=100)),
+ ("scope", models.TextField(null=True)),
+ (
+ "scoped_teams",
+ django.contrib.postgres.fields.ArrayField(base_field=models.IntegerField(), blank=True, null=True),
+ ),
+ ("created", models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ "verbose_name": "OAuth Device Grant",
+ "verbose_name_plural": "OAuth Device Grants",
+ "abstract": False,
+ "swappable": "OAUTH2_PROVIDER_DEVICE_GRANT_MODEL",
+ "indexes": [models.Index(fields=["expires"], name="oauthdevicegrant_expires_idx")],
+ },
+ ),
+ migrations.RemoveConstraint(
+ model_name="oauthapplication",
+ name="enforce_supported_grant_types",
+ ),
+ AddConstraintNotValid(
+ model_name="oauthapplication",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ (
+ "authorization_grant_type__in",
+ [
+ "authorization-code",
+ "urn:ietf:params:oauth:grant-type:device_code",
+ ],
+ )
+ ),
+ name="enforce_supported_grant_types",
+ ),
+ ),
+ migrations.AddField(
+ model_name="oauthdevicegrant",
+ name="user",
+ field=models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="oauth_device_grants",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/1423_validate_oauthapplication_grant_types.py b/posthog/migrations/1423_validate_oauthapplication_grant_types.py
new file mode 100644
index 000000000000..2d7e6d1446a6
--- /dev/null
+++ b/posthog/migrations/1423_validate_oauthapplication_grant_types.py
@@ -0,0 +1,13 @@
+from django.db import migrations
+
+from posthog.migration_helpers import ValidateConstraint
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1422_oauth_device_grant"),
+ ]
+
+ operations = [
+ ValidateConstraint(model_name="oauthapplication", name="enforce_supported_grant_types"),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 1b984d2e36ad..151d9f2b619f 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1421_oauth_supports_step_up
+1423_validate_oauthapplication_grant_types
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index ab48f579aac8..4166dbc9ce63 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -84,6 +84,7 @@ from .oauth import (
CIMDVerificationToken,
OAuthAccessToken,
OAuthApplication,
+ OAuthDeviceGrant,
OAuthGrant,
OAuthIDToken,
OAuthRefreshToken,
@@ -139,6 +140,7 @@ __all__ = [
"OrganizationProvisioning",
"OAuthAccessToken",
"OAuthApplication",
+ "OAuthDeviceGrant",
"OAuthGrant",
"OAuthIDToken",
"OAuthRefreshToken",
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 27ff80778951..661e608dc7c5 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -19,6 +19,7 @@ from oauth2_provider.generators import generate_client_id
from oauth2_provider.models import (
AbstractAccessToken,
AbstractApplication,
+ AbstractDeviceGrant,
AbstractGrant,
AbstractIDToken,
AbstractRefreshToken,
@@ -397,7 +398,12 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore
# Note: We do not support HS256 since we don't want to store the client secret in plaintext
models.CheckConstraint(condition=models.Q(algorithm="RS256"), name="enforce_rs256_algorithm"),
models.CheckConstraint(
- condition=models.Q(authorization_grant_type=AbstractApplication.GRANT_AUTHORIZATION_CODE),
+ condition=models.Q(
+ authorization_grant_type__in=[
+ AbstractApplication.GRANT_AUTHORIZATION_CODE,
+ AbstractApplication.GRANT_DEVICE_CODE,
+ ]
+ ),
name="enforce_supported_grant_types",
),
]
@@ -527,6 +533,14 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore
self.full_clean()
super().save(*args, **kwargs)
+ def allows_grant_type(self, *grant_types: str) -> bool:
+ # The device grant's approval page can only show a client's self-declared name, so a device
+ # client works only while PostHog staff keep it verified. This covers starting a grant,
+ # redeeming one and refreshing its tokens.
+ if self.authorization_grant_type == self.GRANT_DEVICE_CODE and not self.is_verified:
+ return False
+ return super().allows_grant_type(*grant_types)
+
def get_allowed_schemes(self) -> list[str]:
"""Extract unique schemes from the application's registered redirect URIs, filtering out blocked schemes."""
blocked_schemes = self.get_blocked_schemes()
@@ -707,6 +721,44 @@ class OAuthGrant(AbstractGrant):
)
+class OAuthDeviceGrant(AbstractDeviceGrant):
+ """An RFC 8628 device authorization request, from the device code a client polls with to the
+ person who approves it on the approval page.
+
+ Swapped in for DOT's model because a CIMD `client_id` is a URL longer than DOT's 100
+ characters, a PostHog scope list is longer than DOT's 64, and the grant has to carry the
+ project the person picked, which the token is then scoped to.
+ """
+
+ class Meta(AbstractDeviceGrant.Meta):
+ verbose_name = "OAuth Device Grant"
+ verbose_name_plural = "OAuth Device Grants"
+ swappable = "OAUTH2_PROVIDER_DEVICE_GRANT_MODEL"
+ # The cleanup job deletes grants by expiry.
+ indexes = [models.Index(fields=["expires"], name="oauthdevicegrant_expires_idx")]
+ # `device_code` is already unique=True, so DOT's extra constraint would only add a second
+ # unique index on the same column.
+ constraints: list[models.BaseConstraint] = []
+
+ # No database constraint, so creating this table takes no lock on posthog_user. The ORM
+ # still cascades a user delete to their grants.
+ user: "User | None" = models.ForeignKey( # type: ignore[assignment] # ty: ignore[invalid-assignment]
+ "posthog.User",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ related_name="oauth_device_grants",
+ db_constraint=False,
+ )
+ client_id: models.CharField = models.CharField(max_length=2048, db_index=True)
+ user_code: models.CharField = models.CharField(max_length=100, db_index=True)
+ # The scopes the client asked for, already clamped to the application's ceiling. The token
+ # gets these, never the scopes the client sends when it polls.
+ scope: models.TextField = models.TextField(null=True)
+ scoped_teams: ArrayField = ArrayField(models.IntegerField(), null=True, blank=True)
+ created: models.DateTimeField = models.DateTimeField(auto_now_add=True)
+
+
def mint_oauth_access_token(
*,
application: OAuthApplication,
@@ -854,8 +906,10 @@ def revoke_oauth_session(
with transaction.atomic():
lock_oauth_connection(user_id=user.pk, application_id=application.pk)
- # Delete all grants for this user+application
+ # Delete all grants for this user+application, including approved device grants the
+ # client hasn't redeemed yet
OAuthGrant.objects.filter(user=user, application=application).delete()
+ OAuthDeviceGrant.objects.filter(user=user, client_id=application.client_id).delete()
# Delete, rather than revoke, every refresh token for this user+application. Absence is
# what makes the revoke stick: `validate_refresh_token` looks a token up by value and
@@ -984,14 +1038,16 @@ def revoke_application_sessions(application: "OAuthApplication") -> None:
token in autocommit, before its own transaction takes the row lock, so the bulk update
here would otherwise miss the tokens that racing refresh is about to create.
- Grants are deleted before the token sweep: a racing code exchange locks its grant row at
- mint (`_reject_code_exchange_racing_revoke`), so deleting grants first makes this
+ Grants, device grants included, are deleted before the token sweep: a racing code or device
+ code exchange locks its grant row at mint (`_reject_code_exchange_racing_revoke`, and the
+ device token view), so deleting grants first makes this
transaction block on that lock and re-snapshot the token sweep after the mint commits.
Sweeping tokens first would let the racing mint's tokens escape the sweep."""
now = timezone.now()
with transaction.atomic():
OAuthApplication.objects.filter(pk=application.pk).update(sessions_revoked_at=now)
OAuthGrant.objects.filter(application=application).delete()
+ OAuthDeviceGrant.objects.filter(client_id=application.client_id).delete()
OAuthRefreshToken.objects.filter(application=application, revoked__isnull=True).update(revoked=now)
OAuthAccessToken.objects.filter(application=application).delete()
diff --git a/posthog/oauth2_urls.py b/posthog/oauth2_urls.py
index ba0e4e38f8c3..a14916925ee0 100644
--- a/posthog/oauth2_urls.py
+++ b/posthog/oauth2_urls.py
@@ -6,6 +6,7 @@ from posthog.api.oauth import (
OAuthAuthorizationView,
OAuthClientManifestView,
OAuthConnectDiscoveryInfoView,
+ OAuthDeviceAuthorizationView,
OAuthIntrospectTokenView,
OAuthJwksInfoView,
OAuthProtectedResourceMetadataView,
@@ -22,6 +23,7 @@ urlpatterns = [
opt_slash_path("oauth/token", OAuthTokenView.as_view(), name="token"),
opt_slash_path("oauth/revoke", OAuthRevokeTokenView.as_view(), name="revoke"),
opt_slash_path("oauth/introspect", OAuthIntrospectTokenView.as_view(), name="introspect"),
+ opt_slash_path("oauth/device-authorization", OAuthDeviceAuthorizationView.as_view(), name="device-authorization"),
re_path(
r"^\.well-known/openid-configuration/?$",
OAuthConnectDiscoveryInfoView.as_view(),
diff --git a/posthog/scopes.py b/posthog/scopes.py
index a28d05f2766b..83f000bba054 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -668,6 +668,25 @@ def is_truncated_scope_request(requested: Sequence[str]) -> bool:
return any(scope.startswith(tail) for scope in known)
+def resolve_requested_scopes(
+ requested: Sequence[str],
+ app_scopes: Iterable[str],
+ *,
+ allow_wildcard_under_empty_ceiling: bool = False,
+) -> list[str]:
+ """The scopes an OAuth request gets: no scope, or a list cut off mid-token, resolves to the
+ whole ceiling, and anything else is clamped to it.
+
+ `/oauth/authorize` and `/oauth/device-authorization` both resolve scopes here, so a client
+ gets the same scopes from either.
+ """
+ if not requested or is_truncated_scope_request(requested):
+ return sorted(effective_ceiling(app_scopes) | ALWAYS_ALLOWED_SCOPES)
+ return clamp_scopes_to_ceiling(
+ set(requested), app_scopes, allow_wildcard_under_empty_ceiling=allow_wildcard_under_empty_ceiling
+ )
+
+
def narrow_scopes_to_ceiling(original: Iterable[str], app_scopes: Iterable[str]) -> list[str] | None:
"""Cap previously-granted scopes at an app's current ceiling (refresh-time).
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index bc018c6300ec..e9df48a0786c 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1335,6 +1335,7 @@ OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL = "posthog.OAuthAccessToken"
OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL = "posthog.OAuthRefreshToken"
OAUTH2_PROVIDER_ID_TOKEN_MODEL = "posthog.OAuthIDToken"
OAUTH2_PROVIDER_GRANT_MODEL = "posthog.OAuthGrant"
+OAUTH2_PROVIDER_DEVICE_GRANT_MODEL = "posthog.OAuthDeviceGrant"
ID_JAG_ACCESS_TOKEN_TTL_SECONDS: int = get_from_env("ID_JAG_ACCESS_TOKEN_TTL_SECONDS", 60 * 60 * 2, type_cast=int)
ID_JAG_CLOCK_SKEW_SECONDS: int = get_from_env("ID_JAG_CLOCK_SKEW_SECONDS", 30, type_cast=int)
diff --git a/products/growth/dags/oauth.py b/products/growth/dags/oauth.py
index b5ed47bcb03d..ea0a612bb9ae 100644
--- a/products/growth/dags/oauth.py
+++ b/products/growth/dags/oauth.py
@@ -9,7 +9,7 @@ from django.utils import timezone
import dagster
from posthog.dags.common import JobOwners
-from posthog.models.oauth import OAuthAccessToken, OAuthGrant, OAuthIDToken, OAuthRefreshToken
+from posthog.models.oauth import OAuthAccessToken, OAuthDeviceGrant, OAuthGrant, OAuthIDToken, OAuthRefreshToken
def batch_delete_model(queryset: QuerySet, query: Q, context: dagster.OpExecutionContext, token_type: str) -> int:
@@ -58,7 +58,7 @@ def clear_expired_tokens_by_type(
def clear_expired_oauth_tokens(context: dagster.OpExecutionContext) -> None:
"""
Clear expired OAuth tokens from the database.
- This function deletes expired refresh tokens, access tokens, ID tokens, and grants
+ This function deletes expired refresh tokens, access tokens, ID tokens, grants and device grants
"""
now = timezone.now()
retention_cutoff = now - timedelta(seconds=settings.OAUTH_EXPIRED_TOKEN_RETENTION_PERIOD)
@@ -104,6 +104,12 @@ def clear_expired_oauth_tokens(context: dagster.OpExecutionContext) -> None:
"expired": Q(expires__lt=retention_cutoff),
},
),
+ (
+ OAuthDeviceGrant,
+ {
+ "expired": Q(expires__lt=retention_cutoff),
+ },
+ ),
]
total_deleted = 0
diff --git a/products/growth/dags/tests/test_oauth.py b/products/growth/dags/tests/test_oauth.py
index b5408b42cb18..00ba9d11eb76 100644
--- a/products/growth/dags/tests/test_oauth.py
+++ b/products/growth/dags/tests/test_oauth.py
@@ -10,7 +10,7 @@ from django.utils import timezone
import dagster
from posthog.models import Organization, User
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthGrant, OAuthRefreshToken
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthDeviceGrant, OAuthGrant, OAuthRefreshToken
from products.growth.dags.oauth import (
batch_delete_model,
@@ -55,6 +55,13 @@ class TestOAuthTokenCleanup(TestCase):
scope="read write",
)
+ OAuthDeviceGrant.objects.create(
+ client_id="test_client_id", device_code="expired-device", user_code="BCDF-GHJK", expires=expired_time
+ )
+ pending_device_grant = OAuthDeviceGrant.objects.create(
+ client_id="test_client_id", device_code="pending-device", user_code="LMNP-QRST", expires=future_time
+ )
+
initial_count = OAuthAccessToken.objects.count()
self.assertEqual(initial_count, 2)
@@ -66,6 +73,7 @@ class TestOAuthTokenCleanup(TestCase):
self.assertLess(final_count, initial_count)
self.assertTrue(OAuthAccessToken.objects.filter(id=valid_token.id).exists())
+ self.assertEqual(list(OAuthDeviceGrant.objects.values_list("id", flat=True)), [pending_device_grant.id])
class TestBatchDeleteFunctionality(TestCase):
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a9cda96a567e..673208bc2d2e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -34930,6 +34930,56 @@ export namespace Schemas {
tokens: DevToken[];
}
+ export interface DeviceApproval {
+ /**
+ * The code the device shows, as the person typed it. Case and dashes don't matter.
+ * @maxLength 20
+ */
+ user_code: string;
+ /** The project the token is scoped to. */
+ project_id: number;
+ }
+
+ /**
+ * * `authorized` - Authorized
+ * * `denied` - Denied
+ */
+ export type DeviceDecisionEnum = typeof DeviceDecisionEnum[keyof typeof DeviceDecisionEnum];
+
+
+ export const DeviceDecisionEnum = {
+ Authorized: 'authorized',
+ Denied: 'denied',
+ } as const;
+
+ export interface DeviceDecision {
+ /** The device grant's status after the decision.
+ *
+ * * `authorized` - Authorized
+ * * `denied` - Denied */
+ status: DeviceDecisionEnum;
+ }
+
+ export interface DeviceGrantDetails {
+ /** The code, in the form the device shows it. */
+ user_code: string;
+ /** The client that started the device grant. */
+ client_id: string;
+ /** The client's display name. */
+ client_name: string;
+ /**
+ * The client's logo, if it declared one.
+ * @nullable
+ */
+ logo_uri: string | null;
+ /** Whether PostHog has verified the client. */
+ is_verified: boolean;
+ /** The scopes the token will carry if the person approves. */
+ scopes: string[];
+ /** When the code expires. */
+ expires_at: string;
+ }
+
/**
* * `Desktop` - Desktop
* * `Mobile` - Mobile
@@ -34944,6 +34994,14 @@ export namespace Schemas {
Tablet: 'Tablet',
} as const;
+ export interface DeviceUserCode {
+ /**
+ * The code the device shows, as the person typed it. Case and dashes don't matter.
+ * @maxLength 20
+ */
+ user_code: string;
+ }
+
/**
* * `passed` - passed
* * `warned` - warned