|
| 1 | +""" |
| 2 | +Migration script to convert encrypted API keys to hashed format. |
| 3 | +
|
| 4 | +This script: |
| 5 | +1. Decrypts existing API keys from the old encrypted format |
| 6 | +2. Extracts the prefix and secret from the decrypted keys |
| 7 | +3. Hashes the secret using bcrypt |
| 8 | +4. Generates UUID4 for the new primary key |
| 9 | +5. Stores the prefix, hash, and UUID in the new format for backward compatibility |
| 10 | +
|
| 11 | +The format is: "ApiKey {12-char-prefix}{31-char-secret}" (total 43 chars) |
| 12 | +""" |
| 13 | + |
| 14 | +import logging |
| 15 | +import uuid |
| 16 | +from sqlalchemy.orm import Session |
| 17 | +from sqlalchemy import text |
| 18 | +from passlib.context import CryptContext |
| 19 | + |
| 20 | +from app.core.security import decrypt_api_key |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | +# Use the same hash algorithm as APIKeyManager |
| 25 | +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") |
| 26 | + |
| 27 | +# Old format constants |
| 28 | +OLD_PREFIX_NAME = "ApiKey " |
| 29 | +OLD_PREFIX_LENGTH = 12 |
| 30 | +OLD_SECRET_LENGTH = 31 |
| 31 | +OLD_KEY_LENGTH = 43 # Total: 12 + 31 |
| 32 | + |
| 33 | + |
| 34 | +def migrate_api_keys(session: Session, generate_uuid: bool = False) -> None: |
| 35 | + """ |
| 36 | + Migrate all existing API keys from encrypted format to hashed format. |
| 37 | +
|
| 38 | + This function: |
| 39 | + 1. Fetches all API keys with the old 'key' column |
| 40 | + 2. Decrypts each key |
| 41 | + 3. Extracts prefix and secret |
| 42 | + 4. Hashes the secret |
| 43 | + 5. Generates UUID4 for new_id column if generate_uuid is True |
| 44 | + 6. Updates key_prefix, key_hash, and optionally new_id columns |
| 45 | +
|
| 46 | + Args: |
| 47 | + session: SQLAlchemy database session |
| 48 | + generate_uuid: Whether to generate and set UUID for new_id column |
| 49 | + """ |
| 50 | + logger.info( |
| 51 | + "[migrate_api_keys] Starting API key migration from encrypted to hashed format" |
| 52 | + ) |
| 53 | + |
| 54 | + try: |
| 55 | + # Fetch all API keys that have the old 'key' column |
| 56 | + result = session.execute( |
| 57 | + text("SELECT id, key FROM apikey WHERE key IS NOT NULL") |
| 58 | + ) |
| 59 | + api_keys = result.fetchall() |
| 60 | + |
| 61 | + if not api_keys: |
| 62 | + logger.info("[migrate_api_keys] No API keys found to migrate") |
| 63 | + return |
| 64 | + |
| 65 | + logger.info(f"[migrate_api_keys] Found {len(api_keys)} API keys to migrate") |
| 66 | + |
| 67 | + migrated_count = 0 |
| 68 | + failed_count = 0 |
| 69 | + |
| 70 | + for row in api_keys: |
| 71 | + key_id = row[0] |
| 72 | + encrypted_key = row[1] |
| 73 | + |
| 74 | + try: |
| 75 | + # Decrypt the API key |
| 76 | + decrypted_key = decrypt_api_key(encrypted_key) |
| 77 | + |
| 78 | + # Validate format |
| 79 | + if not decrypted_key.startswith(OLD_PREFIX_NAME): |
| 80 | + logger.error( |
| 81 | + f"[migrate_api_keys] Invalid key format for ID {key_id}: " |
| 82 | + f"does not start with '{OLD_PREFIX_NAME}'" |
| 83 | + ) |
| 84 | + failed_count += 1 |
| 85 | + continue |
| 86 | + |
| 87 | + # Extract the key part (after "ApiKey ") |
| 88 | + key_part = decrypted_key[len(OLD_PREFIX_NAME) :] |
| 89 | + |
| 90 | + if len(key_part) != OLD_KEY_LENGTH: |
| 91 | + logger.error( |
| 92 | + f"[migrate_api_keys] Invalid key length for ID {key_id}: " |
| 93 | + f"expected {OLD_KEY_LENGTH}, got {len(key_part)}" |
| 94 | + ) |
| 95 | + failed_count += 1 |
| 96 | + continue |
| 97 | + |
| 98 | + # Extract prefix and secret |
| 99 | + key_prefix = key_part[:OLD_PREFIX_LENGTH] |
| 100 | + secret_key = key_part[OLD_PREFIX_LENGTH:] |
| 101 | + |
| 102 | + # Hash the secret |
| 103 | + key_hash = pwd_context.hash(secret_key) |
| 104 | + |
| 105 | + # Generate UUID if requested |
| 106 | + if generate_uuid: |
| 107 | + new_uuid = uuid.uuid4() |
| 108 | + # Update the record with prefix, hash, and UUID |
| 109 | + session.execute( |
| 110 | + text( |
| 111 | + "UPDATE apikey SET key_prefix = :prefix, key_hash = :hash, new_id = :new_id " |
| 112 | + "WHERE id = :id" |
| 113 | + ), |
| 114 | + { |
| 115 | + "prefix": key_prefix, |
| 116 | + "hash": key_hash, |
| 117 | + "new_id": new_uuid, |
| 118 | + "id": key_id, |
| 119 | + }, |
| 120 | + ) |
| 121 | + else: |
| 122 | + # Update the record with prefix and hash only |
| 123 | + session.execute( |
| 124 | + text( |
| 125 | + "UPDATE apikey SET key_prefix = :prefix, key_hash = :hash " |
| 126 | + "WHERE id = :id" |
| 127 | + ), |
| 128 | + {"prefix": key_prefix, "hash": key_hash, "id": key_id}, |
| 129 | + ) |
| 130 | + |
| 131 | + migrated_count += 1 |
| 132 | + logger.info( |
| 133 | + f"[migrate_api_keys] Successfully migrated key ID {key_id} " |
| 134 | + f"with prefix {key_prefix[:4]}..." |
| 135 | + ) |
| 136 | + |
| 137 | + except Exception as e: |
| 138 | + logger.error( |
| 139 | + f"[migrate_api_keys] Failed to migrate key ID {key_id}: {str(e)}", |
| 140 | + exc_info=True, |
| 141 | + ) |
| 142 | + failed_count += 1 |
| 143 | + continue |
| 144 | + |
| 145 | + logger.info( |
| 146 | + f"[migrate_api_keys] Migration completed: " |
| 147 | + f"{migrated_count} successful, {failed_count} failed" |
| 148 | + ) |
| 149 | + |
| 150 | + except Exception as e: |
| 151 | + logger.error( |
| 152 | + f"[migrate_api_keys] Fatal error during migration: {str(e)}", exc_info=True |
| 153 | + ) |
| 154 | + raise |
| 155 | + |
| 156 | + |
| 157 | +def verify_migration(session: Session) -> bool: |
| 158 | + """ |
| 159 | + Verify that all API keys have been migrated successfully. |
| 160 | +
|
| 161 | + Args: |
| 162 | + session: SQLAlchemy database session |
| 163 | +
|
| 164 | + Returns: |
| 165 | + bool: True if all keys are migrated, False otherwise |
| 166 | + """ |
| 167 | + try: |
| 168 | + # Check for any keys with NULL key_prefix or key_hash |
| 169 | + result = session.execute( |
| 170 | + text( |
| 171 | + "SELECT COUNT(*) FROM apikey " |
| 172 | + "WHERE key_prefix IS NULL OR key_hash IS NULL" |
| 173 | + ) |
| 174 | + ) |
| 175 | + null_count = result.scalar() |
| 176 | + |
| 177 | + if null_count > 0: |
| 178 | + logger.warning( |
| 179 | + f"[verify_migration] Found {null_count} API keys with NULL " |
| 180 | + "key_prefix or key_hash" |
| 181 | + ) |
| 182 | + return False |
| 183 | + |
| 184 | + # Check total count |
| 185 | + result = session.execute(text("SELECT COUNT(*) FROM apikey")) |
| 186 | + total_count = result.scalar() |
| 187 | + |
| 188 | + logger.info( |
| 189 | + f"[verify_migration] All {total_count} API keys have been " |
| 190 | + "successfully migrated" |
| 191 | + ) |
| 192 | + return True |
| 193 | + |
| 194 | + except Exception as e: |
| 195 | + logger.error( |
| 196 | + f"[verify_migration] Error verifying migration: {str(e)}", exc_info=True |
| 197 | + ) |
| 198 | + return False |
0 commit comments