|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import secrets |
| 4 | +from datetime import timedelta |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +from django.contrib.postgres.fields.array import ArrayField |
| 8 | +from django.db import IntegrityError, models |
| 9 | +from django.utils import timezone |
| 10 | + |
| 11 | +from sentry.backup.dependencies import NormalizedModelName, get_model_name |
| 12 | +from sentry.backup.sanitize import SanitizableField, Sanitizer |
| 13 | +from sentry.backup.scopes import RelocationScope |
| 14 | +from sentry.db.models import FlexibleForeignKey, Model, control_silo_model |
| 15 | +from sentry.db.models.fields.hybrid_cloud_foreign_key import HybridCloudForeignKey |
| 16 | + |
| 17 | +# RFC 8628 recommends short lifetimes for device codes (10-15 minutes) |
| 18 | +DEFAULT_EXPIRATION = timedelta(minutes=10) |
| 19 | + |
| 20 | +# Default polling interval in seconds (RFC 8628 §3.2) |
| 21 | +DEFAULT_INTERVAL = 5 |
| 22 | + |
| 23 | +# Base-20 alphabet for user codes: excludes ambiguous characters (0/O, 1/I/L, etc.) |
| 24 | +# This provides ~34 bits of entropy for 8-character codes, sufficient with rate limiting. |
| 25 | +# Reference: RFC 8628 §5.1 |
| 26 | +USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ" |
| 27 | +USER_CODE_LENGTH = 8 |
| 28 | + |
| 29 | + |
| 30 | +def default_expiration(): |
| 31 | + return timezone.now() + DEFAULT_EXPIRATION |
| 32 | + |
| 33 | + |
| 34 | +def generate_device_code(): |
| 35 | + """Generate a cryptographically secure device code (256-bit entropy).""" |
| 36 | + return secrets.token_hex(nbytes=32) |
| 37 | + |
| 38 | + |
| 39 | +def generate_user_code(): |
| 40 | + """ |
| 41 | + Generate a human-readable user code in format "XXXX-XXXX". |
| 42 | +
|
| 43 | + Uses base-20 alphabet to avoid ambiguous characters, providing ~34 bits |
| 44 | + of entropy which is sufficient when combined with rate limiting. |
| 45 | + Reference: RFC 8628 §5.1 |
| 46 | + """ |
| 47 | + chars = [secrets.choice(USER_CODE_ALPHABET) for _ in range(USER_CODE_LENGTH)] |
| 48 | + return f"{''.join(chars[:4])}-{''.join(chars[4:])}" |
| 49 | + |
| 50 | + |
| 51 | +# Maximum retries for generating unique codes |
| 52 | +MAX_CODE_GENERATION_RETRIES = 10 |
| 53 | + |
| 54 | + |
| 55 | +class UserCodeCollisionError(Exception): |
| 56 | + """Raised when unable to generate a unique user code after maximum retries.""" |
| 57 | + |
| 58 | + pass |
| 59 | + |
| 60 | + |
| 61 | +class DeviceCodeStatus: |
| 62 | + """Status values for device authorization codes.""" |
| 63 | + |
| 64 | + PENDING = "pending" |
| 65 | + APPROVED = "approved" |
| 66 | + DENIED = "denied" |
| 67 | + |
| 68 | + |
| 69 | +@control_silo_model |
| 70 | +class ApiDeviceCode(Model): |
| 71 | + """ |
| 72 | + Device authorization code for OAuth 2.0 Device Flow (RFC 8628). |
| 73 | +
|
| 74 | + This model stores the state of a device authorization request, which allows |
| 75 | + headless devices (CLIs, Docker containers, CI/CD jobs) to obtain OAuth tokens |
| 76 | + by having users authorize on a separate device with a browser. |
| 77 | +
|
| 78 | + Flow: |
| 79 | + 1. Device requests authorization via POST /oauth/device_authorization |
| 80 | + 2. Server returns device_code (secret) and user_code (human-readable) |
| 81 | + 3. Device displays user_code and verification_uri to user |
| 82 | + 4. Device polls POST /oauth/token with device_code |
| 83 | + 5. User visits verification_uri, enters user_code, and approves/denies |
| 84 | + 6. On approval, device receives access token on next poll |
| 85 | +
|
| 86 | + Reference: https://datatracker.ietf.org/doc/html/rfc8628 |
| 87 | + """ |
| 88 | + |
| 89 | + __relocation_scope__ = RelocationScope.Global |
| 90 | + |
| 91 | + # Device code: secret, high-entropy code used for token polling (RFC 8628 §3.2) |
| 92 | + device_code = models.CharField(max_length=64, unique=True, default=generate_device_code) |
| 93 | + |
| 94 | + # User code: human-readable code for user entry (RFC 8628 §3.2) |
| 95 | + # Format: "XXXX-XXXX" using base-20 alphabet |
| 96 | + # Must be unique since users look up by this code |
| 97 | + user_code = models.CharField(max_length=16, unique=True, default=generate_user_code) |
| 98 | + |
| 99 | + # The OAuth application requesting authorization |
| 100 | + application = FlexibleForeignKey("sentry.ApiApplication") |
| 101 | + |
| 102 | + # User who approved the request (set when status changes to APPROVED) |
| 103 | + user = FlexibleForeignKey("sentry.User", null=True, on_delete=models.CASCADE) |
| 104 | + |
| 105 | + # Organization selected during approval (for org-level access apps) |
| 106 | + organization_id = HybridCloudForeignKey( |
| 107 | + "sentry.Organization", |
| 108 | + db_index=True, |
| 109 | + null=True, |
| 110 | + on_delete="CASCADE", |
| 111 | + ) |
| 112 | + |
| 113 | + # Requested scopes (space-delimited in requests, stored as array) |
| 114 | + scope_list = ArrayField(models.TextField(), default=list) |
| 115 | + |
| 116 | + # When this device code expires (RFC 8628 §3.2 expires_in) |
| 117 | + expires_at = models.DateTimeField(db_index=True, default=default_expiration) |
| 118 | + |
| 119 | + # Authorization status: pending -> approved/denied |
| 120 | + status = models.CharField(max_length=20, default=DeviceCodeStatus.PENDING) |
| 121 | + |
| 122 | + # Timestamps |
| 123 | + date_added = models.DateTimeField(default=timezone.now) |
| 124 | + |
| 125 | + class Meta: |
| 126 | + app_label = "sentry" |
| 127 | + db_table = "sentry_apidevicecode" |
| 128 | + |
| 129 | + def __str__(self) -> str: |
| 130 | + return f"device_code={self.id}, application={self.application_id}, status={self.status}" |
| 131 | + |
| 132 | + def get_scopes(self) -> list[str]: |
| 133 | + """Return the list of requested scopes.""" |
| 134 | + return self.scope_list |
| 135 | + |
| 136 | + def has_scope(self, scope: str) -> bool: |
| 137 | + """Check if a specific scope was requested.""" |
| 138 | + return scope in self.scope_list |
| 139 | + |
| 140 | + def is_expired(self) -> bool: |
| 141 | + """Check if the device code has expired.""" |
| 142 | + return timezone.now() >= self.expires_at |
| 143 | + |
| 144 | + def is_pending(self) -> bool: |
| 145 | + """Check if the device code is still awaiting user action.""" |
| 146 | + return self.status == DeviceCodeStatus.PENDING |
| 147 | + |
| 148 | + def is_approved(self) -> bool: |
| 149 | + """Check if the user has approved this device code.""" |
| 150 | + return self.status == DeviceCodeStatus.APPROVED |
| 151 | + |
| 152 | + def is_denied(self) -> bool: |
| 153 | + """Check if the user has denied this device code.""" |
| 154 | + return self.status == DeviceCodeStatus.DENIED |
| 155 | + |
| 156 | + @classmethod |
| 157 | + def sanitize_relocation_json( |
| 158 | + cls, json: Any, sanitizer: Sanitizer, model_name: NormalizedModelName | None = None |
| 159 | + ) -> None: |
| 160 | + model_name = get_model_name(cls) if model_name is None else model_name |
| 161 | + super().sanitize_relocation_json(json, sanitizer, model_name) |
| 162 | + |
| 163 | + sanitizer.set_string( |
| 164 | + json, SanitizableField(model_name, "device_code"), lambda _: generate_device_code() |
| 165 | + ) |
| 166 | + sanitizer.set_string( |
| 167 | + json, SanitizableField(model_name, "user_code"), lambda _: generate_user_code() |
| 168 | + ) |
| 169 | + |
| 170 | + @classmethod |
| 171 | + def create_with_retry(cls, application, scope_list: list[str] | None = None) -> ApiDeviceCode: |
| 172 | + """ |
| 173 | + Create a new device code with retry logic for user code collisions. |
| 174 | +
|
| 175 | + Since user codes have ~34 bits of entropy, collisions are rare but possible. |
| 176 | + This method retries with new codes if a collision occurs. |
| 177 | +
|
| 178 | + Args: |
| 179 | + application: The ApiApplication requesting authorization |
| 180 | + scope_list: Optional list of requested scopes |
| 181 | +
|
| 182 | + Returns: |
| 183 | + A new ApiDeviceCode instance |
| 184 | +
|
| 185 | + Raises: |
| 186 | + UserCodeCollisionError: If unable to generate a unique code after max retries |
| 187 | + """ |
| 188 | + if scope_list is None: |
| 189 | + scope_list = [] |
| 190 | + |
| 191 | + for attempt in range(MAX_CODE_GENERATION_RETRIES): |
| 192 | + try: |
| 193 | + return cls.objects.create( |
| 194 | + application=application, |
| 195 | + scope_list=scope_list, |
| 196 | + ) |
| 197 | + except IntegrityError: |
| 198 | + # Collision on device_code or user_code, try again |
| 199 | + if attempt == MAX_CODE_GENERATION_RETRIES - 1: |
| 200 | + raise UserCodeCollisionError( |
| 201 | + f"Unable to generate unique device code after {MAX_CODE_GENERATION_RETRIES} attempts" |
| 202 | + ) |
| 203 | + continue |
| 204 | + |
| 205 | + # This should never be reached, but satisfies type checker |
| 206 | + raise UserCodeCollisionError("Unable to generate unique device code") |
0 commit comments