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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
"""
API Keys Service

This module provides functionality for managing API keys including:
- Creating new API keys with UUIDs
- Validating API keys for authentication
- Managing expiration and revocation
- CRUD operations for user API keys
"""

import asyncio
from datetime import datetime, timezone, timedelta
from typing import Optional, List, Dict
from uuid import UUID, uuid4
import secrets
import string
import hmac
import hashlib
import time
from collections import OrderedDict
from pydantic import BaseModel, Field, field_validator
from fastapi import HTTPException
from core.utils.logger import logger
from core.services.supabase import DBConnection
from core.services import redis
from core.utils.config import config


class APIKeyStatus:
    ACTIVE = "active"
    REVOKED = "revoked"
    EXPIRED = "expired"


class APIKeyCreateRequest(BaseModel):
    """Request model for creating a new API key"""

    title: str = Field(
        ...,
        min_length=1,
        max_length=255,
        description="Human-readable title for the API key",
    )
    description: Optional[str] = Field(
        None, description="Optional description for the API key"
    )
    expires_in_days: Optional[int] = Field(
        None, gt=0, le=365, description="Number of days until expiration (max 365)"
    )

    @field_validator("title")
    def validate_title(cls, v):
        if not v or not v.strip():
            raise ValueError("Title cannot be empty")
        return v.strip()


class APIKeyResponse(BaseModel):
    """Response model for API key information (without the secret key)"""

    key_id: UUID
    public_key: str
    title: str
    description: Optional[str]
    status: str
    expires_at: Optional[datetime]
    last_used_at: Optional[datetime]
    created_at: datetime


class APIKeyCreateResponse(BaseModel):
    """Response model for newly created API key (includes both keys)"""

    key_id: UUID
    public_key: str
    secret_key: str  # Only returned on creation
    title: str
    description: Optional[str]
    status: str
    expires_at: Optional[datetime]
    created_at: datetime


class APIKeyValidationResult(BaseModel):
    """Result of API key validation"""

    is_valid: bool
    account_id: Optional[UUID] = None
    key_id: Optional[UUID] = None
    error_message: Optional[str] = None


class APIKeyService:
    """
    Service for managing API keys with performance optimizations

    Performance Features:
    - HMAC-SHA256 hashing (100x faster than bcrypt)
    - Redis caching for validation results (2min TTL)
    - Throttled last_used_at updates (max once per 15min per key, configurable)
    - Cached user lookups (5min TTL)
    - Asynchronous operations where possible
    - In-memory fallback throttling when Redis unavailable
    - Streamlined database schema without unnecessary triggers
    """

    # Class-level in-memory throttle cache (fallback when Redis unavailable)
    # LRU cache with max size to prevent unbounded growth
    _throttle_cache: OrderedDict[str, float] = OrderedDict()
    _max_throttle_cache_size = 500  # Maximum entries before cleanup

    def __init__(self, db: DBConnection):
        self.db = db

    def _generate_key_pair(self) -> tuple[str, str]:
        """
        Generate a public key and secret key pair

        Returns:
            tuple: (public_key, secret_key) where public_key starts with 'pk_' and secret_key starts with 'sk_'
        """
        # Generate random strings for both keys
        pk_suffix = "".join(
            secrets.choice(string.ascii_letters + string.digits) for _ in range(32)
        )
        sk_suffix = "".join(
            secrets.choice(string.ascii_letters + string.digits) for _ in range(32)
        )

        public_key = f"pk_{pk_suffix}"
        secret_key = f"sk_{sk_suffix}"

        return public_key, secret_key

    def _get_secret_key(self) -> str:
        """Get the secret key for HMAC hashing"""
        return config.API_KEY_SECRET

    def _hash_secret_key(self, secret_key: str) -> str:
        """
        Hash a secret key using HMAC-SHA256 (much faster than bcrypt)

        Args:
            secret_key: The secret key to hash

        Returns:
            str: The HMAC-SHA256 hash of the secret key
        """
        secret = self._get_secret_key().encode("utf-8")
        return hmac.new(secret, secret_key.encode("utf-8"), hashlib.sha256).hexdigest()

    def _verify_secret_key(self, secret_key: str, hashed_key: str) -> bool:
        """
        Verify a secret key against its hash using constant-time comparison

        Args:
            secret_key: The secret key to verify
            hashed_key: The stored hash

        Returns:
            bool: True if the secret key matches the hash
        """
        try:
            expected_hash = self._hash_secret_key(secret_key)
            return hmac.compare_digest(expected_hash, hashed_key)
        except Exception:
            return False

    async def create_api_key(
        self, account_id: UUID, request: APIKeyCreateRequest
    ) -> APIKeyCreateResponse:
        """
        Create a new API key for the specified account

        Args:
            account_id: The account ID to create the key for
            request: The API key creation request

        Returns:
            APIKeyCreateResponse containing the new API key details including both keys
        """
        try:
            # Calculate expiration date if specified
            expires_at = None
            if request.expires_in_days:
                expires_at = datetime.now(timezone.utc) + timedelta(
                    days=request.expires_in_days
                )

            # Generate public and secret key pair
            public_key, secret_key = self._generate_key_pair()

            # Hash the secret key for storage
            secret_key_hash = self._hash_secret_key(secret_key)

            # Insert into database
            client = await self.db.client
            result = (
                await client.table("api_keys")
                .insert(
                    {
                        "public_key": public_key,
                        "secret_key_hash": secret_key_hash,
                        "account_id": str(account_id),
                        "title": request.title,
                        "description": request.description,
                        "expires_at": expires_at.isoformat() if expires_at else None,
                        "status": APIKeyStatus.ACTIVE,
                    }
                )
                .execute()
            )

            if not result.data:
                raise HTTPException(status_code=500, detail="Failed to create API key")

            key_data = result.data[0]

            logger.debug(
                "API key created successfully",
                account_id=str(account_id),
                key_id=key_data["key_id"],
                public_key=public_key,
                title=request.title,
            )

            return APIKeyCreateResponse(
                key_id=UUID(key_data["key_id"]),
                public_key=public_key,
                secret_key=secret_key,  # Only returned on creation
                title=key_data["title"],
                description=key_data["description"],
                status=key_data["status"],
                expires_at=(
                    datetime.fromisoformat(key_data["expires_at"])
                    if key_data["expires_at"]
                    else None
                ),
                created_at=datetime.fromisoformat(key_data["created_at"]),
            )

        except Exception as e:
            logger.error(f"Error creating API key: {e}", exc_info=True)
            raise HTTPException(status_code=500, detail="Failed to create API key")

    async def list_api_keys(self, account_id: UUID) -> List[APIKeyResponse]:
        """
        List all API keys for the specified account

        Args:
            account_id: The account ID to list keys for

        Returns:
            List of APIKeyResponse objects
        """
        try:
            client = await self.db.client
            result = (
                await client.table("api_keys")
                .select(
                    "key_id, public_key, title, description, status, expires_at, last_used_at, created_at"
                )
                .eq("account_id", str(account_id))
                .order("created_at", desc=True)
                .execute()
            )

            api_keys = []
            for key_data in result.data:
                api_keys.append(
                    APIKeyResponse(
                        key_id=UUID(key_data["key_id"]),
                        public_key=key_data["public_key"],
                        title=key_data["title"],
                        description=key_data["description"],
                        status=key_data["status"],
                        expires_at=(
                            datetime.fromisoformat(key_data["expires_at"])
                            if key_data["expires_at"]
                            else None
                        ),
                        last_used_at=(
                            datetime.fromisoformat(key_data["last_used_at"])
                            if key_data["last_used_at"]
                            else None
                        ),
                        created_at=datetime.fromisoformat(key_data["created_at"]),
                    )
                )

            return api_keys

        except Exception as e:
            logger.error(f"Error listing API keys: {e}", exc_info=True)
            raise HTTPException(status_code=500, detail="Failed to list API keys")

    async def revoke_api_key(self, account_id: UUID, key_id: UUID) -> bool:
        """
        Revoke an API key

        Args:
            account_id: The account ID that owns the key
            key_id: The ID of the key to revoke

        Returns:
            True if successful, False otherwise
        """
        try:
            client = await self.db.client
            result = (
                await client.table("api_keys")
                .update({"status": APIKeyStatus.REVOKED})
                .eq("key_id", str(key_id))
                .eq("account_id", str(account_id))
                .execute()
            )

            if not result.data:
                raise HTTPException(status_code=404, detail="API key not found")

            logger.debug(
                "API key revoked successfully",
                account_id=str(account_id),
                key_id=str(key_id),
            )

            return True

        except HTTPException:
            raise
        except Exception as e:
            logger.error(f"Error revoking API key: {e}", exc_info=True)
            raise HTTPException(status_code=500, detail="Failed to revoke API key")

    async def validate_api_key(
        self, public_key: str, secret_key: str
    ) -> APIKeyValidationResult:
        """
        Validate an API key pair with Redis caching for performance

        Args:
            public_key: The public key (starts with 'pk_')
            secret_key: The secret key (starts with 'sk_')

        Returns:
            APIKeyValidationResult with validation status and account info
        """
        try:
            # Validate key format
            if not public_key.startswith("pk_") or not secret_key.startswith("sk_"):
                return APIKeyValidationResult(
                    is_valid=False, error_message="Invalid API key format"
                )

            # Check Redis cache first (cache key includes secret hash for security)
            cache_key = f"api_key:{public_key}:{self._hash_secret_key(secret_key)[:8]}"

            try:
                cached_result = await redis.get(cache_key)
                if cached_result:
                    import json

                    cached_data = json.loads(cached_result)
                    logger.debug(f"API key validation cache hit for {public_key}")
                    return APIKeyValidationResult(
                        is_valid=cached_data["is_valid"],
                        account_id=(
                            UUID(cached_data["account_id"])
                            if cached_data["account_id"]
                            else None
                        ),
                        key_id=(
                            UUID(cached_data["key_id"])
                            if cached_data["key_id"]
                            else None
                        ),
                        error_message=cached_data.get("error_message"),
                    )
            except Exception as e:
                logger.warning(f"Redis cache lookup failed: {e}")
                # Continue without cache

            client = await self.db.client

            # Single optimized query with join to get user info
            result = (
                await client.table("api_keys")
                .select("key_id, account_id, status, expires_at, secret_key_hash")
                .eq("public_key", public_key)
                .execute()
            )

            if not result.data:
                validation_result = APIKeyValidationResult(
                    is_valid=False, error_message="API key not found"
                )
                await self._cache_validation_result(
                    cache_key, validation_result, ttl=300
                )  # Cache negative results for 5 min
                return validation_result

            key_data = result.data[0]

            # Check if key is expired first (faster than status check)
            if key_data["expires_at"]:
                expires_at = datetime.fromisoformat(key_data["expires_at"])
                if expires_at < datetime.now(timezone.utc):
                    validation_result = APIKeyValidationResult(
                        is_valid=False, error_message="API key expired"
                    )
                    await self._cache_validation_result(
                        cache_key, validation_result, ttl=3600
                    )  # Cache expired for 1 hour
                    return validation_result

            # Check if key is active
            if key_data["status"] != APIKeyStatus.ACTIVE:
                validation_result = APIKeyValidationResult(
                    is_valid=False, error_message=f"API key is {key_data['status']}"
                )
                await self._cache_validation_result(
                    cache_key, validation_result, ttl=3600
                )  # Cache inactive for 1 hour
                return validation_result

            # Verify the secret key against the stored hash
            if not self._verify_secret_key(secret_key, key_data["secret_key_hash"]):
                validation_result = APIKeyValidationResult(
                    is_valid=False, error_message="Invalid secret key"
                )
                await self._cache_validation_result(
                    cache_key, validation_result, ttl=300
                )  # Cache invalid for 5 min
                return validation_result

            # Success case
            validation_result = APIKeyValidationResult(
                is_valid=True,
                account_id=UUID(key_data["account_id"]),
                key_id=UUID(key_data["key_id"]),
            )

            # Cache successful validation for 2 minutes
            await self._cache_validation_result(cache_key, validation_result, ttl=120)

            # Update last used timestamp with throttling to prevent DB spam
            # (max once per 15 minutes per key, configurable via config.API_KEY_LAST_USED_THROTTLE_SECONDS)
            asyncio.create_task(self._update_last_used_throttled(key_data["key_id"]))

            return validation_result

        except Exception as e:
            logger.error(f"Error validating API key: {e}", exc_info=True)
            return APIKeyValidationResult(
                is_valid=False, error_message="Internal server error"
            )

    async def _cache_validation_result(
        self, cache_key: str, result: APIKeyValidationResult, ttl: int = 120
    ):
        """Cache validation result in Redis"""
        try:
            import json

            cache_data = {
                "is_valid": result.is_valid,
                "account_id": str(result.account_id) if result.account_id else None,
                "key_id": str(result.key_id) if result.key_id else None,
                "error_message": result.error_message,
            }
            await redis.setex(cache_key, ttl, json.dumps(cache_data))
        except Exception as e:
            logger.warning(f"Failed to cache validation result: {e}")

    async def _update_last_used_throttled(self, key_id: str):
        """Update last used timestamp with throttling to reduce DB load"""
        throttle_interval = config.API_KEY_LAST_USED_THROTTLE_SECONDS
        current_time = time.time()

        # Try Redis first - optimized to use SET NX pattern (1 call instead of 2)
        try:
            throttle_key = f"last_used_throttle:{key_id}"

            # Use SET with NX (set-if-not-exists) to atomically check and set
            # This reduces from 2 Redis calls (GET + SETEX) to 1 call
            # Returns False if key already exists (throttled), True if set successfully
            was_set = await redis.set(throttle_key, "1", ex=throttle_interval, nx=True, timeout=2.0)
            if not was_set:
                # Key already exists - already updated within throttle interval, skip
                return

        except Exception as redis_error:
            # Fallback to in-memory throttling when Redis unavailable
            logger.debug(
                f"Redis unavailable for throttling, using in-memory fallback: {redis_error}"
            )

            # Clean up expired entries and enforce LRU limit
            cutoff_time = current_time - (throttle_interval * 2)  # Keep extra buffer
            
            # Remove expired entries
            expired_keys = [
                k for k, v in self._throttle_cache.items() 
                if v < cutoff_time
            ]
            for k in expired_keys:
                self._throttle_cache.pop(k, None)
            
            # Enforce LRU limit (remove oldest if over limit)
            while len(self._throttle_cache) > self._max_throttle_cache_size:
                self._throttle_cache.popitem(last=False)  # Remove oldest

            # Check in-memory throttle
            last_update_time = self._throttle_cache.get(key_id, 0)
            if current_time - last_update_time < throttle_interval:
                # Already updated within throttle interval, skip
                return

            # Set in-memory throttle (move to end for LRU)
            if key_id in self._throttle_cache:
                self._throttle_cache.move_to_end(key_id)
            self._throttle_cache[key_id] = current_time

        # Update database
        try:
            client = await self.db.client
            await client.table("api_keys").update(
                {"last_used_at": datetime.now(timezone.utc).isoformat()}
            ).eq("key_id", key_id).execute()

            logger.debug(f"Updated last_used_at for key {key_id}")

        except Exception as e:
            logger.warning(f"Failed to update last_used_at for key {key_id}: {e}")

    async def _update_last_used_async(self, key_id: str):
        """Legacy method - kept for backwards compatibility"""
        await self._update_last_used_throttled(key_id)

    async def _clear_throttle(self, key_id: str):
        """Clear the throttle for a specific key (useful for testing)"""
        try:
            throttle_key = f"last_used_throttle:{key_id}"
            await redis.delete(throttle_key)
            logger.debug(f"Cleared throttle for key {key_id}")
        except Exception as e:
            logger.warning(f"Failed to clear throttle for key {key_id}: {e}")

    async def delete_api_key(self, account_id: UUID, key_id: UUID) -> bool:
        """
        Delete an API key permanently

        Args:
            account_id: The account ID that owns the key
            key_id: The ID of the key to delete

        Returns:
            True if successful, False otherwise
        """
        try:
            client = await self.db.client
            result = (
                await client.table("api_keys")
                .delete()
                .eq("key_id", str(key_id))
                .eq("account_id", str(account_id))
                .execute()
            )

            if not result.data:
                raise HTTPException(status_code=404, detail="API key not found")

            logger.debug(
                "API key deleted successfully",
                account_id=str(account_id),
                key_id=str(key_id),
            )

            return True

        except HTTPException:
            raise
        except Exception as e:
            logger.error(f"Error deleting API key: {e}", exc_info=True)
            raise HTTPException(status_code=500, detail="Failed to delete API key")