Compare commits
4 Commits
v0.3.1
...
f3fd871874
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3fd871874 | ||
|
|
f5f7fdc179 | ||
|
|
0aa1365659 | ||
|
|
05b2f84eb8 |
22
CHANGELOG.md
22
CHANGELOG.md
@@ -11,6 +11,28 @@ Versiones: [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## [0.4.0] — 2026-05-26
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- **Envelope encryption v3 en `vault.py`** — credenciales cifradas en dos capas independientes:
|
||||||
|
- DEK (Data Encryption Key): 32 bytes aleatorios, única por operación de cifrado.
|
||||||
|
- Wrapping Key: derivada de `FERNET_KEY` con PBKDF2-HMAC-SHA256, 600k iteraciones, salt de 16 bytes aleatorio por tenant. ~200ms por derivación — fuerza bruta inviable incluso con GPU.
|
||||||
|
- Formato en DB: `{"v":3,"s":"<salt_b64>","k":"<dek_enc>","p":"<payload_enc>"}`
|
||||||
|
- Propiedades: robar la DB sin `FERNET_KEY` es inútil; robar `FERNET_KEY` sin la DB también.
|
||||||
|
- **Cache de wrapping keys** (`lru_cache`) — evita ejecutar PBKDF2 600k iter por cada tenant en cada ciclo del poller. Cache key incluye fingerprint del KEK para invalidar si cambia `FERNET_KEY`.
|
||||||
|
- **Compatibilidad v1 preservada** — `descifrar_credenciales` detecta automáticamente formato v1 (Fernet token puro) vs v3 (JSON). No se generan nuevas v1.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **`scripts/migrar_vault_v3.py`** — migración segura de credenciales v1 → v3:
|
||||||
|
- Verifica que todos los tenants v1 sean descifrables ANTES de tocar la DB (aborta si alguno falla).
|
||||||
|
- Backup automático de la DB antes de cualquier escritura.
|
||||||
|
- Flag `--dry-run` para ver qué haría sin modificar nada.
|
||||||
|
- Commit atómico: o migra todos o no migra ninguno.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## [0.3.1] — 2026-05-26
|
## [0.3.1] — 2026-05-26
|
||||||
|
|
||||||
### Security
|
### Security
|
||||||
|
|||||||
63
CLAUDE.md
63
CLAUDE.md
@@ -47,16 +47,55 @@ Toda llamada a `logger.*()` con datos externos pasa por acá.
|
|||||||
|
|
||||||
## Arquitectura
|
## Arquitectura
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
ABOGADO["👤 Abogado"]
|
||||||
|
TG(["Telegram API"])
|
||||||
|
CSJ(["apps.csj.gov.py · PJ"])
|
||||||
|
|
||||||
|
subgraph VPS ["VPS — Ubuntu 22.04"]
|
||||||
|
NGX["🔐 Nginx\nSSL · 30 r/s webhook · 10 r/min health\nX-Content-Type-Options · X-Frame-Options"]
|
||||||
|
|
||||||
|
subgraph DOCKER ["🐳 Docker container"]
|
||||||
|
WH["POST /webhook\n→ 404 si token inválido\nsecrets.compare_digest"]
|
||||||
|
HL["GET /health\npúblico: status + timestamp"]
|
||||||
|
HH["GET /health/history\nBearer auth · chat_id enmascarado SHA256"]
|
||||||
|
ONB["Onboarding FSM · 8 pasos\ninvite atómico UPDATE WHERE usado=0\ntiming ≥800ms · compare_digest"]
|
||||||
|
CMD["Comandos\n/notif · /exp · /pdf · /estado · /ayuda"]
|
||||||
|
POLLER["Poller · APScheduler\nmulti-tenant · lun-vie 7-18h"]
|
||||||
|
VAULT["🔐 vault.py\nPBKDF2-SHA256 600k iter\nDEK 32B por cifrado · envelope v3"]
|
||||||
|
CFG["🔐 config.py · Settings\nenv vars borradas post-init"]
|
||||||
|
SCRUB["scrub()\ntodo dato externo a logs\npasa por acá antes de escribir"]
|
||||||
|
end
|
||||||
|
|
||||||
|
DB[("pasante.db\ntenants · audit_log\ninvite_codes · migrations")]
|
||||||
|
SNAP["snapshot_{chat_id}.json\ndiff notificaciones por tenant"]
|
||||||
|
end
|
||||||
|
|
||||||
|
ABOGADO <-->|"HTTPS"| TG
|
||||||
|
TG -->|"HTTPS + X-Secret-Token"| NGX
|
||||||
|
NGX --> WH
|
||||||
|
NGX --> HL
|
||||||
|
NGX --> HH
|
||||||
|
WH --> ONB
|
||||||
|
WH --> CMD
|
||||||
|
ONB -->|"cifra credenciales"| VAULT
|
||||||
|
VAULT <-->|"credentials_enc"| DB
|
||||||
|
CMD --> DB
|
||||||
|
HH -->|"audit_log — chat_id enmascarado"| DB
|
||||||
|
POLLER -->|"HTTPS + Bearer + usuario-rol:16"| CSJ
|
||||||
|
CSJ -->|"notificaciones JSON"| POLLER
|
||||||
|
POLLER --> SNAP
|
||||||
|
POLLER -->|"alertas"| TG
|
||||||
|
POLLER -->|"descifra por tenant"| VAULT
|
||||||
|
CFG -.->|"configura"| VAULT
|
||||||
|
CFG -.->|"configura"| POLLER
|
||||||
|
|
||||||
|
classDef secure fill:#fef2f2,stroke:#991b1b,color:#450a0a
|
||||||
|
class NGX,VAULT,CFG,SCRUB secure
|
||||||
```
|
```
|
||||||
main.py ← entrypoint, arranca bot + poller en paralelo
|
|
||||||
config.py ← Settings via pydantic-settings (ÚNICA fuente de config)
|
Ver [SECURITY.md](SECURITY.md) para el diagrama de arquitectura de seguridad detallado.
|
||||||
csj_client.py ← HTTP client del PJ (login + notificaciones, read-only)
|
|
||||||
poller.py ← loop de polling + diff + dispara alertas
|
|
||||||
telegram_bot.py ← envía mensajes y maneja /comandos básicos
|
|
||||||
storage.py ← snapshot en JSON local (sin DB por ahora)
|
|
||||||
utils/
|
|
||||||
sanitize.py ← credential_scrubber() — NUNCA loggear sin pasar por acá
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -68,11 +107,13 @@ utils/
|
|||||||
| HTTP client | `httpx` async |
|
| HTTP client | `httpx` async |
|
||||||
| Bot | `python-telegram-bot v21` async |
|
| Bot | `python-telegram-bot v21` async |
|
||||||
| Scheduler | `APScheduler 3` |
|
| Scheduler | `APScheduler 3` |
|
||||||
| Cifrado | `cryptography` (Fernet) |
|
| Cifrado | `cryptography` (Fernet + PBKDF2) |
|
||||||
|
| HTTP server | `aiohttp>=3.9` (health check + webhook) |
|
||||||
| Config | `pydantic-settings` |
|
| Config | `pydantic-settings` |
|
||||||
| Logging | `structlog` (JSON en prod, ConsoleRenderer en dev) |
|
| Logging | `structlog` (JSON en prod, ConsoleRenderer en dev) |
|
||||||
|
| Infraestructura | Docker + docker-compose |
|
||||||
|
|
||||||
Sin Playwright. Sin Postgres. Sin Redis. Sin LLM. Sin Docker por ahora (opcional).
|
Sin Playwright. Sin Postgres. Sin Redis. Sin LLM.
|
||||||
|
|
||||||
**No introducir librerías fuera de esta lista sin justificación explícita.**
|
**No introducir librerías fuera de esta lista sin justificación explícita.**
|
||||||
|
|
||||||
|
|||||||
21
DEPLOY.md
21
DEPLOY.md
@@ -1069,6 +1069,27 @@ docker compose logs --tail=20
|
|||||||
> diff .env.example .env
|
> diff .env.example .env
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
|
### Actualización especial: migración de credenciales a vault v3 (v0.4.0+)
|
||||||
|
|
||||||
|
Si el servidor tenía abogados registrados **antes de la versión v0.4.0**, sus credenciales en la DB
|
||||||
|
están en formato v1 (cifrado simple). Hay que migrarlas a v3 (PBKDF2 + envelope encryption) **una sola vez**.
|
||||||
|
|
||||||
|
Hacerlo después del `git pull` y **antes** del `docker compose up -d`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Dentro del contenedor (o con uv si no usás Docker):
|
||||||
|
docker compose run --rm pedrito uv run python scripts/migrar_vault_v3.py --dry-run
|
||||||
|
# Verificar que lista los tenants esperados, luego migrar de verdad:
|
||||||
|
docker compose run --rm pedrito uv run python scripts/migrar_vault_v3.py
|
||||||
|
```
|
||||||
|
|
||||||
|
El script:
|
||||||
|
- Verifica que puede descifrar todos los tenants antes de tocar la DB
|
||||||
|
- Hace backup automático de la DB (`data/pasante.db.bak`)
|
||||||
|
- Si algo falla, no escribe nada — la DB original queda intacta
|
||||||
|
|
||||||
|
Si todos los tenants registrados son nuevos (post v0.4.0), este paso no es necesario.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 19. Troubleshooting
|
## 19. Troubleshooting
|
||||||
|
|||||||
179
SECURITY.md
Normal file
179
SECURITY.md
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
# Arquitectura de seguridad — Pedrito Hechakuaa
|
||||||
|
|
||||||
|
Versión actual: **v0.4.1**. Ver [CHANGELOG.md](CHANGELOG.md) para historial.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Defensa en profundidad
|
||||||
|
|
||||||
|
Cada vector de ataque identificado tiene al menos un control en la capa de red,
|
||||||
|
uno en la aplicación, y uno en los datos.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
subgraph THREATS ["Vectores de ataque"]
|
||||||
|
T1["🌐 Red pública\nport scan · DDoS · flood"]
|
||||||
|
T2["📨 Webhook spoofing\nfake Telegram updates"]
|
||||||
|
T3["🔍 Health endpoint\nexfiltración de datos internos"]
|
||||||
|
T4["🔑 Onboarding\nbrute-force de códigos de invitación"]
|
||||||
|
T5["💾 Robo de DB\ncredenciales en texto plano"]
|
||||||
|
T6["🧠 Acceso a proceso\n/proc/pid/environ · docker inspect"]
|
||||||
|
T7["👤 Usuario no registrado\nreconocimiento de comandos"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph DEFENSES ["Controles implementados"]
|
||||||
|
D1["UFW: solo 22/80/443\nNginx rate-limit 30r/s webhook\n10r/min health · security headers"]
|
||||||
|
D2["X-Secret-Token\nsecrets.compare_digest\n→ 404 si falla (no confirma endpoint)"]
|
||||||
|
D3["Bearer auth en /history\nchat_id enmascarado SHA256[:8]\n/health público devuelve mínimo"]
|
||||||
|
D4["UPDATE atómico WHERE usado=0\ntiming mínimo ≥800ms\nsecrets.compare_digest vs master code"]
|
||||||
|
D5["vault.py v3: PBKDF2 + DEK/KEK\nrobar DB sin FERNET_KEY = inútil\nrobar FERNET_KEY sin DB = inútil"]
|
||||||
|
D6["os.environ.pop() post-init\nFERNET_KEY · tokens · secrets borrados\n(protege /proc · no docker inspect)"]
|
||||||
|
D7["Silencio total a desconocidos\nallowlist por chat_id\nrespuestas mínimas no revelan arquitectura"]
|
||||||
|
end
|
||||||
|
|
||||||
|
T1 --> D1
|
||||||
|
T2 --> D2
|
||||||
|
T3 --> D3
|
||||||
|
T4 --> D4
|
||||||
|
T5 --> D5
|
||||||
|
T6 --> D6
|
||||||
|
T7 --> D7
|
||||||
|
|
||||||
|
classDef threat fill:#fef2f2,stroke:#991b1b,color:#450a0a
|
||||||
|
classDef defense fill:#f0fdf4,stroke:#166534,color:#052e16
|
||||||
|
class T1,T2,T3,T4,T5,T6,T7 threat
|
||||||
|
class D1,D2,D3,D4,D5,D6,D7 defense
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Cifrado de credenciales — vault.py v3
|
||||||
|
|
||||||
|
El sistema usa **envelope encryption** en dos capas. Comprometer una capa sola
|
||||||
|
no es suficiente para obtener credenciales en texto plano.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
subgraph INPUT ["Entrada"]
|
||||||
|
FKEY["FERNET_KEY\n(del .env — jamás toca disco como texto)"]
|
||||||
|
CREDS["usuario + password\n(del abogado en Telegram)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph GEN ["Generación de material criptográfico"]
|
||||||
|
SALT["salt = os.urandom(16)\n16 bytes aleatorios\núnico por cada operación de cifrado"]
|
||||||
|
DEK["dek = os.urandom(32)\n32 bytes aleatorios\núnico por cada operación de cifrado"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph KEK_LAYER ["Capa KEK — derivación de clave wrapping"]
|
||||||
|
PBKDF2["PBKDF2-HMAC-SHA256\n600.000 iteraciones · ~200ms\nwrapping_key = PBKDF2(FERNET_KEY, salt)\nfuerza bruta inviable incluso con GPU"]
|
||||||
|
WRAP["dek_enc = Fernet(wrapping_key).encrypt(dek)\nla DEK queda protegida por la clave derivada"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph DEK_LAYER ["Capa DEK — cifrado de datos"]
|
||||||
|
PAYLOAD["payload = JSON con usuario + password"]
|
||||||
|
PENC["payload_enc = Fernet(dek).encrypt(payload)\nlos datos quedan protegidos por clave efímera"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph STORED ["Guardado en DB — credentials_enc"]
|
||||||
|
JSON_OUT["{v:3, s:salt_b64, k:dek_enc_b64, p:payload_enc_b64}"]
|
||||||
|
end
|
||||||
|
|
||||||
|
FKEY --> PBKDF2
|
||||||
|
SALT --> PBKDF2
|
||||||
|
PBKDF2 --> WRAP
|
||||||
|
DEK --> WRAP
|
||||||
|
DEK --> PENC
|
||||||
|
CREDS --> PAYLOAD --> PENC
|
||||||
|
WRAP --> JSON_OUT
|
||||||
|
PENC --> JSON_OUT
|
||||||
|
SALT --> JSON_OUT
|
||||||
|
|
||||||
|
classDef input fill:#eff6ff,stroke:#1d4ed8,color:#1e3a8a
|
||||||
|
classDef crypto fill:#f0fdf4,stroke:#166534,color:#052e16
|
||||||
|
classDef stored fill:#fefce8,stroke:#854d0e,color:#451a03
|
||||||
|
class FKEY,CREDS input
|
||||||
|
class SALT,DEK,PBKDF2,WRAP,PAYLOAD,PENC crypto
|
||||||
|
class JSON_OUT stored
|
||||||
|
```
|
||||||
|
|
||||||
|
### Por qué dos capas
|
||||||
|
|
||||||
|
| Atacante tiene acceso a... | Puede obtener credenciales? |
|
||||||
|
|----------------------------|-----------------------------|
|
||||||
|
| Solo la DB (`pasante.db`) | No — DEK y payload cifrados con clave derivada de FERNET_KEY |
|
||||||
|
| Solo `FERNET_KEY` | No — el salt está en la DB; sin él no se puede derivar la wrapping key |
|
||||||
|
| DB + `FERNET_KEY` | Sí — pero requiere acceso completo al servidor |
|
||||||
|
| Una credencial descifrada | No afecta las demás — cada tenant tiene salt y DEK únicos |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Ciclo de vida de credenciales
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
actor Abogado
|
||||||
|
participant ONB as Onboarding FSM
|
||||||
|
participant BOT as telegram_bot
|
||||||
|
participant VAULT as vault.py
|
||||||
|
participant DB as pasante.db
|
||||||
|
participant POLL as Poller
|
||||||
|
participant CSJ as apps.csj.gov.py
|
||||||
|
|
||||||
|
Note over Abogado,DB: — Alta de abogado —
|
||||||
|
|
||||||
|
Abogado->>BOT: envía contraseña por Telegram
|
||||||
|
BOT->>BOT: delete_message() — borra el mensaje del chat
|
||||||
|
BOT->>ONB: procesa credencial
|
||||||
|
ONB->>VAULT: cifrar_credenciales(chat_id, usuario, password, fernet_key)
|
||||||
|
Note over VAULT: genera salt (16B) + DEK (32B) aleatorios
|
||||||
|
Note over VAULT: PBKDF2(FERNET_KEY, salt, 600k iter) → wrapping_key
|
||||||
|
Note over VAULT: Fernet(wrapping_key).encrypt(DEK) → dek_enc
|
||||||
|
Note over VAULT: Fernet(DEK).encrypt(payload) → payload_enc
|
||||||
|
VAULT-->>ONB: JSON envelope v3
|
||||||
|
ONB->>DB: UPDATE tenants SET credentials_enc = ?
|
||||||
|
Note over ONB: del password — limpieza de memoria inmediata
|
||||||
|
|
||||||
|
Note over Abogado,CSJ: — Ciclo de polling (cada hora) —
|
||||||
|
|
||||||
|
POLL->>DB: SELECT credentials_enc FROM tenants WHERE estado='activo'
|
||||||
|
POLL->>VAULT: descifrar_credenciales(chat_id, credentials_enc, fernet_key)
|
||||||
|
Note over VAULT: lru_cache(wrapping_key) si mismo (salt, fernet_key) ya derivado
|
||||||
|
Note over VAULT: Fernet(wrapping_key).decrypt(dek_enc) → DEK
|
||||||
|
Note over VAULT: Fernet(DEK).decrypt(payload_enc) → usuario, password
|
||||||
|
VAULT-->>POLL: (usuario, password) — solo en memoria
|
||||||
|
POLL->>CSJ: POST /autenticador/login {usuario, clave}
|
||||||
|
CSJ-->>POLL: bearerToken (TTL 1h)
|
||||||
|
Note over POLL: del usuario, password — limpieza de memoria
|
||||||
|
POLL->>CSJ: GET /Notificaciones/PorRecibir (Bearer)
|
||||||
|
CSJ-->>POLL: lista de notificaciones
|
||||||
|
POLL->>Abogado: alerta Telegram si hay novedades
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Controles transversales
|
||||||
|
|
||||||
|
| Control | Implementación | Archivo |
|
||||||
|
|---------|---------------|---------|
|
||||||
|
| Log sanitization | `scrub()` — todo dato externo pasa por acá antes de `logger.*()` | `utils/sanitize.py` |
|
||||||
|
| Audit trail | `audit.log()` — quién, qué, cuándo, resultado — sin payload sensible | `audit.py` |
|
||||||
|
| Rate limiting (HTTP) | `limit_req_zone` en Nginx — 30r/s webhook, 10r/min health | `DEPLOY.md § 11` |
|
||||||
|
| Rate limiting (bot) | Ventana deslizante 20 req/60s por chat_id | `utils/rate_limiter.py` |
|
||||||
|
| Comparación de secrets | `secrets.compare_digest()` — evita timing oracle en todas las validaciones | `health.py`, `onboarding.py` |
|
||||||
|
| Env vars post-init | `os.environ.pop()` para FERNET_KEY, tokens y secrets tras cargar Settings | `main.py` |
|
||||||
|
| Invite codes | `UPDATE WHERE usado=0` atómico — elimina TOCTOU race condition | `database.py` |
|
||||||
|
| chat_id en logs | Enmascarado como `usr_` + SHA256[:8] — no reversible, sí correlacionable | `health.py` |
|
||||||
|
| Respuestas a desconocidos | Silencio total; `/health` público devuelve solo `{status, timestamp}` | `telegram_bot.py`, `health.py` |
|
||||||
|
| Acuse de notificaciones | `PUT /Notificaciones/{id}/recibir` **NUNCA se llama** — efecto procesal irreversible | invariante global |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Limitaciones conocidas
|
||||||
|
|
||||||
|
| Limitación | Motivo | Mitigación |
|
||||||
|
|------------|--------|------------|
|
||||||
|
| `docker inspect` expone env vars | Docker no puede evitarlo por diseño | Usar Docker secrets en v1; FERNET_KEY en vault externo (HashiCorp Vault) |
|
||||||
|
| Credenciales en memoria no se pueden zerear | Python `str` es inmutable; GC no garantizado | `del` inmediato post-uso; sin referencias persistentes |
|
||||||
|
| lru_cache mantiene wrapping keys en RAM | Tradeoff performance vs isolation | Cache key incluye fingerprint del KEK; se invalida si cambia FERNET_KEY |
|
||||||
|
| `.env` en disco del servidor | Necesario para arrancar | Permisos `600`, usuario dedicado `pedrito`, fuera del directorio web |
|
||||||
|
| Backup de DB sin cifrar | `data/pasante.db.bak` queda en disco | Incluir en política de backup cifrado; mismos permisos que la DB |
|
||||||
163
scripts/migrar_vault_v3.py
Normal file
163
scripts/migrar_vault_v3.py
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
#!/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())
|
||||||
@@ -10,6 +10,7 @@ Responsabilidades:
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import unicodedata
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
@@ -47,6 +48,41 @@ logger = structlog.get_logger(__name__)
|
|||||||
|
|
||||||
PJ_URL = "https://apps.csj.gov.py/gestion-partes/notificaciones-electronicas"
|
PJ_URL = "https://apps.csj.gov.py/gestion-partes/notificaciones-electronicas"
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────────────
|
||||||
|
# Mapeo de frases libres a comandos (sin LLM)
|
||||||
|
# ──────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
_FRASES_COMANDOS: dict[str, str] = {
|
||||||
|
"novedades": "notif",
|
||||||
|
"actualizaciones": "notif",
|
||||||
|
"que hay nuevo": "notif",
|
||||||
|
"qué hay nuevo": "notif",
|
||||||
|
"hay algo nuevo": "notif",
|
||||||
|
"alguna novedad": "notif",
|
||||||
|
"notificaciones": "notif",
|
||||||
|
"notificacion": "notif",
|
||||||
|
"notificación": "notif",
|
||||||
|
"revisar": "notif",
|
||||||
|
"actualizar": "notif",
|
||||||
|
"estado": "estado",
|
||||||
|
"como estas": "estado",
|
||||||
|
"cómo estás": "estado",
|
||||||
|
"ayuda": "ayuda",
|
||||||
|
"help": "ayuda",
|
||||||
|
"que podes hacer": "ayuda",
|
||||||
|
"qué podés hacer": "ayuda",
|
||||||
|
"comandos": "ayuda",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _normalizar(texto: str) -> str:
|
||||||
|
"""Lowercase, sin acentos, sin puntuación — para comparación de frases."""
|
||||||
|
texto = texto.lower().strip()
|
||||||
|
texto = unicodedata.normalize("NFD", texto)
|
||||||
|
texto = "".join(c for c in texto if unicodedata.category(c) != "Mn")
|
||||||
|
texto = re.sub(r"[^\w\s]", " ", texto)
|
||||||
|
return re.sub(r"\s+", " ", texto).strip()
|
||||||
|
|
||||||
# ──────────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────────
|
||||||
# Helpers de formato
|
# Helpers de formato
|
||||||
# ──────────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────────
|
||||||
@@ -626,6 +662,45 @@ class PedritoBot:
|
|||||||
if self._onboarding.is_in_onboarding(chat_id):
|
if self._onboarding.is_in_onboarding(chat_id):
|
||||||
await self._onboarding.handle_mensaje(update, context)
|
await self._onboarding.handle_mensaje(update, context)
|
||||||
|
|
||||||
|
async def _intentar_mapear_comando(
|
||||||
|
self,
|
||||||
|
update: Update,
|
||||||
|
context: ContextTypes.DEFAULT_TYPE,
|
||||||
|
texto: str,
|
||||||
|
) -> bool:
|
||||||
|
"""
|
||||||
|
Intenta mapear texto libre a un comando conocido sin LLM.
|
||||||
|
Retorna True si encontró match y ejecutó el handler correspondiente.
|
||||||
|
"""
|
||||||
|
texto_norm = _normalizar(texto)
|
||||||
|
texto_lower = texto.lower()
|
||||||
|
|
||||||
|
# Regex especiales sobre texto original (preserva la "/")
|
||||||
|
m_exp = re.search(r"\bexp(?:ediente)?\b\s+(\d+(?:/\d+)?)", texto_lower)
|
||||||
|
if m_exp:
|
||||||
|
context.args = [m_exp.group(1)] # type: ignore[assignment]
|
||||||
|
await self.cmd_exp(update, context)
|
||||||
|
return True
|
||||||
|
|
||||||
|
m_pdf = re.search(r"\bpdf\b\s+(\d+/\d+)", texto_lower)
|
||||||
|
if m_pdf:
|
||||||
|
context.args = [m_pdf.group(1)] # type: ignore[assignment]
|
||||||
|
await self.cmd_pdf(update, context)
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Matching por frases del diccionario
|
||||||
|
for frase, comando in _FRASES_COMANDOS.items():
|
||||||
|
if _normalizar(frase) in texto_norm:
|
||||||
|
if comando == "notif":
|
||||||
|
await self.cmd_notif(update, context)
|
||||||
|
elif comando == "estado":
|
||||||
|
await self.cmd_estado(update, context)
|
||||||
|
elif comando == "ayuda":
|
||||||
|
await self.cmd_ayuda(update, context)
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
async def handle_texto_libre(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def handle_texto_libre(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
"""Responde a texto que no es comando ni está en un flujo de onboarding."""
|
"""Responde a texto que no es comando ni está en un flujo de onboarding."""
|
||||||
chat_id = update.effective_chat.id # type: ignore[union-attr]
|
chat_id = update.effective_chat.id # type: ignore[union-attr]
|
||||||
@@ -635,11 +710,16 @@ class PedritoBot:
|
|||||||
return # el onboarding lo maneja en handle_mensaje, no responder acá
|
return # el onboarding lo maneja en handle_mensaje, no responder acá
|
||||||
|
|
||||||
tenant = await get_tenant(chat_id)
|
tenant = await get_tenant(chat_id)
|
||||||
if tenant and tenant.get("estado") == "activo":
|
if not (tenant and tenant.get("estado") == "activo"):
|
||||||
texto = _escape_md(_texto_tono("texto_no_reconocido", tenant))
|
# Usuarios sin registro: silencio total.
|
||||||
await update.effective_message.reply_text(texto, parse_mode=ParseMode.MARKDOWN_V2) # type: ignore[union-attr]
|
return
|
||||||
# Usuarios sin registro: silencio total.
|
|
||||||
# No confirmar que el bot existe ni qué hace — quien lo debe usar ya sabe cómo.
|
texto_original = (update.effective_message.text or "") # type: ignore[union-attr]
|
||||||
|
if await self._intentar_mapear_comando(update, context, texto_original):
|
||||||
|
return
|
||||||
|
|
||||||
|
texto = _escape_md(_texto_tono("texto_no_reconocido", tenant))
|
||||||
|
await update.effective_message.reply_text(texto, parse_mode=ParseMode.MARKDOWN_V2) # type: ignore[union-attr]
|
||||||
|
|
||||||
# ──────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────
|
||||||
# Handlers de callbacks
|
# Handlers de callbacks
|
||||||
|
|||||||
169
vault.py
169
vault.py
@@ -1,55 +1,182 @@
|
|||||||
"""
|
"""
|
||||||
vault.py — Cifrado de credenciales por tenant.
|
vault.py — Cifrado de credenciales por tenant.
|
||||||
|
|
||||||
Cada tenant tiene sus credenciales cifradas con una clave derivada de:
|
## Arquitectura v3: Envelope Encryption con PBKDF2 + DEK por tenant
|
||||||
FERNET_KEY (global, del .env) + str(chat_id) (único por tenant)
|
|
||||||
|
|
||||||
Esto asegura que las credenciales de un tenant no se pueden descifrar
|
Cada credencial se cifra en dos capas independientes:
|
||||||
con solo la FERNET_KEY — hace falta también el chat_id.
|
|
||||||
|
1. DEK (Data Encryption Key): 32 bytes aleatorios, única por operación de cifrado.
|
||||||
|
2. KEK→Wrapping Key: derivada de FERNET_KEY usando PBKDF2-HMAC-SHA256 con salt único
|
||||||
|
por tenant. El salt se genera al cifrar y se guarda junto al ciphertext.
|
||||||
|
|
||||||
|
La KEK (FERNET_KEY del .env) nunca cifra datos directamente — solo envuelve la DEK.
|
||||||
|
|
||||||
|
Formato credentials_enc v3:
|
||||||
|
JSON compacto: {"v":3,"s":"<salt_b64>","k":"<dek_enc_b64>","p":"<payload_enc_b64>"}
|
||||||
|
|
||||||
|
s = salt de 16 bytes (base64url) para derivar la wrapping key via PBKDF2
|
||||||
|
k = DEK cifrada con Fernet(wrapping_key)
|
||||||
|
p = {"usuario": ..., "password": ...} cifrado con Fernet(DEK)
|
||||||
|
|
||||||
|
Ventajas sobre v1 (SHA256):
|
||||||
|
- PBKDF2 (600k iter): derivar la wrapping key cuesta ~200ms — fuerza bruta inviable
|
||||||
|
- Salt único por tenant: mismo FERNET_KEY + mismo password → ciphertexts distintos
|
||||||
|
- DEK aleatoria: comprometer una credencial no ayuda con las demás
|
||||||
|
- Dos capas: robar la DB sin FERNET_KEY es inútil; robar FERNET_KEY sin la DB también
|
||||||
|
|
||||||
|
## Formato v1 (legacy, solo lectura)
|
||||||
|
|
||||||
|
Fernet(SHA256(FERNET_KEY + str(chat_id))) — mantenido para migración desde el script
|
||||||
|
`scripts/migrar_vault_v3.py`. No se generan nuevos v1.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
import structlog
|
import structlog
|
||||||
from cryptography.fernet import Fernet, InvalidToken
|
from cryptography.fernet import Fernet, InvalidToken
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||||
|
|
||||||
from utils.sanitize import scrub
|
from utils.sanitize import scrub
|
||||||
|
|
||||||
logger = structlog.get_logger(__name__)
|
logger = structlog.get_logger(__name__)
|
||||||
|
|
||||||
|
# PBKDF2: NIST SP 800-132 (2023) recomienda mínimo 600k iteraciones para SHA-256
|
||||||
|
_PBKDF2_ITERATIONS = 600_000
|
||||||
|
_SALT_BYTES = 16
|
||||||
|
_DEK_BYTES = 32
|
||||||
|
|
||||||
def _derive_key(fernet_key: str, chat_id: int) -> bytes:
|
|
||||||
"""Deriva una clave Fernet única por tenant usando SHA-256(fernet_key + chat_id)."""
|
|
||||||
raw = (fernet_key + str(chat_id)).encode()
|
|
||||||
digest = hashlib.sha256(raw).digest()
|
|
||||||
return base64.urlsafe_b64encode(digest)
|
|
||||||
|
|
||||||
|
def _derive_wrapping_key(kek: str, salt: bytes) -> bytes:
|
||||||
|
"""
|
||||||
|
Deriva una wrapping key de 32 bytes usando PBKDF2-HMAC-SHA256.
|
||||||
|
~200ms intencionalmente — hace fuerza bruta inviable incluso con GPU.
|
||||||
|
"""
|
||||||
|
kdf = PBKDF2HMAC(
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
length=_DEK_BYTES,
|
||||||
|
salt=salt,
|
||||||
|
iterations=_PBKDF2_ITERATIONS,
|
||||||
|
)
|
||||||
|
return base64.urlsafe_b64encode(kdf.derive(kek.encode("utf-8")))
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=256)
|
||||||
|
def _wrapping_key_cached(kek_fingerprint: str, salt_hex: str, kek: str) -> bytes:
|
||||||
|
"""
|
||||||
|
Cache de wrapping keys por (salt, kek) para no ejecutar PBKDF2 600k veces
|
||||||
|
en el mismo proceso cuando el poller revisa múltiples tenants.
|
||||||
|
|
||||||
|
kek_fingerprint es el SHA256[:8] de kek — sirve para invalidar entradas
|
||||||
|
si el FERNET_KEY cambia (nueva instancia del proceso).
|
||||||
|
"""
|
||||||
|
return _derive_wrapping_key(kek, bytes.fromhex(salt_hex))
|
||||||
|
|
||||||
|
|
||||||
|
def _get_wrapping_key(kek: str, salt: bytes) -> bytes:
|
||||||
|
"""Obtiene wrapping key del cache o la deriva si no está."""
|
||||||
|
fingerprint = hashlib.sha256(kek.encode()).hexdigest()[:8]
|
||||||
|
return _wrapping_key_cached(fingerprint, salt.hex(), kek)
|
||||||
|
|
||||||
|
|
||||||
|
# ── API pública ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def cifrar_credenciales(chat_id: int, usuario: str, password: str, fernet_key: str) -> str:
|
def cifrar_credenciales(chat_id: int, usuario: str, password: str, fernet_key: str) -> str:
|
||||||
"""Retorna JSON cifrado con Fernet listo para guardar en DB."""
|
"""
|
||||||
key = _derive_key(fernet_key, chat_id)
|
Cifra credenciales con envelope encryption v3.
|
||||||
f = Fernet(key)
|
Retorna JSON compacto listo para guardar en DB.
|
||||||
payload = json.dumps({"usuario": usuario, "password": password}).encode()
|
"""
|
||||||
encrypted = f.encrypt(payload).decode()
|
# Capa 1: generar salt (para PBKDF2) y DEK aleatoria
|
||||||
logger.info("credenciales_cifradas", chat_id=chat_id)
|
salt = os.urandom(_SALT_BYTES)
|
||||||
return encrypted
|
dek_raw = os.urandom(_DEK_BYTES)
|
||||||
|
dek_b64 = base64.urlsafe_b64encode(dek_raw)
|
||||||
|
|
||||||
|
# Capa 2: cifrar DEK con wrapping key derivada de FERNET_KEY + salt
|
||||||
|
wrapping_key = _get_wrapping_key(fernet_key, salt)
|
||||||
|
f_wrap = Fernet(wrapping_key)
|
||||||
|
dek_enc = f_wrap.encrypt(dek_b64)
|
||||||
|
|
||||||
|
# Capa 3: cifrar payload con DEK
|
||||||
|
f_dek = Fernet(dek_b64)
|
||||||
|
payload_bytes = json.dumps({"usuario": usuario, "password": password}).encode()
|
||||||
|
payload_enc = f_dek.encrypt(payload_bytes)
|
||||||
|
|
||||||
|
envelope = {
|
||||||
|
"v": 3,
|
||||||
|
"s": base64.urlsafe_b64encode(salt).decode(),
|
||||||
|
"k": dek_enc.decode(),
|
||||||
|
"p": payload_enc.decode(),
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("credenciales_cifradas_v3", chat_id=chat_id)
|
||||||
|
return json.dumps(envelope, separators=(",", ":"))
|
||||||
|
|
||||||
|
|
||||||
def descifrar_credenciales(chat_id: int, credentials_enc: str, fernet_key: str) -> tuple[str, str]:
|
def descifrar_credenciales(chat_id: int, credentials_enc: str, fernet_key: str) -> tuple[str, str]:
|
||||||
"""
|
"""
|
||||||
Retorna (usuario, password).
|
Descifra credenciales. Soporta v1 (legacy) y v3 (actual).
|
||||||
Levanta ValueError si no se puede descifrar (clave incorrecta o datos corruptos).
|
Levanta ValueError si no se puede descifrar.
|
||||||
"""
|
"""
|
||||||
key = _derive_key(fernet_key, chat_id)
|
stripped = credentials_enc.strip()
|
||||||
|
if stripped.startswith("{"):
|
||||||
|
return _descifrar_v3(chat_id, stripped, fernet_key)
|
||||||
|
return _descifrar_v1(chat_id, stripped, fernet_key)
|
||||||
|
|
||||||
|
|
||||||
|
def es_formato_v3(credentials_enc: str) -> bool:
|
||||||
|
"""Retorna True si las credenciales ya están en formato v3."""
|
||||||
|
return credentials_enc.strip().startswith("{")
|
||||||
|
|
||||||
|
|
||||||
|
# ── Implementaciones internas ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _descifrar_v3(chat_id: int, credentials_enc: str, fernet_key: str) -> tuple[str, str]:
|
||||||
|
try:
|
||||||
|
envelope = json.loads(credentials_enc)
|
||||||
|
if envelope.get("v") != 3:
|
||||||
|
raise ValueError(f"Versión desconocida: {envelope.get('v')}")
|
||||||
|
|
||||||
|
salt = base64.urlsafe_b64decode(envelope["s"])
|
||||||
|
dek_enc = envelope["k"].encode()
|
||||||
|
payload_enc = envelope["p"].encode()
|
||||||
|
|
||||||
|
# Descifrar DEK con wrapping key derivada de PBKDF2
|
||||||
|
wrapping_key = _get_wrapping_key(fernet_key, salt)
|
||||||
|
f_wrap = Fernet(wrapping_key)
|
||||||
|
dek_b64 = f_wrap.decrypt(dek_enc)
|
||||||
|
|
||||||
|
# Descifrar payload con DEK
|
||||||
|
f_dek = Fernet(dek_b64)
|
||||||
|
payload = json.loads(f_dek.decrypt(payload_enc).decode())
|
||||||
|
|
||||||
|
return payload["usuario"], payload["password"]
|
||||||
|
|
||||||
|
except (InvalidToken, KeyError, ValueError, json.JSONDecodeError) as e:
|
||||||
|
logger.error("error_descifrar_v3", chat_id=chat_id, error=scrub(str(e)))
|
||||||
|
raise ValueError(
|
||||||
|
f"No se pudieron descifrar credenciales (v3) para chat_id={chat_id}"
|
||||||
|
) from e
|
||||||
|
|
||||||
|
|
||||||
|
def _descifrar_v1(chat_id: int, credentials_enc: str, fernet_key: str) -> tuple[str, str]:
|
||||||
|
"""
|
||||||
|
Legacy: clave derivada con SHA256(fernet_key + chat_id).
|
||||||
|
Disponible para migración — no se generan nuevas v1.
|
||||||
|
"""
|
||||||
|
raw = (fernet_key + str(chat_id)).encode()
|
||||||
|
key = base64.urlsafe_b64encode(hashlib.sha256(raw).digest())
|
||||||
f = Fernet(key)
|
f = Fernet(key)
|
||||||
try:
|
try:
|
||||||
payload = json.loads(f.decrypt(credentials_enc.encode()).decode())
|
payload = json.loads(f.decrypt(credentials_enc.encode()).decode())
|
||||||
|
logger.warning("credenciales_v1_descifradas_migracion_pendiente", chat_id=chat_id)
|
||||||
return payload["usuario"], payload["password"]
|
return payload["usuario"], payload["password"]
|
||||||
except (InvalidToken, KeyError, ValueError) as e:
|
except (InvalidToken, KeyError, ValueError) as e:
|
||||||
logger.error("error_descifrar_credenciales", chat_id=chat_id, error=scrub(str(e)))
|
logger.error("error_descifrar_v1", chat_id=chat_id, error=scrub(str(e)))
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"No se pudieron descifrar credenciales para chat_id={chat_id}"
|
f"No se pudieron descifrar credenciales (v1) para chat_id={chat_id}"
|
||||||
) from e
|
) from e
|
||||||
|
|||||||
Reference in New Issue
Block a user