#!/usr/bin/env python3 """ scripts/migrar_vault_v3.py — Migración de credenciales v1 → v3 (PBKDF2 + envelope encryption). Qué hace: 1. Lee FERNET_KEY del .env 2. Conecta a la DB y lista todos los tenants con credentials_enc 3. Saltea tenants ya en v3 (JSON, empieza con '{') 4. Para cada tenant v1: descifra con el algoritmo legacy, re-cifra con v3 5. Si algún tenant falla al descifrar: aborta SIN escribir nada 6. Si todo OK: hace backup de la DB, aplica todos los UPDATE en una transacción atómica Uso: python scripts/migrar_vault_v3.py # migra de verdad python scripts/migrar_vault_v3.py --dry-run # solo muestra qué haría, no escribe Seguridad: - Las credenciales descifradas NUNCA se escriben en disco ni en logs - El backup de la DB se hace ANTES de cualquier modificación - Si el proceso se interrumpe a mitad, el backup permite restaurar """ from __future__ import annotations import argparse import asyncio import shutil import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent)) async def main() -> None: parser = argparse.ArgumentParser( description="Migra credenciales de vault v1 a v3 (PBKDF2 + envelope encryption)" ) parser.add_argument( "--dry-run", action="store_true", help="Muestra qué haría sin escribir nada en la DB", ) args = parser.parse_args() env_path = Path(".env") if not env_path.exists(): print("ERROR: No encontré .env. Ejecutá desde el directorio raíz del proyecto.") sys.exit(1) # Leer FERNET_KEY del .env import re env_contenido = env_path.read_text(encoding="utf-8") m = re.search(r"^FERNET_KEY=(.+)$", env_contenido, re.MULTILINE) if not m or not m.group(1).strip(): print("ERROR: FERNET_KEY no encontrada o vacía en .env") sys.exit(1) fernet_key = m.group(1).strip() from config import get_settings from database import run_migrations, get_conn import vault settings = get_settings() await run_migrations(settings.db_path) conn = get_conn() # Traer todos los tenants con credentials_enc async with conn.execute( "SELECT chat_id, credentials_enc FROM tenants WHERE credentials_enc IS NOT NULL" ) as cur: tenants = list(await cur.fetchall()) if not tenants: print("No hay tenants con credenciales en la DB. Nada que migrar.") return total = len(tenants) ya_v3 = 0 a_migrar: list[tuple[int, str]] = [] # (chat_id, credentials_enc_v1) for row in tenants: if vault.es_formato_v3(row["credentials_enc"]): ya_v3 += 1 else: a_migrar.append((row["chat_id"], row["credentials_enc"])) print() print("=== Migración vault v1 → v3 ===") print() print(f" Tenants totales: {total}") print(f" Ya en v3: {ya_v3} (se saltean)") print(f" A migrar (v1): {len(a_migrar)}") print() if not a_migrar: print(" Todos los tenants ya están en v3. Nada que hacer.") return if args.dry_run: print(" [DRY RUN] Los siguientes tenants serían migrados:") for chat_id, _ in a_migrar: print(f" chat_id={chat_id}") print() print(" [DRY RUN] No se escribió nada.") return # Descifrar todos ANTES de tocar la DB — abortar si alguno falla actualizaciones: list[tuple[str, int]] = [] # (nuevo_enc, chat_id) errores: list[tuple[int, str]] = [] print(" Verificando que todos los v1 sean descifrables...") for chat_id, credentials_enc in a_migrar: try: usuario, password = vault.descifrar_credenciales(chat_id, credentials_enc, fernet_key) nuevo_enc = vault.cifrar_credenciales(chat_id, usuario, password, fernet_key) actualizaciones.append((nuevo_enc, chat_id)) del usuario, password # no dejar en memoria más de lo necesario except ValueError as e: errores.append((chat_id, str(e))) print(f" ERROR tenant {chat_id}: {e}") if errores: print() print(f" {len(errores)} tenant(s) no pudieron descifrarse.") print(" La DB NO fue modificada. Revisá los errores de arriba.") sys.exit(1) print(f" OK — {len(actualizaciones)} tenant(s) listos para migrar.") print() # Confirmar confirmar = input(" Escribí 'migrar' para confirmar y escribir en la DB: ").strip() if confirmar != "migrar": print(" Operación cancelada.") sys.exit(0) # Backup de la DB ANTES de cualquier escritura db_path = settings.db_path bak_path = db_path.with_suffix(".db.bak") shutil.copy2(db_path, bak_path) print(f"\n Backup guardado en {bak_path}") # Aplicar todos los UPDATE en una sola transacción for nuevo_enc, chat_id in actualizaciones: await conn.execute( "UPDATE tenants SET credentials_enc = ? WHERE chat_id = ?", (nuevo_enc, chat_id), ) await conn.commit() print(f" {len(actualizaciones)} tenant(s) migrados a v3.") print() print(" ✅ Migración completada.") print(f" Backup de la DB anterior: {bak_path}") print() print(" Próximo paso: reiniciar el bot.") print(" systemctl restart pedrito (en VPS con systemd)") print(" docker compose restart (en VPS con Docker)") print(" o Ctrl+C y uv run python main.py (en local)") print() if __name__ == "__main__": asyncio.run(main())