""" API Key management system for authentication and rate limiting. """ import secrets import sqlite3 import time from datetime import datetime, timedelta from typing import Dict, List, Optional, Tuple from dataclasses import dataclass @dataclass class APIKey: """API Key data model.""" key: str name: str created_at: datetime last_used: Optional[datetime] request_count: int rate_limit: int # requests per minute is_active: bool class APIKeyManager: """Manages API keys, validation, and rate limiting.""" def __init__(self, db_path: str = "app/data/api_keys.db"): self.db_path = db_path self._init_database() def _init_database(self) -> None: """Initialize the API keys database.""" with sqlite3.connect(self.db_path) as conn: conn.execute(""" CREATE TABLE IF NOT EXISTS api_keys ( key TEXT PRIMARY KEY, name TEXT NOT NULL, created_at TIMESTAMP NOT NULL, last_used TIMESTAMP, request_count INTEGER DEFAULT 0, rate_limit INTEGER DEFAULT 100, is_active BOOLEAN DEFAULT 1 ) """) conn.execute(""" CREATE TABLE IF NOT EXISTS rate_limits ( key TEXT NOT NULL, minute_window INTEGER NOT NULL, request_count INTEGER DEFAULT 0, PRIMARY KEY (key, minute_window), FOREIGN KEY (key) REFERENCES api_keys (key) ) """) def generate_api_key(self, name: str, rate_limit: int = 100) -> str: """Generate a new API key.""" # Generate a secure random key api_key = f"is_{secrets.token_urlsafe(32)}" with sqlite3.connect(self.db_path) as conn: conn.execute(""" INSERT INTO api_keys (key, name, created_at, rate_limit) VALUES (?, ?, ?, ?) """, (api_key, name, datetime.now(), rate_limit)) return api_key def validate_api_key(self, api_key: str) -> bool: """Validate if an API key exists and is active.""" with sqlite3.connect(self.db_path) as conn: cursor = conn.execute(""" SELECT is_active FROM api_keys WHERE key = ? """, (api_key,)) result = cursor.fetchone() return result is not None and result[0] == 1 def get_api_key_info(self, api_key: str) -> Optional[APIKey]: """Get API key information.""" with sqlite3.connect(self.db_path) as conn: cursor = conn.execute(""" SELECT key, name, created_at, last_used, request_count, rate_limit, is_active FROM api_keys WHERE key = ? """, (api_key,)) result = cursor.fetchone() if not result: return None return APIKey( key=result[0], name=result[1], created_at=datetime.fromisoformat(result[2]), last_used=datetime.fromisoformat(result[3]) if result[3] else None, request_count=result[4], rate_limit=result[5], is_active=bool(result[6]) ) def check_rate_limit(self, api_key: str) -> Tuple[bool, int, int]: """ Check if API key is within rate limits. Returns: (is_allowed, current_count, limit) """ current_minute = int(time.time() // 60) with sqlite3.connect(self.db_path) as conn: # Get rate limit for this key cursor = conn.execute(""" SELECT rate_limit FROM api_keys WHERE key = ? AND is_active = 1 """, (api_key,)) result = cursor.fetchone() if not result: return False, 0, 0 rate_limit = result[0] # Get current request count for this minute cursor = conn.execute(""" SELECT request_count FROM rate_limits WHERE key = ? AND minute_window = ? """, (api_key, current_minute)) result = cursor.fetchone() current_count = result[0] if result else 0 # Check if within limit if current_count >= rate_limit: return False, current_count, rate_limit return True, current_count, rate_limit def increment_request_count(self, api_key: str) -> None: """Increment the request count for rate limiting.""" current_minute = int(time.time() // 60) with sqlite3.connect(self.db_path) as conn: # Update rate limit counter conn.execute(""" INSERT INTO rate_limits (key, minute_window, request_count) VALUES (?, ?, 1) ON CONFLICT (key, minute_window) DO UPDATE SET request_count = request_count + 1 """, (api_key, current_minute)) # Update total request count and last used conn.execute(""" UPDATE api_keys SET request_count = request_count + 1, last_used = ? WHERE key = ? """, (datetime.now(), api_key)) def list_api_keys(self) -> List[APIKey]: """List all API keys.""" with sqlite3.connect(self.db_path) as conn: cursor = conn.execute(""" SELECT key, name, created_at, last_used, request_count, rate_limit, is_active FROM api_keys ORDER BY created_at DESC """) keys = [] for row in cursor.fetchall(): keys.append(APIKey( key=row[0], name=row[1], created_at=datetime.fromisoformat(row[2]), last_used=datetime.fromisoformat(row[3]) if row[3] else None, request_count=row[4], rate_limit=row[5], is_active=bool(row[6]) )) return keys def deactivate_api_key(self, api_key: str) -> bool: """Deactivate an API key.""" with sqlite3.connect(self.db_path) as conn: cursor = conn.execute(""" UPDATE api_keys SET is_active = 0 WHERE key = ? """, (api_key,)) return cursor.rowcount > 0 def update_rate_limit(self, api_key: str, new_limit: int) -> bool: """Update the rate limit for an API key.""" with sqlite3.connect(self.db_path) as conn: cursor = conn.execute(""" UPDATE api_keys SET rate_limit = ? WHERE key = ? """, (new_limit, api_key)) return cursor.rowcount > 0 def cleanup_old_rate_limits(self, hours: int = 24) -> None: """Clean up old rate limit records.""" cutoff_time = int((time.time() - hours * 3600) // 60) with sqlite3.connect(self.db_path) as conn: conn.execute(""" DELETE FROM rate_limits WHERE minute_window < ? """, (cutoff_time,)) def get_usage_stats(self) -> Dict[str, any]: """Get usage statistics.""" with sqlite3.connect(self.db_path) as conn: # Total keys cursor = conn.execute("SELECT COUNT(*) FROM api_keys") total_keys = cursor.fetchone()[0] # Active keys cursor = conn.execute("SELECT COUNT(*) FROM api_keys WHERE is_active = 1") active_keys = cursor.fetchone()[0] # Total requests today today = datetime.now().date() cursor = conn.execute(""" SELECT SUM(request_count) FROM api_keys WHERE DATE(last_used) = ? """, (today,)) today_requests = cursor.fetchone()[0] or 0 return { 'total_keys': total_keys, 'active_keys': active_keys, 'today_requests': today_requests, 'timestamp': datetime.now().isoformat() }