Add integration tests for NodeProfile and SchemaMigration, implement login rate limiting, and enhance password encoding
- Introduced `NodeProfileIT` for testing application-node.yml and login functionality with existing Sequelize tables. - Created `SchemaMigrationIT` to validate schema migrations and ensure data integrity across various scenarios. - Added `LoginRateLimitFilterTest` to verify independent rate limiting for login attempts from different IP addresses. - Implemented `MigrationPasswordEncoderTest` to ensure compatibility with legacy password formats and enforce password policies. - Developed tests for email templates in `ResetPasswordEmailTemplateTest` and `SmtpResetMailSenderTest` to validate HTML escaping and email content. - Added SQL fixture `sequelize-schema.sql` to support integration tests with predefined database structure and data.
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
.git
|
||||
.env
|
||||
.secrets
|
||||
.tools
|
||||
target
|
||||
.idea
|
||||
@@ -0,0 +1,12 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
|
||||
[*.{yml,yaml,xml}]
|
||||
indent_size = 2
|
||||
@@ -0,0 +1,28 @@
|
||||
# Copiar a .env y sustituir la contraseña. Docker Compose lee .env automáticamente.
|
||||
# Spring ejecutado directamente requiere estas variables en el entorno del proceso.
|
||||
DB_USER=genesis
|
||||
DB_PASSWORD=replace-with-a-long-random-password
|
||||
DB_NAME=genesis_auth
|
||||
# Dejar vacío para base nueva. Usar node solo con una copia que ya tenga tablas Sequelize.
|
||||
SPRING_PROFILES_ACTIVE=
|
||||
JWT_ISSUER=http://localhost:8080
|
||||
JWT_AUDIENCE=genesis-api
|
||||
CORS_ALLOWED_ORIGINS=http://localhost:3000
|
||||
AUTH_MAX_ACTIVE_SESSIONS=5
|
||||
AUTH_ALLOW_LEGACY_PASSWORDS=false
|
||||
PASSWORD_MIN_LENGTH=10
|
||||
PASSWORD_MAX_LENGTH=128
|
||||
PASSWORD_MIN_CLASSES=3
|
||||
PASSWORD_REQUIRE_COMPLEXITY=true
|
||||
# Habilitar solo después de configurar SMTP y la URL real del frontend.
|
||||
AUTH_RECOVERY_ENABLED=false
|
||||
APP_NAME=Genesis
|
||||
PASSWORD_RESET_URL=http://localhost:3000/reset-password
|
||||
MAIL_FROM=
|
||||
MAIL_HOST=localhost
|
||||
MAIL_PORT=587
|
||||
MAIL_USERNAME=
|
||||
MAIL_PASSWORD=
|
||||
MAIL_AUTH=true
|
||||
MAIL_SSL=false
|
||||
MAIL_STARTTLS=true
|
||||
@@ -0,0 +1,6 @@
|
||||
* text=auto
|
||||
mvnw text eol=lf
|
||||
mvnw.cmd text eol=crlf
|
||||
*.java text eol=lf
|
||||
*.yml text eol=lf
|
||||
*.sql text eol=lf
|
||||
@@ -0,0 +1,15 @@
|
||||
name: verify
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '25'
|
||||
cache: maven
|
||||
- run: bash ./mvnw -B -ntp verify
|
||||
@@ -0,0 +1,8 @@
|
||||
/target/
|
||||
/.tools/
|
||||
/.secrets/
|
||||
/.env
|
||||
/.idea/
|
||||
*.iml
|
||||
*.log
|
||||
.DS_Store
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip
|
||||
distributionSha256Sum=0d7125e8c91097b36edb990ea5934e6c68b4440eef4ea96510a0f6815e7eeadb
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"java.configuration.updateBuildConfiguration": "interactive"
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
FROM maven:3.9.11-eclipse-temurin-25 AS build
|
||||
WORKDIR /build
|
||||
COPY pom.xml .
|
||||
COPY src src
|
||||
RUN mvn -B -ntp -DskipTests package
|
||||
|
||||
FROM eclipse-temurin:25-jre
|
||||
WORKDIR /app
|
||||
RUN groupadd --system app && useradd --system --gid app app
|
||||
COPY --from=build --chown=app:app /build/target/genesis-auth-0.0.1-SNAPSHOT.jar app.jar
|
||||
USER app
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
|
||||
@@ -0,0 +1,128 @@
|
||||
# Genesis Auth — Java 25
|
||||
|
||||
Migración del flujo de autenticación Express a Spring Boot 4.0.8, Spring Security, PostgreSQL y Flyway. Conserva las seis rutas de Node y las respuestas `{ data, status }`.
|
||||
|
||||
**Lee [la guía de migración desde Node](docs/MIGRACION_NODE.md)**: explica dónde está cada parte y cómo probar con tu base. Java utiliza las tablas de los modelos recibidos (`users`, `rol`, `specialization`, `status`, `refresh_tokens`, `audit_events`) e IDs enteros. No se ha conectado ninguna base externa.
|
||||
|
||||
## Arranque
|
||||
|
||||
Requisitos: JDK 25 y Docker Compose. Maven Wrapper incluido.
|
||||
|
||||
```powershell
|
||||
# Ajusta JAVA_HOME a tu instalación si Java no está en el PATH.
|
||||
$env:JAVA_HOME = 'C:\Program Files\Eclipse Adoptium\jdk-25.0.4.101-hotspot'
|
||||
$env:PATH = "$env:JAVA_HOME\bin;$env:PATH"
|
||||
|
||||
if (!(Test-Path .env)) { Copy-Item .env.example .env }
|
||||
# Si copiaste el ejemplo, cambia DB_PASSWORD por una contraseña aleatoria larga.
|
||||
if (!(Test-Path .secrets/private.pem)) { java scripts/GenerateKeys.java }
|
||||
docker compose up --build -d
|
||||
Invoke-RestMethod http://localhost:8080/actuator/health
|
||||
```
|
||||
|
||||
La carpeta original ya contiene claves de desarrollo y `.env` con contraseña aleatoria, excluidos de Git. Un clon nuevo requiere generarlos. Restringe los permisos de la clave privada al usuario del servicio; el generador no configura las ACL de Windows.
|
||||
|
||||
PostgreSQL persiste datos en un volumen. `docker compose down` lo conserva; `down -v` elimina los datos. No hay usuarios de ejemplo ni alta pública: hay que provisionar o importar usuarios antes del primer login.
|
||||
|
||||
Para ejecutar Java directamente:
|
||||
|
||||
```powershell
|
||||
docker compose up -d postgres
|
||||
$env:DB_URL = 'jdbc:postgresql://localhost:5432/genesis_auth'
|
||||
$env:DB_USER = 'genesis'
|
||||
$env:DB_PASSWORD = 'la-contraseña-de-tu-env'
|
||||
.\mvnw.cmd spring-boot:run
|
||||
```
|
||||
|
||||
Spring no carga `.env` automáticamente; exporta las variables en el proceso o configúralas en el IDE. En Linux/macOS usa `bash ./mvnw` y las variables de tu shell.
|
||||
|
||||
Para una **copia de una base Node ya existente**, activa `SPRING_PROFILES_ACTIVE=node` y apunta `DB_URL` a esa copia. El perfil amplía el esquema existente y conserva usuarios y catálogos. Para la base nueva/de desarrollo de este proyecto utiliza el perfil por defecto; V3 convierte el esquema provisional automáticamente. Los procedimientos y precomprobaciones están en la guía.
|
||||
|
||||
## Endpoints
|
||||
|
||||
Prefijos equivalentes: `/auth` y `/api/v1/auth`.
|
||||
|
||||
| POST | JSON | Acceso |
|
||||
|---|---|---|
|
||||
| `/login` | `email`, `password` | Público |
|
||||
| `/refresh` | `refreshToken` | Refresh válido |
|
||||
| `/logout` | `refreshToken` | Público, idempotente |
|
||||
| `/forgotpassword` | `email` | Público, requiere correo configurado |
|
||||
| `/resetpassword` | `token`, `password`, `email` opcional | Token de recuperación válido |
|
||||
| `/changepassword` | `oldpassword`, `password` | Bearer con rol USER/ADMIN |
|
||||
|
||||
Ejemplo con un usuario ya provisionado:
|
||||
|
||||
```powershell
|
||||
$base = 'http://localhost:8080/auth'
|
||||
$body = @{ email = 'tu-usuario@example.com'; password = 'tu-contraseña' } | ConvertTo-Json
|
||||
$login = Invoke-RestMethod "$base/login" -Method Post -ContentType 'application/json' -Body $body
|
||||
$tokens = $login.data
|
||||
|
||||
$renew = @{ refreshToken = $tokens.refreshToken } | ConvertTo-Json
|
||||
$tokens = (Invoke-RestMethod "$base/refresh" -Method Post -ContentType 'application/json' -Body $renew).data
|
||||
|
||||
$logout = @{ refreshToken = $tokens.refreshToken } | ConvertTo-Json
|
||||
Invoke-RestMethod "$base/logout" -Method Post -ContentType 'application/json' -Body $logout
|
||||
```
|
||||
|
||||
## Configuración
|
||||
|
||||
| Variable | Uso / valor por defecto |
|
||||
|---|---|
|
||||
| `DB_URL` | `jdbc:postgresql://localhost:5432/genesis_auth` |
|
||||
| `DB_USER` | `genesis` |
|
||||
| `DB_PASSWORD` | Obligatoria, sin respaldo |
|
||||
| `DB_NAME` | `genesis_auth`, usada por Compose |
|
||||
| `SPRING_PROFILES_ACTIVE` | Vacío para base nueva/de desarrollo; `node` para una copia existente de Sequelize |
|
||||
| `JWT_ISSUER` | `http://localhost:8080` |
|
||||
| `JWT_AUDIENCE` | `genesis-api` |
|
||||
| `JWT_PRIVATE_KEY` / `JWT_PUBLIC_KEY` | Rutas `file:.secrets/private.pem` / `public.pem` |
|
||||
| `CORS_ALLOWED_ORIGINS` | `http://localhost:3000`, lista separada por comas |
|
||||
| `AUTH_MAX_ACTIVE_SESSIONS` | `5` |
|
||||
| `AUTH_ALLOW_LEGACY_PASSWORDS` | `false`; habilita temporalmente los MD5/plain originales de Node |
|
||||
| `PASSWORD_MIN_LENGTH` / `PASSWORD_MAX_LENGTH` | `10` / `128`, para contraseñas nuevas |
|
||||
| `PASSWORD_MIN_CLASSES` | `3`, entre minúsculas, mayúsculas, números y símbolos |
|
||||
| `PASSWORD_REQUIRE_COMPLEXITY` | `true`; si es false, solo comprueba longitudes |
|
||||
| `AUTH_RECOVERY_ENABLED` | `false`; forgot/reset devuelven 503 hasta configurar correo |
|
||||
| `APP_NAME` | `Genesis`, nombre en la plantilla de correo |
|
||||
| `PASSWORD_RESET_URL` | Página del frontend; por defecto `http://localhost:3000/reset-password` |
|
||||
| `MAIL_FROM`, `MAIL_HOST`, `MAIL_PORT`, `MAIL_USERNAME`, `MAIL_PASSWORD` | Configuración del proveedor SMTP |
|
||||
| `MAIL_AUTH` / `MAIL_SSL` / `MAIL_STARTTLS` | `true` / `false` / `true`; ver guía para puerto 465 o pruebas locales |
|
||||
| `PORT` | `8080`, ejecución directa |
|
||||
|
||||
El access token dura 15 minutos y la sesión siete días, configurables en `application.yml`. Una renovación no prolonga la duración absoluta de la sesión.
|
||||
|
||||
`/actuator/health` comprueba SMTP solo cuando `AUTH_RECOVERY_ENABLED=true`. Con recuperación desactivada, un servidor de correo no disponible no impide que la API aparezca como saludable. Para puerto 465 usa `MAIL_SSL=true` y `MAIL_STARTTLS=false`; para 587 con STARTTLS, `MAIL_SSL=false` y `MAIL_STARTTLS=true`.
|
||||
|
||||
## Seguridad y operación
|
||||
|
||||
- Argon2id para hashes nuevos; bcrypt de Node se actualiza al iniciar sesión correctamente. Los MD5/plain originales se aceptan solo con la opción temporal `AUTH_ALLOW_LEGACY_PASSWORDS=true`, desactivada por defecto. Las etiquetas de importación previas siguen siendo compatibles.
|
||||
- JWT RS256 con RSA de al menos 3072 bits: validación de firma, expiración, issuer, audience y sesión activa. El JWT está firmado, no cifrado.
|
||||
- Refresh tokens aleatorios de 256 bits, almacenados solo como SHA-256, con rotación transaccional y detección de reutilización. Serializa las renovaciones en el cliente y guarda la nueva pareja de tokens.
|
||||
- Logout, cambio y recuperación de contraseña revocan sesiones. Cada petición autenticada comprueba la sesión y el estado del usuario en PostgreSQL; una petición que ya superó la autenticación puede terminar.
|
||||
- Cinco fallos bloquean 15 minutos, incluso para emails inexistentes. Límite adicional local de 20 POST de auth por IP/minuto. En varias réplicas aplica también límites compartidos en gateway/Redis.
|
||||
- SMTP con timeouts, cola persistente, hasta cinco intentos de envío y token de recuperación de un solo uso con caducidad de 30 minutos.
|
||||
- Auditoría en `audit_events` sin contraseñas/tokens y sin borrado automático de registros históricos. Limpieza horaria de sesiones Java expiradas y sus refresh asociados.
|
||||
- API Bearer sin cookies de autenticación ni sesión HTTP. Si añades cookies, debes incorporar protección CSRF. CORS usa orígenes explícitos y las respuestas llevan `no-store`.
|
||||
- SQL parametrizado, migraciones Flyway y contenedor sin privilegios con filesystem de solo lectura. Actuator solo publica el estado general de salud.
|
||||
|
||||
En producción configura HTTPS, issuer estable, orígenes reales y un gestor de secretos. Usa TLS verificado para PostgreSQL remoto y separa los permisos del usuario de migraciones del usuario de aplicación. La sustitución del par RSA actual invalida JWT anteriores; una rotación sin interrupciones requiere varias claves con distintos `kid`.
|
||||
|
||||
El límite por IP usa la conexión directa; configura proxies de confianza antes de aceptar cabeceras reenviadas. Protege los tokens del cliente frente a XSS; no los registres en logs. MFA y servidor OAuth2/OIDC no están implementados.
|
||||
|
||||
## Pruebas y empaquetado
|
||||
|
||||
```powershell
|
||||
.\mvnw.cmd test # Unitarias, sin base de datos
|
||||
.\mvnw.cmd verify # Unitarias + integración PostgreSQL con Docker/Testcontainers
|
||||
.\mvnw.cmd package # JAR ejecutable en target/
|
||||
```
|
||||
|
||||
Las pruebas de integración no se omiten si falta Docker. También admiten `TEST_DB_URL`, `TEST_DB_USER` y `TEST_DB_PASSWORD` para un PostgreSQL externo **exclusivo y desechable**: la suite trunca tablas de autenticación. Las pruebas verifican contratos HTTP, hashes legacy, JWT, concurrencia, revocación, bloqueos, usuarios deshabilitados y recuperación con un transporte de correo de pruebas; no envían correo a un proveedor externo.
|
||||
|
||||
Las pruebas de migración crean schemas aislados para verificar las tablas Sequelize, las relaciones, la conservación de datos y la conversión del esquema provisional. La plantilla de correo conserva tu diseño original y se prueba el escape de valores dinámicos.
|
||||
|
||||
GitHub Actions ejecuta `verify` con Java 25. Docker Compose requiere validarse en una máquina con Docker.
|
||||
|
||||
Referencias: [Spring Boot 4.0](https://docs.spring.io/spring-boot/4.0/system-requirements.html), [almacenamiento de contraseñas](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html) y [correo con Spring](https://docs.spring.io/spring-boot/3.5/reference/io/email.html).
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18
|
||||
environment:
|
||||
POSTGRES_DB: ${DB_NAME:-genesis_auth}
|
||||
POSTGRES_USER: ${DB_USER:-genesis}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:?Define DB_PASSWORD en .env}
|
||||
ports:
|
||||
- "127.0.0.1:5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 15
|
||||
restart: unless-stopped
|
||||
auth:
|
||||
build: .
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
environment:
|
||||
DB_URL: jdbc:postgresql://postgres:5432/${DB_NAME:-genesis_auth}
|
||||
SPRING_PROFILES_ACTIVE: ${SPRING_PROFILES_ACTIVE:-}
|
||||
DB_USER: ${DB_USER:-genesis}
|
||||
DB_PASSWORD: ${DB_PASSWORD:?Define DB_PASSWORD en .env}
|
||||
JWT_PUBLIC_KEY: file:/run/keys/public.pem
|
||||
JWT_PRIVATE_KEY: file:/run/keys/private.pem
|
||||
JWT_ISSUER: ${JWT_ISSUER:-http://localhost:8080}
|
||||
JWT_AUDIENCE: ${JWT_AUDIENCE:-genesis-api}
|
||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-http://localhost:3000}
|
||||
AUTH_MAX_ACTIVE_SESSIONS: ${AUTH_MAX_ACTIVE_SESSIONS:-5}
|
||||
AUTH_ALLOW_LEGACY_PASSWORDS: ${AUTH_ALLOW_LEGACY_PASSWORDS:-false}
|
||||
PASSWORD_MIN_LENGTH: ${PASSWORD_MIN_LENGTH:-10}
|
||||
PASSWORD_MAX_LENGTH: ${PASSWORD_MAX_LENGTH:-128}
|
||||
PASSWORD_MIN_CLASSES: ${PASSWORD_MIN_CLASSES:-3}
|
||||
PASSWORD_REQUIRE_COMPLEXITY: ${PASSWORD_REQUIRE_COMPLEXITY:-true}
|
||||
AUTH_RECOVERY_ENABLED: ${AUTH_RECOVERY_ENABLED:-false}
|
||||
APP_NAME: ${APP_NAME:-Genesis}
|
||||
PASSWORD_RESET_URL: ${PASSWORD_RESET_URL:-http://localhost:3000/reset-password}
|
||||
MAIL_FROM: ${MAIL_FROM:-}
|
||||
MAIL_HOST: ${MAIL_HOST:-localhost}
|
||||
MAIL_PORT: ${MAIL_PORT:-587}
|
||||
MAIL_USERNAME: ${MAIL_USERNAME:-}
|
||||
MAIL_PASSWORD: ${MAIL_PASSWORD:-}
|
||||
MAIL_AUTH: ${MAIL_AUTH:-true}
|
||||
MAIL_SSL: ${MAIL_SSL:-false}
|
||||
MAIL_STARTTLS: ${MAIL_STARTTLS:-true}
|
||||
volumes:
|
||||
- ./.secrets:/run/keys:ro
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=64m
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,163 @@
|
||||
# Migración de Node a Java
|
||||
|
||||
La implementación utiliza ahora los nombres, campos e identificadores de tus modelos Sequelize: `users`, `rol`, `specialization`, `status`, `refresh_tokens` y `audit_events`. Ya no utiliza `app_user`, un UUID de usuario ni `legacy_id`.
|
||||
|
||||
El trabajo se ha validado con PostgreSQL local y tablas creadas a partir de los modelos que compartiste. **No se ha accedido a tu base real**, ni enviado correo mediante tu proveedor. Se ha recibido y contrastado `security/password.js`: las reglas de longitud y clases, y los formatos bcrypt/MD5/plain, se detallan abajo.
|
||||
|
||||
## Dónde está cada parte
|
||||
|
||||
| Node | Java | Responsabilidad |
|
||||
|---|---|---|
|
||||
| Router y parte HTTP del controller | `api/AuthController.java` | Las seis rutas y sus respuestas |
|
||||
| Esquemas Zod | `api/AuthDtos.java` | Validación de campos con `@Valid` |
|
||||
| `User.findOne/findByPk/update` | `repository/UserRepository.java` | SQL parametrizado sobre `users` y JOIN con `rol` |
|
||||
| Datos del usuario consultado | `domain/UserAccount.java` | Record Java con ID entero, datos y claves de catálogo |
|
||||
| Login, refresh, logout y cambio | `service/AuthService.java` | Lógica de autenticación |
|
||||
| `password.js` | `service/MigrationPasswordEncoder.java` | Comprobar formatos y actualizar a Argon2id |
|
||||
| `login-attempts.js` | `service/LoginAttemptService.java` | Bloqueo persistente por email |
|
||||
| `tokenMiddleware` | `config/SecurityConfig.java` y `service/SessionValidator.java` | Validar firma, claims, sesión y estado del usuario |
|
||||
| `audit.js` y modelo `AuditEvent` | `service/AuditService.java` | Escritura en `audit_events`, incluida metadata JSONB |
|
||||
| Forgot/reset password | `service/PasswordRecoveryService.java` | Cola y consumo del token de recuperación |
|
||||
| Nodemailer | `service/SmtpResetMailSender.java` | Transporte SMTP multipart texto/HTML |
|
||||
| `buildResetPasswordEmail` | `service/ResetPasswordEmailTemplate.java` y `resources/emails/reset-password.html` | Plantilla con paleta y diseño del correo original |
|
||||
| Envío pendiente y reintentos | `service/RecoveryWorker.java` y `RecoveryDeliveryService.java` | Cola persistente y reintentos SMTP |
|
||||
| `keys.js` | `application.yml` y clases de propiedades | Variables de entorno |
|
||||
|
||||
Aquí usamos **JDBC, no JPA**: no necesitas copiar las definiciones Sequelize como entidades anotadas. `UserAccount` representa el resultado de una consulta y `UserRepository` se encarga del acceso a datos. El servicio decide qué hacer con ellos. Las tablas de catálogos mantienen sus relaciones; no se han añadido endpoints CRUD para gestionar especialidades, estados o roles porque este módulo solo implementa autenticación.
|
||||
|
||||
El controller se queda pequeño: recibe el DTO, llama al servicio y construye `{ data, status }`. Los errores se convierten en respuestas desde `ApiExceptionHandler`. Las rutas `/register`, `/me`, `/logout-all` y `/password` que pertenecían a la plantilla inicial se retiraron; el alta de usuarios corresponde a tu administración existente.
|
||||
|
||||
## Elegir la vía de base de datos
|
||||
|
||||
### A. Base vacía o base de desarrollo creada por este proyecto
|
||||
|
||||
Ejecuta con el perfil por defecto. Flyway mantiene las migraciones V1/V2 originales y aplica **V3**, que convierte el esquema provisional a las tablas Sequelize. No edites ni borres migraciones anteriores para evitar fallos de checksum.
|
||||
|
||||
En una base vacía crea los catálogos mínimos de desarrollo: rol 1 `admin`, rol 2 `user`, estado 1 activo y estado 2 deshabilitado. No crea cuentas de ejemplo.
|
||||
|
||||
Si existían usuarios provisionales, V3 conserva sus credenciales y datos; conserva `legacy_id` como nuevo ID entero cuando estaba informado y asigna un entero a los UUID que no lo tenían. Convierte las referencias de sesiones y cola, y conserva auditoría y hashes de refresh. El UUID antiguo de cada evento queda en `metadata.previous_event_id`. Las sesiones anteriores quedan revocadas y se requiere un nuevo login porque cambia el formato de `sub`.
|
||||
|
||||
### B. Copia de la base existente de Node
|
||||
|
||||
Usa el perfil **`node`** sobre una copia de ensayo con las tablas de usuarios y catálogos Sequelize ya presentes. Este perfil no ejecuta V1/V2/V3 de la base provisional ni crea catálogos o usuarios. Si `refresh_tokens` o `audit_events` todavía no se crearon en Node, las prepara con la estructura de los modelos antes de aplicar la ampliación. Si existen, conserva sus datos.
|
||||
|
||||
```powershell
|
||||
$env:SPRING_PROFILES_ACTIVE = 'node'
|
||||
$env:DB_URL = 'jdbc:postgresql://localhost:5432/copia_genesis'
|
||||
$env:DB_USER = 'usuario_de_la_copia'
|
||||
$env:DB_PASSWORD = 'contraseña_en_tu_entorno'
|
||||
.\mvnw.cmd spring-boot:run
|
||||
```
|
||||
|
||||
Spring no lee `.env` automáticamente al ejecutarse así; exporta las variables o configúralas en el IDE. Conserva también las variables de claves JWT y correo que necesites.
|
||||
|
||||
`application-node.yml` utiliza `db/node-migration` y una tabla Flyway propia, `genesis_auth_schema_history`, con baseline 0 para poder trabajar con un esquema existente. Aplica una ampliación del esquema que:
|
||||
|
||||
- Añade `users.reset_requested_at` y los campos de reset si no existían.
|
||||
- Crea `auth_session`, `auth_login_attempt` y `password_reset_request`.
|
||||
- Añade `refresh_tokens.session_id` nullable e índices para buscar sesiones y hashes.
|
||||
- Añade índices únicos de email normalizado y token de recuperación, además de un índice de fecha de auditoría.
|
||||
|
||||
La preparación de las dos tablas auxiliares usa un [callback SQL `beforeMigrate` de Flyway](https://documentation.red-gate.com/fd/executing-scripts-before-or-after-deployment-via-callbacks-313491459.html), sin editar el checksum de V1. Si el arranque anterior falló con `no existe la relación refresh_tokens` o `audit_events`, vuelve a arrancar tras actualizar el código: no necesitas borrar tablas, desactivar Flyway ni ejecutar repair para ese fallo transaccional.
|
||||
|
||||
**No sobrescribe usuarios, contraseñas, roles, especialidades, estados, auditoría ni hashes históricos de refresh.** Los índices se construirán sobre los datos existentes y pueden bloquear escrituras mientras se crean; ensaya tiempos y programa el cambio antes del despliegue.
|
||||
|
||||
La migración rechaza emails ambiguos y hashes duplicados en lugar de eliminar registros. Antes de aplicarla puedes revisar:
|
||||
|
||||
```sql
|
||||
SELECT lower(btrim(email)) AS email_normalizado, count(*)
|
||||
FROM users GROUP BY lower(btrim(email)) HAVING count(*) > 1;
|
||||
|
||||
SELECT token_hash, count(*)
|
||||
FROM refresh_tokens GROUP BY token_hash HAVING count(*) > 1;
|
||||
|
||||
SELECT reset_token_hash, count(*)
|
||||
FROM users WHERE reset_token_hash IS NOT NULL
|
||||
GROUP BY reset_token_hash HAVING count(*) > 1;
|
||||
```
|
||||
|
||||
El modelo es la referencia recibida; una base real puede tener nombres de esquema, tipos o constraints adicionales. Revisa el resultado de una copia restaurada antes de usar producción. Mantén el perfil elegido para esa base: no actives `node` sobre una base que ya convirtió el perfil por defecto.
|
||||
|
||||
## Correspondencia de datos
|
||||
|
||||
| Modelo | Uso en Java |
|
||||
|---|---|
|
||||
| `User.id` INTEGER | `long` en Java, claim `id` numérico y claim `sub` como representación textual del mismo número |
|
||||
| `User.password` | Se consulta y actualiza `users.password`; al actualizarlo también se escribe `users.updated` |
|
||||
| `User.name`, `lastname`, `acronym`, `rate` | Alimentan `displayName`, `acronym` y `rate` en el JWT; `rate` se mantiene como DOUBLE PRECISION |
|
||||
| `User.id_rol` → `Rol.id` | JOIN con `rol`; el número del rol no se presupone. `rol.name` aporta el nombre real |
|
||||
| `User.id_status` | El valor 2 bloquea login, refresh y peticiones autenticadas, según la regla de tu controller |
|
||||
| `User.id_specialization` | Conserva su relación con `specialization`; autenticación no lo modifica |
|
||||
| `RefreshToken` | Se mantienen expiración, IPs, agente, request ID, revocación y hash sustituto |
|
||||
| `AuditEvent.metadata` JSONB | Los motivos de eventos Java van en `metadata.reason`; la auditoría anterior sigue intacta |
|
||||
|
||||
La comprobación de email usa `lower(btrim(email))` sin reescribir los emails almacenados. Las contraseñas no se recortan ni normalizan. `roles` se emite en mayúsculas para Spring Security y `rol` en minúsculas para el cliente Node. Solo `user` y `admin` tienen acceso a cambiar contraseña, como en tu router.
|
||||
|
||||
Los refresh nuevos guardan un `session_id`. Los refresh anteriores de Node mantienen ese campo NULL y **Java no los acepta**. No se han inventado sesiones para esos tokens ni alterado sus hashes. El corte entre backends requiere nuevo login y actualizar a RSA los consumidores que verificaban HMAC. No mantengas Node atendiendo renovaciones durante el corte si quieres que la revocación de sesiones sea coherente.
|
||||
|
||||
## Contrato HTTP
|
||||
|
||||
Prefijos equivalentes `/auth` y `/api/v1/auth`. Todos los métodos son POST:
|
||||
|
||||
| Ruta | JSON | Acceso |
|
||||
|---|---|---|
|
||||
| `/login` | `email`, `password` | Público |
|
||||
| `/refresh` | `refreshToken` | Refresh válido |
|
||||
| `/logout` | `refreshToken` | Público e idempotente |
|
||||
| `/forgotpassword` | `email` | Público; requiere correo habilitado |
|
||||
| `/resetpassword` | `token`, `password`, `email` opcional | Token de recuperación válido |
|
||||
| `/changepassword` | `oldpassword`, `password` | Bearer con rol user/admin |
|
||||
|
||||
Login/refresh devuelven `{ "data": { "accessToken": "...", "refreshToken": "...", "tokenType": "Bearer", "expiresIn": 900 }, "status": "success" }`. Los dos últimos campos son adicionales respecto a Node. Los demás éxitos contienen `data.message`. Los errores de endpoints usan `status: "error"` y `data.message`; usa el código HTTP para decidir cómo responder en el cliente.
|
||||
|
||||
Las rutas públicas ignoran un Bearer adjunto, permitiendo renovar o cerrar sesión aunque un interceptor envíe un access token caducado. Validan los tokens de su cuerpo. `changepassword` sí valida el Bearer.
|
||||
|
||||
## Contraseñas
|
||||
|
||||
- Bcrypt `$2a$`, `$2b$`, `$2y$` y `{bcrypt}` se admite directamente desde `users.password` y se actualiza a Argon2id tras un login válido.
|
||||
- Con `AUTH_ALLOW_LEGACY_PASSWORDS=true`, los valores sin prefijo de exactamente 32 caracteres hexadecimales se interpretan como MD5 y los demás valores legacy como texto plano, según tu helper. No es necesario modificar las filas antes de iniciar sesión. También siguen siendo compatibles las etiquetas `{legacy-md5}` y `{legacy-plain}` previstas en la primera versión.
|
||||
- La opción está desactivada por defecto. Actívala solo durante la transición y desactívala cuando los usuarios hayan actualizado sus hashes. La actualización ocurre únicamente tras comprobar la contraseña correcta; no se acepta el hash MD5 como contraseña.
|
||||
- El login permite contraseñas cortas anteriores. Cambiar o restablecer exige por defecto **10–128 caracteres**, al menos **tres de cuatro clases** (minúsculas ASCII, mayúsculas ASCII, números ASCII y símbolos) y una contraseña diferente de la actual. La complejidad no se exige al login.
|
||||
- Se mantienen los nombres de entorno de Node: `PASSWORD_MIN_LENGTH=10`, `PASSWORD_MAX_LENGTH=128`, `PASSWORD_MIN_CLASSES=3` y `PASSWORD_REQUIRE_COMPLEXITY=true`. Con complejidad false solo se comprueban longitudes. Espacios y caracteres no ASCII cuentan como símbolos, y se mide UTF-16 como `String.length` de JavaScript. No se recortan contraseñas.
|
||||
- La configuración Java rechaza valores inválidos al arrancar, en lugar de intentar aplicar números incoherentes: longitudes de 1–128, mínimo no superior al máximo y clases de 1–4. El límite de entrada de la API sigue siendo 128 caracteres.
|
||||
- Para bcrypt se rechazan entradas de más de 72 bytes para evitar actualizar coincidencias por truncamiento; esas cuentas necesitarán recuperación.
|
||||
- Se aceptan hashes MD5 hexadecimales tanto en minúsculas como en mayúsculas. El helper Node detectaba ambos, pero su comparación exacta solo verificaba el resultado en minúsculas. Los identificadores de hash desconocidos y bcrypt malformado se rechazan, en lugar de permitir que el hash literal funcione como contraseña.
|
||||
|
||||
El helper original genera bcrypt de coste 12. Java verifica esos hashes y conserva la decisión de guardar **Argon2id** para las contraseñas nuevas y las actualizadas tras login. Este es un cambio deliberado de almacenamiento respecto a Node, no una exigencia de cambiar la contraseña del usuario.
|
||||
|
||||
Referencia: [actualizar hashes antiguos según OWASP](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#upgrading-legacy-hashes).
|
||||
|
||||
## Correo y plantilla
|
||||
|
||||
El HTML conserva tablas, estilos inline, tarjeta, botón y los colores `#4B2E83`, `#00A3E0` y `#0033A0` de tu plantilla. La edición visual está en `src/main/resources/emails/reset-password.html`. La clase `ResetPasswordEmailTemplate` rellena los valores escapados y prepara el texto plano. El nombre de la aplicación se configura con `APP_NAME`, por defecto Genesis.
|
||||
|
||||
```dotenv
|
||||
AUTH_RECOVERY_ENABLED=true
|
||||
APP_NAME=Genesis
|
||||
PASSWORD_RESET_URL=https://tu-frontend.example/reset-password
|
||||
MAIL_FROM=auth@tu-dominio.example
|
||||
MAIL_HOST=smtp.tu-proveedor.example
|
||||
MAIL_PORT=587
|
||||
MAIL_USERNAME=usuario-smtp
|
||||
MAIL_PASSWORD=secreto-en-tu-entorno
|
||||
MAIL_AUTH=true
|
||||
MAIL_SSL=false
|
||||
MAIL_STARTTLS=true
|
||||
```
|
||||
|
||||
Para puerto 465 usa `MAIL_SSL=true` y `MAIL_STARTTLS=false`. Para SMTP local sin TLS ni autenticación, configura ambos como false y `MAIL_AUTH=false`. En Docker, un SMTP del ordenador anfitrión suele alcanzarse mediante `host.docker.internal` en Docker Desktop.
|
||||
|
||||
La URL es una página del frontend que lee `?token=...` y envía POST a `/resetpassword`. No es una página servida por el backend. Con recuperación desactivada, forgot/reset responden 503 para todos los usuarios.
|
||||
|
||||
Forgot devuelve la misma respuesta 200 para email conocido o desconocido y encola solicitudes sin guardar el token en claro. El worker genera el token al enviar, guarda solo SHA-256 con validez de 30 minutos y reintenta SMTP hasta cinco veces. Un fallo entre aceptación del correo y commit puede producir un enlace inválido o un envío duplicado; se puede solicitar de nuevo. Los timeouts acotan la transacción de entrega.
|
||||
|
||||
## Comportamiento de seguridad conservado
|
||||
|
||||
- Access token de 15 minutos y sesión absoluta de siete días; renovar no amplía la sesión.
|
||||
- Rotación de refresh con bloqueo transaccional. Reutilizar un token sustituido revoca la sesión; serializa las renovaciones en el cliente.
|
||||
- Logout revoca también el acceso del JWT. Cambio y reset de contraseña revocan todas las sesiones y cancelan otros enlaces/solicitudes de recuperación.
|
||||
- Cinco fallos bloquean el email 15 minutos, incluso para emails inexistentes, con respuesta 429 y `Retry-After`.
|
||||
- Límite de sesiones configurable con `AUTH_MAX_ACTIVE_SESSIONS`, por defecto cinco. Límite local adicional por IP; en varias réplicas requiere un límite compartido.
|
||||
- Auditoría con metadatos de petición, sin contraseñas ni tokens y sin borrar automáticamente el historial existente. La limpieza elimina sesiones Java expiradas y sus refresh asociados; no elimina los refresh históricos de Node que tienen `session_id` NULL.
|
||||
|
||||
Los tests verifican contratos HTTP, rotación, datos de auditoría y asociaciones. Además, ensayan V1/V2→V3, una base vacía y una base con estructura Sequelize, comprobando conservación de datos y rechazo de duplicados sin borrarlos. No sustituyen el ensayo con un backup de tu base real ni la comprobación de entrega con tu proveedor SMTP.
|
||||
@@ -0,0 +1,295 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
if [ -n "${JAVA_HOME-}" ]; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
scriptDir="$(dirname "$0")"
|
||||
scriptName="$(basename "$0")"
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||
|
||||
exec_maven() {
|
||||
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||
}
|
||||
|
||||
if [ -d "$MAVEN_HOME" ]; then
|
||||
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
exec_maven "$@"
|
||||
fi
|
||||
|
||||
case "${distributionUrl-}" in
|
||||
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||
esac
|
||||
|
||||
# prepare tmp dir
|
||||
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||
trap clean HUP INT TERM EXIT
|
||||
else
|
||||
die "cannot create temp dir"
|
||||
fi
|
||||
|
||||
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||
|
||||
# Download and Install Apache Maven
|
||||
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
verbose "Downloading from: $distributionUrl"
|
||||
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
# select .zip or .tar.gz
|
||||
if ! command -v unzip >/dev/null; then
|
||||
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
fi
|
||||
|
||||
# verbose opt
|
||||
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||
|
||||
# normalize http auth
|
||||
case "${MVNW_PASSWORD:+has-password}" in
|
||||
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
esac
|
||||
|
||||
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||
verbose "Found wget ... using wget"
|
||||
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||
verbose "Found curl ... using curl"
|
||||
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||
elif set_java_home; then
|
||||
verbose "Falling back to use Java to download"
|
||||
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
cat >"$javaSource" <<-END
|
||||
public class Downloader extends java.net.Authenticator
|
||||
{
|
||||
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||
{
|
||||
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||
}
|
||||
public static void main( String[] args ) throws Exception
|
||||
{
|
||||
setDefault( new Downloader() );
|
||||
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||
}
|
||||
}
|
||||
END
|
||||
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||
verbose " - Compiling Downloader.java ..."
|
||||
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||
verbose " - Running Downloader.java ..."
|
||||
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||
fi
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
if [ -n "${distributionSha256Sum-}" ]; then
|
||||
distributionSha256Result=false
|
||||
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
elif command -v sha256sum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
elif command -v shasum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ $distributionSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# unzip and move
|
||||
if command -v unzip >/dev/null; then
|
||||
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||
else
|
||||
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||
fi
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
actualDistributionDir=""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
|
||||
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$distributionUrlNameMain"
|
||||
fi
|
||||
fi
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
# enable globbing to iterate over items
|
||||
set +f
|
||||
for dir in "$TMP_DOWNLOAD_DIR"/*; do
|
||||
if [ -d "$dir" ]; then
|
||||
if [ -f "$dir/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$(basename "$dir")"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
set -f
|
||||
fi
|
||||
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
verbose "Contents of $TMP_DOWNLOAD_DIR:"
|
||||
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
|
||||
die "Could not find Maven distribution directory in extracted archive"
|
||||
fi
|
||||
|
||||
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
@@ -0,0 +1,189 @@
|
||||
<# : batch portion
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
|
||||
$MAVEN_M2_PATH = "$HOME/.m2"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
|
||||
}
|
||||
|
||||
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
|
||||
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
|
||||
}
|
||||
|
||||
$MAVEN_WRAPPER_DISTS = $null
|
||||
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
|
||||
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
|
||||
} else {
|
||||
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
|
||||
}
|
||||
|
||||
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
$actualDistributionDir = ""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
|
||||
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
|
||||
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
|
||||
$actualDistributionDir = $distributionUrlNameMain
|
||||
}
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if (!$actualDistributionDir) {
|
||||
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
|
||||
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
|
||||
if (Test-Path -Path $testPath -PathType Leaf) {
|
||||
$actualDistributionDir = $_.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$actualDistributionDir) {
|
||||
Write-Error "Could not find Maven distribution directory in extracted archive"
|
||||
}
|
||||
|
||||
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.0.8</version><relativePath/></parent>
|
||||
<groupId>com.aellis</groupId><artifactId>genesis-auth</artifactId><version>0.0.1-SNAPSHOT</version>
|
||||
<name>Genesis Auth</name>
|
||||
<properties><java.version>25</java.version></properties>
|
||||
<dependencies>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webmvc</artifactId></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-resource-server</artifactId></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-flyway</artifactId></dependency>
|
||||
<dependency><groupId>org.flywaydb</groupId><artifactId>flyway-database-postgresql</artifactId></dependency>
|
||||
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>runtime</scope></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
|
||||
<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk18on</artifactId><version>1.83</version></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
|
||||
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency>
|
||||
<dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers-postgresql</artifactId><scope>test</scope></dependency>
|
||||
<dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers-junit-jupiter</artifactId><scope>test</scope></dependency>
|
||||
</dependencies>
|
||||
<build><plugins>
|
||||
<plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin>
|
||||
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-failsafe-plugin</artifactId><executions><execution><goals><goal>integration-test</goal><goal>verify</goal></goals></execution></executions></plugin>
|
||||
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-enforcer-plugin</artifactId><version>3.6.2</version><executions><execution><goals><goal>enforce</goal></goals><configuration><rules><requireJavaVersion><version>[25,26)</version></requireJavaVersion></rules></configuration></execution></executions></plugin>
|
||||
</plugins></build>
|
||||
</project>
|
||||
@@ -0,0 +1,27 @@
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.security.*;
|
||||
import java.util.Base64;
|
||||
|
||||
/** Ejecutar: java scripts/GenerateKeys.java. No sobrescribe claves existentes. */
|
||||
class GenerateKeys {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path directory = Path.of(".secrets");
|
||||
Files.createDirectories(directory);
|
||||
if (Files.exists(directory.resolve("private.pem")) || Files.exists(directory.resolve("public.pem"))) {
|
||||
throw new IllegalStateException("Ya existen claves. No se sobrescriben para evitar invalidar tokens.");
|
||||
}
|
||||
var generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(3072);
|
||||
var pair = generator.generateKeyPair();
|
||||
write(directory.resolve("private.pem"), "PRIVATE KEY", pair.getPrivate().getEncoded());
|
||||
write(directory.resolve("public.pem"), "PUBLIC KEY", pair.getPublic().getEncoded());
|
||||
System.out.println("Claves creadas en .secrets. Restringe el acceso a private.pem al usuario del servicio.");
|
||||
}
|
||||
static void write(Path path, String type, byte[] bytes) throws Exception {
|
||||
String pem = "-----BEGIN " + type + "-----\n"
|
||||
+ Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(bytes)
|
||||
+ "\n-----END " + type + "-----\n";
|
||||
Files.writeString(path, pem, StandardCharsets.US_ASCII, StandardOpenOption.CREATE_NEW);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aellis.auth;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
public class AuthApplication {
|
||||
public static void main(String[] args) { SpringApplication.run(AuthApplication.class, args); }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.aellis.auth.api;
|
||||
|
||||
import com.aellis.auth.api.AuthDtos.ApiResponse;
|
||||
import com.aellis.auth.api.AuthDtos.Message;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class ApiExceptionHandler {
|
||||
@ExceptionHandler(AuthException.class)
|
||||
ResponseEntity<ApiResponse<Message>> auth(AuthException exception) {
|
||||
var response = ResponseEntity.status(exception.status());
|
||||
if (exception.retryAfter() > 0) response.header("Retry-After", Long.toString(exception.retryAfter()));
|
||||
return response.body(ApiResponse.error(exception.getMessage()));
|
||||
}
|
||||
@ExceptionHandler({MethodArgumentNotValidException.class, HttpMessageNotReadableException.class})
|
||||
ResponseEntity<ApiResponse<Message>> validation(Exception exception) {
|
||||
return ResponseEntity.badRequest().body(ApiResponse.error("Revisa los campos enviados"));
|
||||
}
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
ResponseEntity<ApiResponse<Message>> notFound() {
|
||||
return ResponseEntity.status(404).body(ApiResponse.error("Ruta no encontrada"));
|
||||
}
|
||||
@ExceptionHandler(Exception.class)
|
||||
ResponseEntity<ApiResponse<Message>> unexpected(Exception exception) {
|
||||
if (exception instanceof org.springframework.web.ErrorResponse error) {
|
||||
return ResponseEntity.status(error.getStatusCode()).headers(error.getHeaders())
|
||||
.body(ApiResponse.error("Solicitud no válida"));
|
||||
}
|
||||
LoggerFactory.getLogger(getClass()).error("auth_unexpected_error type={}", exception.getClass().getSimpleName());
|
||||
return ResponseEntity.internalServerError().body(ApiResponse.error("Ocurrió un error inesperado"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.aellis.auth.api;
|
||||
|
||||
import com.aellis.auth.api.AuthDtos.*;
|
||||
import com.aellis.auth.service.*;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping({"/auth", "/api/v1/auth"})
|
||||
public class AuthController {
|
||||
private final AuthService auth;
|
||||
private final PasswordRecoveryService recovery;
|
||||
public AuthController(AuthService auth, PasswordRecoveryService recovery) {
|
||||
this.auth = auth; this.recovery = recovery;
|
||||
}
|
||||
@PostMapping("/login")
|
||||
public ApiResponse<TokenResponse> login(@Valid @RequestBody LoginRequest body, HttpServletRequest request) {
|
||||
return ApiResponse.success(auth.login(body, RequestMetadata.from(request)));
|
||||
}
|
||||
@PostMapping("/refresh")
|
||||
public ApiResponse<TokenResponse> refresh(@Valid @RequestBody RefreshRequest body, HttpServletRequest request) {
|
||||
return ApiResponse.success(auth.refresh(body.refreshToken(), RequestMetadata.from(request)));
|
||||
}
|
||||
@PostMapping("/logout")
|
||||
public ApiResponse<Message> logout(@Valid @RequestBody RefreshRequest body, HttpServletRequest request) {
|
||||
auth.logout(body.refreshToken(), RequestMetadata.from(request));
|
||||
return ApiResponse.success(new Message("Logout ok."));
|
||||
}
|
||||
@PostMapping("/forgotpassword")
|
||||
public ApiResponse<Message> forgot(@Valid @RequestBody ForgotPasswordRequest body, HttpServletRequest request) {
|
||||
recovery.request(body.email(), RequestMetadata.from(request));
|
||||
return ApiResponse.success(new Message("Si el correo existe, enviaremos instrucciones para restablecer la contraseña."));
|
||||
}
|
||||
@PostMapping("/resetpassword")
|
||||
public ApiResponse<Message> reset(@Valid @RequestBody ResetPasswordRequest body, HttpServletRequest request) {
|
||||
recovery.reset(body, RequestMetadata.from(request));
|
||||
return ApiResponse.success(new Message("Contraseña restablecida correctamente."));
|
||||
}
|
||||
@PostMapping("/changepassword")
|
||||
public ApiResponse<Message> change(@AuthenticationPrincipal Jwt jwt, @Valid @RequestBody PasswordRequest body,
|
||||
HttpServletRequest request) {
|
||||
auth.changePassword(Long.parseLong(jwt.getSubject()), body, RequestMetadata.from(request));
|
||||
return ApiResponse.success(new Message("Contraseña cambiada exitosamente."));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.aellis.auth.api;
|
||||
|
||||
import jakarta.validation.constraints.*;
|
||||
|
||||
/** Los nombres de los campos mantienen el contrato del router de Express. */
|
||||
public final class AuthDtos {
|
||||
private AuthDtos() {}
|
||||
public record LoginRequest(@NotBlank @Email @Size(max = 254) String email,
|
||||
@NotEmpty @Size(max = 128) String password) {}
|
||||
public record RefreshRequest(@NotBlank @Size(max = 512) String refreshToken) {}
|
||||
public record ForgotPasswordRequest(@NotBlank @Email @Size(max = 254) String email) {}
|
||||
public record ResetPasswordRequest(@Email @Size(max = 254) String email,
|
||||
@NotBlank @Pattern(regexp = "[a-fA-F0-9]{64}") String token,
|
||||
@NotEmpty @Size(max = 128) String password) {}
|
||||
public record PasswordRequest(@NotEmpty @Size(max = 128) String oldpassword,
|
||||
@NotEmpty @Size(max = 128) String password) {}
|
||||
public record TokenResponse(String accessToken, String refreshToken, String tokenType, long expiresIn) {}
|
||||
public record Message(String message) {}
|
||||
public record ApiResponse<T>(T data, String status) {
|
||||
public static <T> ApiResponse<T> success(T data) { return new ApiResponse<>(data, "success"); }
|
||||
public static ApiResponse<Message> error(String message) { return new ApiResponse<>(new Message(message), "error"); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.aellis.auth.api;
|
||||
|
||||
public class AuthException extends RuntimeException {
|
||||
private final int status;
|
||||
private final long retryAfter;
|
||||
public AuthException() { this(401, "Credenciales o sesión no válidas"); }
|
||||
public AuthException(int status, String message) { this(status, message, 0); }
|
||||
public AuthException(int status, String message, long retryAfter) {
|
||||
super(message); this.status = status; this.retryAfter = retryAfter;
|
||||
}
|
||||
public int status() { return status; }
|
||||
public long retryAfter() { return retryAfter; }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.aellis.auth.config;
|
||||
|
||||
import jakarta.validation.constraints.*;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.bind.DefaultValue;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
@Validated
|
||||
@ConfigurationProperties("auth.policy")
|
||||
public record AuthPolicyProperties(boolean allowLegacyPasswords, @Min(1) @Max(100) int maxActiveSessions,
|
||||
@DefaultValue("10") @Min(1) @Max(128) int passwordMinLength,
|
||||
@DefaultValue("128") @Min(1) @Max(128) int passwordMaxLength,
|
||||
@DefaultValue("3") @Min(1) @Max(4) int passwordMinClasses,
|
||||
@DefaultValue("true") boolean passwordRequireComplexity) {
|
||||
public AuthPolicyProperties {
|
||||
if (passwordMinLength > passwordMaxLength) {
|
||||
throw new IllegalArgumentException("PASSWORD_MIN_LENGTH no puede superar PASSWORD_MAX_LENGTH");
|
||||
}
|
||||
}
|
||||
|
||||
/** Equivalente a validatePasswordPolicy de Node. String.length cuenta unidades UTF-16, como JS. */
|
||||
public String passwordPolicyError(String password) {
|
||||
if (password == null || password.length() < passwordMinLength) {
|
||||
return "Password must be at least " + passwordMinLength + " characters long.";
|
||||
}
|
||||
if (password.length() > passwordMaxLength) {
|
||||
return "Password must be at most " + passwordMaxLength + " characters long.";
|
||||
}
|
||||
if (!passwordRequireComplexity) return null;
|
||||
// Mismas clases ASCII que /[a-z]/, /[A-Z]/, /\\d/ y /[^A-Za-z0-9]/ en JS.
|
||||
boolean lower = false, upper = false, number = false, symbol = false;
|
||||
for (int i = 0; i < password.length(); i++) {
|
||||
char character = password.charAt(i);
|
||||
if (character >= 'a' && character <= 'z') lower = true;
|
||||
else if (character >= 'A' && character <= 'Z') upper = true;
|
||||
else if (character >= '0' && character <= '9') number = true;
|
||||
else symbol = true;
|
||||
}
|
||||
int classes = (lower ? 1 : 0) + (upper ? 1 : 0) + (number ? 1 : 0) + (symbol ? 1 : 0);
|
||||
return classes < passwordMinClasses
|
||||
? "Password must include at least " + passwordMinClasses + " of: lowercase, uppercase, number, symbol."
|
||||
: null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.aellis.auth.config;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
@ConfigurationProperties("auth")
|
||||
@Validated
|
||||
public record AuthProperties(@NotBlank String issuer, @NotBlank String audience,
|
||||
@NotNull Resource publicKey, @NotNull Resource privateKey,
|
||||
@NotNull Duration accessTtl, @NotNull Duration refreshTtl,
|
||||
@NotEmpty List<String> allowedOrigins) {
|
||||
public AuthProperties {
|
||||
if (accessTtl != null && (accessTtl.isNegative() || accessTtl.isZero() || accessTtl.compareTo(Duration.ofMinutes(30)) > 0)) {
|
||||
throw new IllegalArgumentException("auth.access-ttl debe ser mayor que cero y como máximo 30 minutos");
|
||||
}
|
||||
if (refreshTtl != null && accessTtl != null && (refreshTtl.compareTo(accessTtl) <= 0 || refreshTtl.compareTo(Duration.ofDays(30)) > 0)) {
|
||||
throw new IllegalArgumentException("auth.refresh-ttl debe superar access-ttl y ser como máximo 30 días");
|
||||
}
|
||||
if (allowedOrigins != null && allowedOrigins.contains("*")) {
|
||||
throw new IllegalArgumentException("Configura orígenes CORS explícitos");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.aellis.auth.config;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.http.*;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
/** Límite local y acotado. En múltiples réplicas, aplicar además un límite en el gateway. */
|
||||
@Component
|
||||
public class LoginRateLimitFilter extends OncePerRequestFilter {
|
||||
private final Map<String, Integer> clients = new HashMap<>();
|
||||
private long currentMinute = Long.MIN_VALUE;
|
||||
private final Clock clock;
|
||||
public LoginRateLimitFilter(Clock clock) { this.clock = clock; }
|
||||
|
||||
synchronized boolean allow(String address) {
|
||||
long minute = clock.instant().getEpochSecond() / 60;
|
||||
if (currentMinute != minute) {
|
||||
clients.clear();
|
||||
currentMinute = minute;
|
||||
}
|
||||
var previous = clients.get(address);
|
||||
if (previous == null && clients.size() >= 10_000) return false;
|
||||
int count = previous == null ? 1 : previous + 1;
|
||||
clients.put(address, Math.min(count, 21));
|
||||
return count <= 20;
|
||||
}
|
||||
|
||||
@Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
if ("POST".equals(req.getMethod()) && (req.getServletPath().startsWith("/api/v1/auth/")
|
||||
|| req.getServletPath().startsWith("/auth/")) && !allow(req.getRemoteAddr())) {
|
||||
res.setStatus(429);
|
||||
res.setHeader("Retry-After", "60");
|
||||
res.setContentType("application/json");
|
||||
res.getWriter().write("{\"data\":{\"message\":\"Demasiadas solicitudes\"},\"status\":\"error\"}");
|
||||
return;
|
||||
}
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
chain.doFilter(req, res);
|
||||
}
|
||||
|
||||
// Se registra únicamente dentro de Spring Security, evitando ejecutar el filtro dos veces.
|
||||
@Bean FilterRegistrationBean<LoginRateLimitFilter> disableServletRegistration() {
|
||||
var registration = new FilterRegistrationBean<>(this);
|
||||
registration.setEnabled(false);
|
||||
return registration;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.aellis.auth.config;
|
||||
|
||||
import java.net.URI;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.bind.DefaultValue;
|
||||
|
||||
@ConfigurationProperties("auth.recovery")
|
||||
public record RecoveryProperties(boolean enabled, URI resetUrl, String from, @DefaultValue("Genesis") String appName) {
|
||||
public RecoveryProperties {
|
||||
if (appName == null || appName.isBlank() || appName.contains("\r") || appName.contains("\n")) {
|
||||
throw new IllegalArgumentException("auth.recovery.app-name debe ser un nombre sin saltos de línea");
|
||||
}
|
||||
if (enabled && (resetUrl == null || resetUrl.getHost() == null || resetUrl.getUserInfo() != null
|
||||
|| resetUrl.getQuery() != null || resetUrl.getFragment() != null
|
||||
|| !("https".equals(resetUrl.getScheme()) || ("http".equals(resetUrl.getScheme())
|
||||
&& ("localhost".equals(resetUrl.getHost()) || "127.0.0.1".equals(resetUrl.getHost()))))
|
||||
|| from == null || from.isBlank())) {
|
||||
throw new IllegalArgumentException("Configura auth.recovery.reset-url (HTTPS) y from para habilitar recuperación");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.aellis.auth.config;
|
||||
|
||||
import com.aellis.auth.service.SessionValidator;
|
||||
import com.aellis.auth.service.MigrationPasswordEncoder;
|
||||
import com.nimbusds.jose.jwk.JWKSet;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.core.*;
|
||||
import org.springframework.security.oauth2.jwt.*;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.*;
|
||||
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.*;
|
||||
|
||||
@Configuration
|
||||
@EnableMethodSecurity
|
||||
public class SecurityConfig {
|
||||
@Bean Clock clock() { return Clock.systemUTC(); }
|
||||
|
||||
@Bean PasswordEncoder passwordEncoder(AuthPolicyProperties policy) {
|
||||
return new MigrationPasswordEncoder(policy.allowLegacyPasswords());
|
||||
}
|
||||
|
||||
@Bean RSAKey rsaKey(AuthProperties props) throws Exception {
|
||||
var factory = KeyFactory.getInstance("RSA");
|
||||
var publicKey = (RSAPublicKey) factory.generatePublic(new X509EncodedKeySpec(pem(props.publicKey())));
|
||||
var privateKey = (RSAPrivateKey) factory.generatePrivate(new PKCS8EncodedKeySpec(pem(props.privateKey())));
|
||||
if (publicKey.getModulus().bitLength() < 3072 || !publicKey.getModulus().equals(privateKey.getModulus())) {
|
||||
throw new IllegalArgumentException("Se requiere un par RSA coincidente de al menos 3072 bits");
|
||||
}
|
||||
return new RSAKey.Builder(publicKey).privateKey(privateKey).keyID("genesis-1").build();
|
||||
}
|
||||
|
||||
private byte[] pem(org.springframework.core.io.Resource resource) throws Exception {
|
||||
try (var input = resource.getInputStream()) {
|
||||
return Base64.getDecoder().decode(new String(input.readAllBytes(), StandardCharsets.US_ASCII)
|
||||
.replaceAll("-----[^-]+-----", "").replaceAll("\\s", ""));
|
||||
}
|
||||
}
|
||||
|
||||
@Bean JwtEncoder jwtEncoder(RSAKey key) {
|
||||
return new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(key)));
|
||||
}
|
||||
|
||||
@Bean JwtDecoder jwtDecoder(RSAKey key, AuthProperties props, SessionValidator sessions) throws Exception {
|
||||
var decoder = NimbusJwtDecoder.withPublicKey(key.toRSAPublicKey()).build();
|
||||
OAuth2TokenValidator<Jwt> claims = jwt -> {
|
||||
if (jwt.getExpiresAt() == null || jwt.getIssuedAt() == null || jwt.getSubject() == null
|
||||
|| !jwt.getAudience().contains(props.audience()) || !"access".equals(jwt.getClaimAsString("token_use"))) {
|
||||
return OAuth2TokenValidatorResult.failure(new OAuth2Error("invalid_token"));
|
||||
}
|
||||
return OAuth2TokenValidatorResult.success();
|
||||
};
|
||||
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
|
||||
JwtValidators.createDefaultWithIssuer(props.issuer()), claims, sessions));
|
||||
return decoder;
|
||||
}
|
||||
|
||||
@Bean SecurityFilterChain security(HttpSecurity http, AuthProperties props, LoginRateLimitFilter limiter) throws Exception {
|
||||
var authorities = new JwtGrantedAuthoritiesConverter();
|
||||
authorities.setAuthoritiesClaimName("roles");
|
||||
authorities.setAuthorityPrefix("ROLE_");
|
||||
var converter = new JwtAuthenticationConverter();
|
||||
converter.setJwtGrantedAuthoritiesConverter(authorities);
|
||||
var bearerTokens = new DefaultBearerTokenResolver();
|
||||
return http.cors(cors -> cors.configurationSource(cors(props)))
|
||||
// API exclusivamente Bearer: no usa cookies de autenticación ni sesión del navegador.
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.requestCache(c -> c.disable())
|
||||
.formLogin(c -> c.disable()).httpBasic(c -> c.disable()).logout(c -> c.disable())
|
||||
.headers(h -> h.contentSecurityPolicy(c -> c.policyDirectives("default-src 'none'; frame-ancestors 'none'"))
|
||||
.referrerPolicy(c -> c.policy(org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)))
|
||||
.authorizeHttpRequests(a -> a
|
||||
.requestMatchers(org.springframework.http.HttpMethod.POST,
|
||||
"/auth/login", "/auth/refresh", "/auth/logout", "/auth/forgotpassword", "/auth/resetpassword",
|
||||
"/api/v1/auth/login", "/api/v1/auth/refresh", "/api/v1/auth/logout",
|
||||
"/api/v1/auth/forgotpassword", "/api/v1/auth/resetpassword").permitAll()
|
||||
.requestMatchers(org.springframework.http.HttpMethod.GET, "/actuator/health").permitAll()
|
||||
.requestMatchers(org.springframework.http.HttpMethod.POST, "/auth/changepassword", "/api/v1/auth/changepassword")
|
||||
.hasAnyRole("ADMIN", "USER").anyRequest().denyAll())
|
||||
.exceptionHandling(e -> e.authenticationEntryPoint((req, res, ex) -> error(res, 401, "Credenciales o sesión no válidas"))
|
||||
.accessDeniedHandler((req, res, ex) -> error(res, 403, "Acceso denegado")))
|
||||
.oauth2ResourceServer(o -> o.jwt(j -> j.jwtAuthenticationConverter(converter))
|
||||
.bearerTokenResolver(request -> publicAuthRequest(request) ? null : bearerTokens.resolve(request))
|
||||
.authenticationEntryPoint((req, res, ex) -> error(res, 401, "Credenciales o sesión no válidas")))
|
||||
.addFilterBefore(limiter, UsernamePasswordAuthenticationFilter.class).build();
|
||||
}
|
||||
|
||||
private static boolean publicAuthRequest(jakarta.servlet.http.HttpServletRequest request) {
|
||||
if (!"POST".equals(request.getMethod())) return false;
|
||||
for (String prefix : List.of("/auth", "/api/v1/auth")) {
|
||||
for (String route : List.of("/login", "/refresh", "/logout", "/forgotpassword", "/resetpassword")) {
|
||||
if ((prefix + route).equals(request.getServletPath())) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void error(jakarta.servlet.http.HttpServletResponse response, int status, String message) throws java.io.IOException {
|
||||
response.setStatus(status);
|
||||
if (status == 401) response.setHeader("WWW-Authenticate", "Bearer");
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.setContentType("application/json");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.getWriter().write("{\"data\":{\"message\":\"" + message + "\"},\"status\":\"error\"}");
|
||||
}
|
||||
|
||||
private CorsConfigurationSource cors(AuthProperties props) {
|
||||
var config = new CorsConfiguration();
|
||||
config.setAllowedOrigins(props.allowedOrigins());
|
||||
config.setAllowedMethods(List.of("GET", "POST", "OPTIONS"));
|
||||
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
|
||||
config.setAllowCredentials(false);
|
||||
var source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.aellis.auth.domain;
|
||||
|
||||
/** Proyección de users + rol. id y las claves foráneas conservan los INTEGER de Sequelize. */
|
||||
public record UserAccount(long id, String email, String passwordHash, String role, int status,
|
||||
String name, String lastname, String acronym, Double rate,
|
||||
int roleId, Integer specializationId) {}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.aellis.auth.repository;
|
||||
|
||||
import com.aellis.auth.domain.UserAccount;
|
||||
import java.util.Optional;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/** Equivalente a las consultas User.findOne/findByPk de Sequelize. */
|
||||
@Repository
|
||||
public class UserRepository {
|
||||
private static final String SELECT = "SELECT u.*,r.name AS role_name FROM users u JOIN rol r ON r.id=u.id_rol ";
|
||||
private final JdbcClient jdbc;
|
||||
public UserRepository(JdbcClient jdbc) { this.jdbc = jdbc; }
|
||||
public Optional<UserAccount> findByEmailForUpdate(String normalizedEmail) {
|
||||
return jdbc.sql(SELECT + "WHERE lower(btrim(u.email))=:email FOR UPDATE OF u")
|
||||
.param("email", normalizedEmail).query(this::map).optional();
|
||||
}
|
||||
public Optional<UserAccount> findByIdForUpdate(long id) {
|
||||
return jdbc.sql(SELECT + "WHERE u.id=:id FOR UPDATE OF u").param("id", id).query(this::map).optional();
|
||||
}
|
||||
public Optional<String> findEmailById(long id) {
|
||||
return jdbc.sql("SELECT email FROM users WHERE id=:id").param("id", id).query(String.class).optional();
|
||||
}
|
||||
public void updatePassword(long id, String hash) {
|
||||
jdbc.sql("UPDATE users SET password=:hash,updated=CURRENT_TIMESTAMP WHERE id=:id")
|
||||
.param("hash", hash).param("id", id).update();
|
||||
}
|
||||
public void updatePasswordAndClearReset(long id, String hash) {
|
||||
jdbc.sql("""
|
||||
UPDATE users SET password=:hash,reset_token_hash=NULL,reset_token_expires_at=NULL,updated=CURRENT_TIMESTAMP
|
||||
WHERE id=:id
|
||||
""").param("hash", hash).param("id", id).update();
|
||||
}
|
||||
private UserAccount map(java.sql.ResultSet rs, int row) throws java.sql.SQLException {
|
||||
return new UserAccount(rs.getLong("id"), rs.getString("email"), rs.getString("password"),
|
||||
rs.getString("role_name"), rs.getInt("id_status"), rs.getString("name"), rs.getString("lastname"),
|
||||
rs.getString("acronym"), rs.getObject("rate", Double.class), rs.getInt("id_rol"),
|
||||
rs.getObject("id_specialization", Integer.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import java.util.Map;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class AuditService {
|
||||
private final JdbcClient jdbc;
|
||||
private final JsonMapper json;
|
||||
public AuditService(JdbcClient jdbc, JsonMapper json) { this.jdbc = jdbc; this.json = json; }
|
||||
public void record(String action, Long userId, String reason, RequestMetadata metadata) {
|
||||
jdbc.sql("""
|
||||
INSERT INTO audit_events(action,user_id,metadata,ip,user_agent,request_id)
|
||||
VALUES (:action,:user,CAST(:metadata AS JSONB),:ip,:agent,:request)
|
||||
""").param("action", action).param("user", userId)
|
||||
.param("metadata", json.writeValueAsString(reason == null ? Map.of() : Map.of("reason", reason)))
|
||||
.param("ip", metadata.ip()).param("agent", metadata.userAgent())
|
||||
.param("request", metadata.requestId()).update();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import com.aellis.auth.api.AuthDtos.*;
|
||||
import com.aellis.auth.api.AuthException;
|
||||
import com.aellis.auth.config.*;
|
||||
import com.aellis.auth.domain.UserAccount;
|
||||
import com.aellis.auth.repository.UserRepository;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.*;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.*;
|
||||
import java.util.*;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.scheduling.annotation.*;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
|
||||
import org.springframework.security.oauth2.jwt.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@EnableScheduling
|
||||
public class AuthService {
|
||||
private record Session(UUID id, long userId, Instant expiresAt, boolean revoked) {}
|
||||
private record RefreshState(boolean consumed, boolean revoked) {}
|
||||
private final JdbcClient jdbc;
|
||||
private final PasswordEncoder passwords;
|
||||
private final JwtEncoder encoder;
|
||||
private final AuthProperties props;
|
||||
private final AuthPolicyProperties policy;
|
||||
private final Clock clock;
|
||||
private final AuditService audit;
|
||||
private final LoginAttemptService attempts;
|
||||
private final UserRepository users;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final String dummyHash;
|
||||
|
||||
public AuthService(JdbcClient jdbc, PasswordEncoder passwords, JwtEncoder encoder, AuthProperties props,
|
||||
AuthPolicyProperties policy, Clock clock, AuditService audit, LoginAttemptService attempts,
|
||||
UserRepository users) {
|
||||
this.jdbc = jdbc; this.passwords = passwords; this.encoder = encoder; this.props = props;
|
||||
this.policy = policy; this.clock = clock; this.audit = audit; this.attempts = attempts;
|
||||
this.users = users;
|
||||
dummyHash = passwords.encode(UUID.randomUUID().toString());
|
||||
}
|
||||
|
||||
@Transactional(noRollbackFor = AuthException.class)
|
||||
public TokenResponse login(LoginRequest request, RequestMetadata metadata) {
|
||||
String email = normalize(request.email());
|
||||
var attempt = attempts.lock(email);
|
||||
try { attempts.check(attempt); }
|
||||
catch (AuthException exception) {
|
||||
audit.record("login_locked", null, null, metadata);
|
||||
throw exception;
|
||||
}
|
||||
var found = users.findByEmailForUpdate(email);
|
||||
if (found.isEmpty()) {
|
||||
passwords.matches(request.password(), dummyHash);
|
||||
attempts.fail(email, attempt);
|
||||
audit.record("login_failed", null, "invalid_credentials", metadata);
|
||||
throw new AuthException();
|
||||
}
|
||||
var user = found.get();
|
||||
if (!passwords.matches(request.password(), user.passwordHash())) {
|
||||
attempts.fail(email, attempt);
|
||||
audit.record("login_failed", user.id(), "invalid_credentials", metadata);
|
||||
throw new AuthException();
|
||||
}
|
||||
// Se comprueba el estado después de la contraseña para reducir enumeración de cuentas.
|
||||
if (user.status() == 2) {
|
||||
audit.record("login_failed", user.id(), "disabled", metadata);
|
||||
throw new AuthException(403, "Usuario deshabilitado, consulte con el administrador");
|
||||
}
|
||||
if (passwords.upgradeEncoding(user.passwordHash())) {
|
||||
users.updatePassword(user.id(), passwords.encode(request.password()));
|
||||
}
|
||||
// El bloqueo del usuario serializa logins y renovaciones al limitar sesiones.
|
||||
jdbc.sql("""
|
||||
UPDATE auth_session SET revoked=TRUE WHERE id IN (
|
||||
SELECT id FROM auth_session WHERE user_id=:user AND NOT revoked AND expires_at>CURRENT_TIMESTAMP
|
||||
ORDER BY created_at DESC,id DESC OFFSET :keep)
|
||||
""").param("user", user.id()).param("keep", policy.maxActiveSessions() - 1).update();
|
||||
jdbc.sql("""
|
||||
UPDATE refresh_tokens r SET revoked_at=CURRENT_TIMESTAMP WHERE r.user_id=:user AND r.revoked_at IS NULL
|
||||
AND EXISTS(SELECT 1 FROM auth_session s WHERE s.id=r.session_id AND s.revoked)
|
||||
""").param("user", user.id()).update();
|
||||
var session = new Session(UUID.randomUUID(), user.id(), clock.instant().plus(props.refreshTtl()), false);
|
||||
jdbc.sql("INSERT INTO auth_session(id,user_id,expires_at) VALUES (:id,:user,:expires)")
|
||||
.param("id", session.id()).param("user", user.id()).param("expires", Timestamp.from(session.expiresAt())).update();
|
||||
attempts.clear(email);
|
||||
audit.record("login_success", user.id(), null, metadata);
|
||||
return tokens(user, session, metadata);
|
||||
}
|
||||
|
||||
@Transactional(noRollbackFor = AuthException.class)
|
||||
public TokenResponse refresh(String raw, RequestMetadata metadata) {
|
||||
String hash = hash(raw);
|
||||
var owner = jdbc.sql("""
|
||||
SELECT s.user_id FROM auth_session s JOIN refresh_tokens r ON r.session_id=s.id WHERE r.token_hash=:hash
|
||||
""").param("hash", hash).query(Long.class).optional();
|
||||
if (owner.isEmpty()) {
|
||||
audit.record("token_refresh_failed", null, "invalid_token", metadata);
|
||||
throw new AuthException();
|
||||
}
|
||||
var user = users.findByIdForUpdate(owner.get()).orElseThrow(AuthException::new);
|
||||
var session = jdbc.sql("""
|
||||
SELECT s.* FROM auth_session s JOIN refresh_tokens r ON r.session_id=s.id
|
||||
WHERE r.token_hash=:hash FOR UPDATE OF s
|
||||
""").param("hash", hash).query((rs, row) -> new Session(rs.getObject("id", UUID.class),
|
||||
rs.getLong("user_id"), rs.getTimestamp("expires_at").toInstant(), rs.getBoolean("revoked")))
|
||||
.optional().orElseThrow(AuthException::new);
|
||||
var state = jdbc.sql("""
|
||||
SELECT replaced_by_token_hash IS NOT NULL AS consumed,revoked_at IS NOT NULL AS revoked
|
||||
FROM refresh_tokens WHERE token_hash=:hash
|
||||
""").param("hash", hash).query((rs, row) -> new RefreshState(rs.getBoolean("consumed"), rs.getBoolean("revoked"))).single();
|
||||
if (state.consumed() || state.revoked() || session.revoked() || !session.expiresAt().isAfter(clock.instant()) || user.status() == 2) {
|
||||
revoke(session.id(), user.id(), metadata.ip());
|
||||
audit.record("token_refresh_failed", user.id(), state.consumed() ? "replay" : "inactive", metadata);
|
||||
if (user.status() == 2) throw new AuthException(403, "Usuario deshabilitado");
|
||||
throw new AuthException();
|
||||
}
|
||||
var result = tokens(user, session, metadata);
|
||||
jdbc.sql("""
|
||||
UPDATE refresh_tokens SET revoked_at=CURRENT_TIMESTAMP,revoked_by_ip=:ip,replaced_by_token_hash=:next
|
||||
WHERE token_hash=:hash
|
||||
""").param("hash", hash).param("ip", metadata.ip()).param("next", hash(result.refreshToken())).update();
|
||||
audit.record("token_refreshed", user.id(), null, metadata);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void logout(String raw, RequestMetadata metadata) {
|
||||
var user = jdbc.sql("""
|
||||
UPDATE auth_session SET revoked=TRUE WHERE id IN
|
||||
(SELECT session_id FROM refresh_tokens WHERE token_hash=:hash) AND NOT revoked RETURNING user_id
|
||||
""").param("hash", hash(raw)).query(Long.class).optional();
|
||||
jdbc.sql("""
|
||||
UPDATE refresh_tokens SET revoked_at=COALESCE(revoked_at,CURRENT_TIMESTAMP),revoked_by_ip=COALESCE(revoked_by_ip,:ip)
|
||||
WHERE session_id IN (SELECT session_id FROM refresh_tokens WHERE token_hash=:hash)
|
||||
""").param("hash", hash(raw)).param("ip", metadata.ip()).update();
|
||||
user.ifPresent(id -> audit.record("token_revoked", id, null, metadata));
|
||||
}
|
||||
|
||||
private void revoke(UUID session, long user, String ip) {
|
||||
jdbc.sql("UPDATE auth_session SET revoked=TRUE WHERE id=:id AND user_id=:user")
|
||||
.param("id", session).param("user", user).update();
|
||||
jdbc.sql("""
|
||||
UPDATE refresh_tokens SET revoked_at=COALESCE(revoked_at,CURRENT_TIMESTAMP),revoked_by_ip=COALESCE(revoked_by_ip,:ip)
|
||||
WHERE session_id=:session
|
||||
""").param("session", session).param("ip", ip).update();
|
||||
}
|
||||
|
||||
@Transactional(noRollbackFor = AuthException.class)
|
||||
public void changePassword(long userId, PasswordRequest request, RequestMetadata metadata) {
|
||||
String email = normalize(users.findEmailById(userId).orElseThrow(AuthException::new));
|
||||
attempts.lock(email);
|
||||
var user = users.findByIdForUpdate(userId).orElseThrow(AuthException::new);
|
||||
if (user.status() == 2) throw new AuthException(403, "Usuario deshabilitado");
|
||||
if (!passwords.matches(request.oldpassword(), user.passwordHash())) {
|
||||
audit.record("password_change_failed", userId, "invalid_password", metadata);
|
||||
throw new AuthException(400, "Contraseña anterior inválida");
|
||||
}
|
||||
String policyError = policy.passwordPolicyError(request.password());
|
||||
if (policyError != null) throw new AuthException(400, policyError);
|
||||
if (passwords.matches(request.password(), user.passwordHash())) {
|
||||
throw new AuthException(400, "La nueva contraseña debe ser diferente.");
|
||||
}
|
||||
users.updatePasswordAndClearReset(userId, passwords.encode(request.password()));
|
||||
invalidateCredentials(userId, email);
|
||||
audit.record("password_changed", userId, null, metadata);
|
||||
}
|
||||
|
||||
// El llamador ya tiene bloqueados el intento y el usuario, en ese orden.
|
||||
void invalidateCredentials(long user, String email) {
|
||||
jdbc.sql("UPDATE auth_session SET revoked=TRUE WHERE user_id=:user").param("user", user).update();
|
||||
jdbc.sql("UPDATE refresh_tokens SET revoked_at=COALESCE(revoked_at,CURRENT_TIMESTAMP) WHERE user_id=:user")
|
||||
.param("user", user).update();
|
||||
jdbc.sql("DELETE FROM password_reset_request WHERE user_id=:user").param("user", user).update();
|
||||
attempts.clear(email);
|
||||
}
|
||||
|
||||
private TokenResponse tokens(UserAccount user, Session session, RequestMetadata metadata) {
|
||||
Instant now = clock.instant();
|
||||
Instant expires = now.plus(props.accessTtl());
|
||||
if (expires.isAfter(session.expiresAt())) expires = session.expiresAt();
|
||||
var claims = JwtClaimsSet.builder().issuer(props.issuer()).subject(Long.toString(user.id()))
|
||||
.audience(List.of(props.audience())).issuedAt(now).expiresAt(expires).id(UUID.randomUUID().toString())
|
||||
.claim("sid", session.id().toString()).claim("token_use", "access").claim("roles", List.of(user.role().toUpperCase(Locale.ROOT)))
|
||||
.claim("id", user.id())
|
||||
.claim("displayName", (user.name() + " " + user.lastname()).strip())
|
||||
.claim("rol", user.role().toLowerCase(Locale.ROOT));
|
||||
if (user.acronym() != null) claims.claim("acronym", user.acronym());
|
||||
if (user.rate() != null) claims.claim("rate", user.rate());
|
||||
String jwt = encoder.encode(JwtEncoderParameters.from(
|
||||
JwsHeader.with(SignatureAlgorithm.RS256).keyId("genesis-1").build(), claims.build())).getTokenValue();
|
||||
byte[] bytes = new byte[32]; random.nextBytes(bytes);
|
||||
String refresh = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
jdbc.sql("""
|
||||
INSERT INTO refresh_tokens(user_id,token_hash,session_id,expires_at,created_by_ip,user_agent,request_id)
|
||||
VALUES (:user,:hash,:session,:expires,:ip,:agent,:request)
|
||||
""").param("user", user.id()).param("hash", hash(refresh)).param("session", session.id())
|
||||
.param("expires", Timestamp.from(session.expiresAt())).param("ip", metadata.ip())
|
||||
.param("agent", metadata.userAgent()).param("request", metadata.requestId()).update();
|
||||
return new TokenResponse(jwt, refresh, "Bearer", Duration.between(now, expires).toSeconds());
|
||||
}
|
||||
|
||||
static String hash(String token) {
|
||||
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8))); }
|
||||
catch (NoSuchAlgorithmException exception) { throw new IllegalStateException(exception); }
|
||||
}
|
||||
static String normalize(String email) { return email.strip().toLowerCase(Locale.ROOT); }
|
||||
@Scheduled(fixedDelayString = "PT1H")
|
||||
public void cleanup() {
|
||||
jdbc.sql("DELETE FROM auth_session WHERE expires_at<CURRENT_TIMESTAMP").update();
|
||||
jdbc.sql("DELETE FROM auth_login_attempt WHERE updated_at<CURRENT_TIMESTAMP-INTERVAL '1 day'").update();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import com.aellis.auth.api.AuthException;
|
||||
import java.time.*;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class LoginAttemptService {
|
||||
private final JdbcClient jdbc;
|
||||
private final Clock clock;
|
||||
public LoginAttemptService(JdbcClient jdbc, Clock clock) { this.jdbc = jdbc; this.clock = clock; }
|
||||
public record Attempt(int failures, Instant lockedUntil) {}
|
||||
/** Invocar dentro de una transacción y antes de bloquear al usuario. También cubre emails inexistentes. */
|
||||
public Attempt lock(String email) {
|
||||
jdbc.sql("INSERT INTO auth_login_attempt(email) VALUES (:email) ON CONFLICT DO NOTHING").param("email", email).update();
|
||||
return jdbc.sql("SELECT failed_attempts,locked_until FROM auth_login_attempt WHERE email=:email FOR UPDATE")
|
||||
.param("email", email).query((rs, row) -> {
|
||||
var until = rs.getTimestamp("locked_until");
|
||||
if (until != null && !until.toInstant().isAfter(clock.instant())) return new Attempt(0, null);
|
||||
return new Attempt(rs.getInt("failed_attempts"), until == null ? null : until.toInstant());
|
||||
}).single();
|
||||
}
|
||||
public void check(Attempt attempt) {
|
||||
if (attempt.lockedUntil() != null && attempt.lockedUntil().isAfter(clock.instant())) {
|
||||
throw new AuthException(429, "Demasiados intentos. Intenta nuevamente más tarde.",
|
||||
Math.max(1, Duration.between(clock.instant(), attempt.lockedUntil()).toSeconds()));
|
||||
}
|
||||
}
|
||||
public void fail(String email, Attempt attempt) {
|
||||
int failures = attempt.failures() + 1;
|
||||
jdbc.sql("""
|
||||
UPDATE auth_login_attempt SET failed_attempts=:failures,locked_until=:until,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE email=:email
|
||||
""").param("failures", failures >= 5 ? 0 : failures)
|
||||
.param("until", failures >= 5 ? clock.instant().plusSeconds(900).atOffset(ZoneOffset.UTC) : null,
|
||||
java.sql.Types.TIMESTAMP_WITH_TIMEZONE).param("email", email).update();
|
||||
}
|
||||
public void clear(String email) {
|
||||
jdbc.sql("DELETE FROM auth_login_attempt WHERE email=:email").param("email", email).update();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.*;
|
||||
import java.util.HexFormat;
|
||||
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
/** Compatibilidad con password.js de Node; MD5/plain requieren habilitación temporal explícita. */
|
||||
public class MigrationPasswordEncoder implements PasswordEncoder {
|
||||
private final PasswordEncoder modern = new Argon2PasswordEncoder(16, 32, 1, 19456, 2);
|
||||
private final PasswordEncoder bcrypt = new BCryptPasswordEncoder();
|
||||
private final boolean allowLegacy;
|
||||
public MigrationPasswordEncoder(boolean allowLegacy) { this.allowLegacy = allowLegacy; }
|
||||
@Override public String encode(CharSequence raw) { return "{argon2}" + modern.encode(raw); }
|
||||
@Override public boolean matches(CharSequence raw, String stored) {
|
||||
if (raw == null || stored == null) return false;
|
||||
try {
|
||||
if (stored.startsWith("{argon2}")) return modern.matches(raw, stored.substring(8));
|
||||
String hash = stored.startsWith("{bcrypt}") ? stored.substring(8) : stored;
|
||||
if (hash.matches("\\$2[aby]\\$\\d{2}\\$[./A-Za-z0-9]{53}")) {
|
||||
return raw.toString().getBytes(StandardCharsets.UTF_8).length <= 72 && bcrypt.matches(raw, hash);
|
||||
}
|
||||
if (!allowLegacy) return false;
|
||||
if (stored.startsWith("{legacy-md5}")) {
|
||||
return MessageDigest.isEqual(digest("MD5", raw.toString()), HexFormat.of().parseHex(stored.substring(12)));
|
||||
}
|
||||
if (stored.startsWith("{legacy-plain}")) {
|
||||
return MessageDigest.isEqual(digest("SHA-256", raw.toString()), digest("SHA-256", stored.substring(14)));
|
||||
}
|
||||
if (stored.matches("[a-fA-F0-9]{32}")) {
|
||||
return MessageDigest.isEqual(digest("MD5", raw.toString()), HexFormat.of().parseHex(stored));
|
||||
}
|
||||
// Un hash bcrypt malformado o un identificador de hash desconocido no se interpreta como texto plano.
|
||||
if (stored.startsWith("$2") || stored.startsWith("{")) return false;
|
||||
return MessageDigest.isEqual(digest("SHA-256", raw.toString()), digest("SHA-256", stored));
|
||||
} catch (IllegalArgumentException exception) { return false; }
|
||||
}
|
||||
@Override public boolean upgradeEncoding(String stored) {
|
||||
return stored != null && (!stored.startsWith("{argon2}") || modern.upgradeEncoding(stored.substring(8)));
|
||||
}
|
||||
private static byte[] digest(String algorithm, String value) {
|
||||
try { return MessageDigest.getInstance(algorithm).digest(value.getBytes(StandardCharsets.UTF_8)); }
|
||||
catch (NoSuchAlgorithmException exception) { throw new IllegalStateException(exception); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import com.aellis.auth.api.AuthDtos.ResetPasswordRequest;
|
||||
import com.aellis.auth.api.AuthException;
|
||||
import com.aellis.auth.config.RecoveryProperties;
|
||||
import com.aellis.auth.config.AuthPolicyProperties;
|
||||
import java.time.Clock;
|
||||
import java.util.*;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
public class PasswordRecoveryService {
|
||||
private final JdbcClient jdbc;
|
||||
private final PasswordEncoder passwords;
|
||||
private final RecoveryProperties properties;
|
||||
private final Clock clock;
|
||||
private final AuditService audit;
|
||||
private final LoginAttemptService attempts;
|
||||
private final AuthService auth;
|
||||
private final AuthPolicyProperties policy;
|
||||
public PasswordRecoveryService(JdbcClient jdbc, PasswordEncoder passwords, RecoveryProperties properties,
|
||||
Clock clock, AuditService audit, LoginAttemptService attempts, AuthService auth,
|
||||
AuthPolicyProperties policy) {
|
||||
this.jdbc = jdbc; this.passwords = passwords; this.properties = properties;
|
||||
this.clock = clock; this.audit = audit; this.attempts = attempts; this.auth = auth;
|
||||
this.policy = policy;
|
||||
}
|
||||
@Transactional
|
||||
public void request(String email, RequestMetadata metadata) {
|
||||
enabled();
|
||||
var user = jdbc.sql("""
|
||||
UPDATE users SET reset_requested_at=CURRENT_TIMESTAMP WHERE lower(btrim(email))=:email AND id_status<>2
|
||||
AND (reset_requested_at IS NULL OR reset_requested_at<CURRENT_TIMESTAMP-INTERVAL '1 minute') RETURNING id
|
||||
""").param("email", AuthService.normalize(email)).query(Long.class).optional();
|
||||
user.ifPresent(id -> jdbc.sql("""
|
||||
INSERT INTO password_reset_request(user_id) VALUES (:id) ON CONFLICT(user_id) DO NOTHING
|
||||
""").param("id", id).update());
|
||||
audit.record("password_reset_requested", user.orElse(null), null, metadata);
|
||||
}
|
||||
|
||||
@Transactional(noRollbackFor = AuthException.class)
|
||||
public void reset(ResetPasswordRequest request, RequestMetadata metadata) {
|
||||
enabled();
|
||||
String hash = AuthService.hash(request.token());
|
||||
var email = jdbc.sql("SELECT email FROM users WHERE reset_token_hash=:hash").param("hash", hash)
|
||||
.query(String.class).optional();
|
||||
if (email.isEmpty()) throw invalid();
|
||||
attempts.lock(AuthService.normalize(email.get()));
|
||||
var user = jdbc.sql("SELECT * FROM users WHERE reset_token_hash=:hash FOR UPDATE")
|
||||
.param("hash", hash).query((rs, row) -> {
|
||||
var expiration = rs.getTimestamp("reset_token_expires_at");
|
||||
return new ResetUser(rs.getLong("id"), rs.getString("email"), rs.getString("password"),
|
||||
rs.getInt("id_status"), expiration == null ? null : expiration.toInstant());
|
||||
}).optional().orElseThrow(PasswordRecoveryService::invalid);
|
||||
if (user.status() == 2 || user.expiresAt() == null || !user.expiresAt().isAfter(clock.instant())
|
||||
|| (request.email() != null && !AuthService.normalize(request.email()).equals(AuthService.normalize(user.email())))) {
|
||||
audit.record("password_reset_failed", user.id(), "invalid_token", metadata);
|
||||
throw invalid();
|
||||
}
|
||||
String policyError = policy.passwordPolicyError(request.password());
|
||||
if (policyError != null) throw new AuthException(400, policyError);
|
||||
if (passwords.matches(request.password(), user.passwordHash())) {
|
||||
throw new AuthException(400, "La nueva contraseña debe ser diferente.");
|
||||
}
|
||||
jdbc.sql("""
|
||||
UPDATE users SET password=:password,reset_token_hash=NULL,reset_token_expires_at=NULL,updated=CURRENT_TIMESTAMP WHERE id=:id
|
||||
""").param("password", passwords.encode(request.password())).param("id", user.id()).update();
|
||||
auth.invalidateCredentials(user.id(), AuthService.normalize(user.email()));
|
||||
audit.record("password_reset_completed", user.id(), null, metadata);
|
||||
}
|
||||
private void enabled() {
|
||||
if (!properties.enabled()) throw new AuthException(503, "Recuperación por correo no configurada");
|
||||
}
|
||||
private static AuthException invalid() { return new AuthException(400, "Token inválido o expirado"); }
|
||||
private record ResetUser(long id, String email, String passwordHash, int status, java.time.Instant expiresAt) {}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Clock;
|
||||
import java.util.*;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
public class RecoveryDeliveryService {
|
||||
private final JdbcClient jdbc;
|
||||
private final ResetMailSender mail;
|
||||
private final Clock clock;
|
||||
private final AuditService audit;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
public RecoveryDeliveryService(JdbcClient jdbc, ResetMailSender mail, Clock clock, AuditService audit) {
|
||||
this.jdbc = jdbc; this.mail = mail; this.clock = clock; this.audit = audit;
|
||||
}
|
||||
@Transactional
|
||||
public boolean deliverNext() {
|
||||
var candidate = jdbc.sql("""
|
||||
SELECT user_id FROM password_reset_request WHERE available_at<=CURRENT_TIMESTAMP ORDER BY available_at LIMIT 1
|
||||
""").query(Long.class).optional();
|
||||
if (candidate.isEmpty()) return false;
|
||||
long id = candidate.get();
|
||||
// Mismo orden de bloqueo que login/reset: usuario antes que sesión/cola.
|
||||
var user = jdbc.sql("SELECT email,name,lastname,id_status FROM users WHERE id=:id FOR UPDATE SKIP LOCKED")
|
||||
.param("id", id).query((rs, row) -> new Recipient(rs.getString("email"),
|
||||
(rs.getString("name") + " " + rs.getString("lastname")).strip(), rs.getInt("id_status"))).optional();
|
||||
if (user.isEmpty()) return false;
|
||||
var attempt = jdbc.sql("SELECT attempts FROM password_reset_request WHERE user_id=:id FOR UPDATE SKIP LOCKED")
|
||||
.param("id", id).query(Integer.class).optional();
|
||||
if (attempt.isEmpty()) return false;
|
||||
if (user.get().status() == 2) { delete(id); return true; }
|
||||
byte[] bytes = new byte[32]; random.nextBytes(bytes);
|
||||
String raw = HexFormat.of().formatHex(bytes);
|
||||
try { mail.send(user.get().email(), user.get().fullName(), raw); }
|
||||
catch (MailException exception) {
|
||||
if (attempt.get() >= 4) {
|
||||
delete(id);
|
||||
audit.record("password_reset_delivery_failed", id, "smtp", RequestMetadata.system());
|
||||
} else {
|
||||
jdbc.sql("""
|
||||
UPDATE password_reset_request SET attempts=attempts+1,available_at=:next WHERE user_id=:id
|
||||
""").param("next", Timestamp.from(clock.instant().plusSeconds(60L * (attempt.get() + 1))))
|
||||
.param("id", id).update();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
jdbc.sql("UPDATE users SET reset_token_hash=:hash,reset_token_expires_at=:until,updated=CURRENT_TIMESTAMP WHERE id=:id")
|
||||
.param("hash", AuthService.hash(raw)).param("until", Timestamp.from(clock.instant().plusSeconds(1800)))
|
||||
.param("id", id).update();
|
||||
delete(id);
|
||||
audit.record("password_reset_sent", id, null, RequestMetadata.system());
|
||||
return true;
|
||||
}
|
||||
private void delete(long id) { jdbc.sql("DELETE FROM password_reset_request WHERE user_id=:id").param("id", id).update(); }
|
||||
private record Recipient(String email, String fullName, int status) {}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import com.aellis.auth.config.RecoveryProperties;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "auth.recovery.worker-enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class RecoveryWorker {
|
||||
private final RecoveryDeliveryService delivery;
|
||||
private final RecoveryProperties properties;
|
||||
public RecoveryWorker(RecoveryDeliveryService delivery, RecoveryProperties properties) {
|
||||
this.delivery = delivery; this.properties = properties;
|
||||
}
|
||||
@Scheduled(fixedDelayString = "PT5S")
|
||||
public void run() {
|
||||
if (properties.enabled()) for (int i = 0; i < 10 && delivery.deliverNext(); i++) { /* lote acotado */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.UUID;
|
||||
|
||||
public record RequestMetadata(String ip, String userAgent, String requestId) {
|
||||
public static RequestMetadata from(HttpServletRequest request) {
|
||||
return new RequestMetadata(limit(request.getRemoteAddr(), 255), limit(request.getHeader("User-Agent"), 255),
|
||||
UUID.randomUUID().toString());
|
||||
}
|
||||
public static RequestMetadata system() { return new RequestMetadata(null, null, UUID.randomUUID().toString()); }
|
||||
private static String limit(String value, int max) {
|
||||
return value == null ? null : value.substring(0, Math.min(max, value.length()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
public interface ResetMailSender {
|
||||
void send(String email, String fullName, String rawToken);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.regex.*;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
/** Equivalente a buildResetPasswordEmail: presentación separada del transporte SMTP. */
|
||||
@Component
|
||||
public class ResetPasswordEmailTemplate {
|
||||
private static final Pattern PLACEHOLDER = Pattern.compile("\\{\\{(APP_NAME|FULL_NAME|RESET_URL|EXPIRES_MINUTES)\\}\\}");
|
||||
private final String template;
|
||||
public ResetPasswordEmailTemplate() throws IOException {
|
||||
try (var input = new ClassPathResource("emails/reset-password.html").getInputStream()) {
|
||||
template = new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
public record Content(String subject, String html, String text) {}
|
||||
public Content build(String fullName, String resetUrl, int expiresMinutes, String appName) {
|
||||
String name = fullName == null || fullName.isBlank() ? "usuario" : fullName;
|
||||
var values = Map.of("APP_NAME", HtmlUtils.htmlEscape(appName), "FULL_NAME", HtmlUtils.htmlEscape(name),
|
||||
"RESET_URL", HtmlUtils.htmlEscape(resetUrl), "EXPIRES_MINUTES", Integer.toString(expiresMinutes));
|
||||
String html = PLACEHOLDER.matcher(template).replaceAll(match -> Matcher.quoteReplacement(values.get(match.group(1))));
|
||||
String text = "Hola " + name + ",\n\nRecibimos una solicitud para restablecer tu contraseña.\n"
|
||||
+ "Este enlace es válido por " + expiresMinutes + " minutos:\n" + resetUrl
|
||||
+ "\n\nSi no solicitaste esto, ignora este correo.";
|
||||
return new Content(appName + " - Restablecer contraseña", html, text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import java.util.UUID;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.security.oauth2.core.*;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SessionValidator implements OAuth2TokenValidator<Jwt> {
|
||||
private final JdbcClient jdbc;
|
||||
public SessionValidator(JdbcClient jdbc) { this.jdbc = jdbc; }
|
||||
@Override public OAuth2TokenValidatorResult validate(Jwt jwt) {
|
||||
try {
|
||||
boolean active = jdbc.sql("""
|
||||
SELECT EXISTS(SELECT 1 FROM auth_session s JOIN users u ON u.id=s.user_id
|
||||
WHERE s.id = :id AND s.user_id = :user AND u.id_status<>2
|
||||
AND NOT s.revoked AND s.expires_at > CURRENT_TIMESTAMP)
|
||||
""").param("id", UUID.fromString(jwt.getClaimAsString("sid")))
|
||||
.param("user", Long.parseLong(jwt.getSubject())).query(Boolean.class).single();
|
||||
if (active) return OAuth2TokenValidatorResult.success();
|
||||
} catch (IllegalArgumentException | NullPointerException ignored) { /* claim inválido */ }
|
||||
return OAuth2TokenValidatorResult.failure(new OAuth2Error("invalid_token"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import com.aellis.auth.config.RecoveryProperties;
|
||||
import jakarta.mail.MessagingException;
|
||||
import org.springframework.mail.MailPreparationException;
|
||||
import org.springframework.mail.javamail.*;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SmtpResetMailSender implements ResetMailSender {
|
||||
private final JavaMailSender mail;
|
||||
private final RecoveryProperties properties;
|
||||
private final ResetPasswordEmailTemplate template;
|
||||
public SmtpResetMailSender(JavaMailSender mail, RecoveryProperties properties, ResetPasswordEmailTemplate template) {
|
||||
this.mail = mail; this.properties = properties; this.template = template;
|
||||
}
|
||||
@Override public void send(String email, String fullName, String rawToken) {
|
||||
String link = properties.resetUrl() + "?token=" + rawToken;
|
||||
var content = template.build(fullName, link, 30, properties.appName());
|
||||
try {
|
||||
var message = mail.createMimeMessage();
|
||||
var helper = new MimeMessageHelper(message, true, "UTF-8");
|
||||
helper.setFrom(properties.from());
|
||||
helper.setTo(email);
|
||||
helper.setSubject(content.subject());
|
||||
helper.setText(content.text(), content.html());
|
||||
mail.send(message);
|
||||
} catch (MessagingException exception) { throw new MailPreparationException("No se pudo preparar el correo"); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Usar exclusivamente en una copia de una base que ya contenga las tablas Sequelize.
|
||||
spring:
|
||||
flyway:
|
||||
locations: classpath:db/node-migration
|
||||
table: genesis_auth_schema_history
|
||||
baseline-on-migrate: true
|
||||
baseline-version: "0"
|
||||
@@ -0,0 +1,70 @@
|
||||
spring:
|
||||
application:
|
||||
name: genesis-auth
|
||||
datasource:
|
||||
url: ${DB_URL:jdbc:postgresql://localhost:5432/genesis_auth}
|
||||
username: ${DB_USER:genesis}
|
||||
password: ${DB_PASSWORD}
|
||||
hikari:
|
||||
maximum-pool-size: 10
|
||||
connection-timeout: 5000
|
||||
mail:
|
||||
host: ${MAIL_HOST:localhost}
|
||||
port: ${MAIL_PORT:587}
|
||||
username: ${MAIL_USERNAME:}
|
||||
password: ${MAIL_PASSWORD:}
|
||||
properties:
|
||||
mail.smtp.auth: ${MAIL_AUTH:true}
|
||||
mail.smtp.ssl.enable: ${MAIL_SSL:false}
|
||||
mail.smtp.starttls.enable: ${MAIL_STARTTLS:true}
|
||||
mail.smtp.starttls.required: ${MAIL_STARTTLS:true}
|
||||
mail.smtp.connectiontimeout: 5000
|
||||
mail.smtp.timeout: 5000
|
||||
mail.smtp.writetimeout: 5000
|
||||
mvc:
|
||||
problemdetails:
|
||||
enabled: true
|
||||
jackson:
|
||||
deserialization:
|
||||
fail-on-unknown-properties: true
|
||||
server:
|
||||
port: ${PORT:8080}
|
||||
shutdown: graceful
|
||||
forward-headers-strategy: none
|
||||
max-http-request-header-size: 16KB
|
||||
tomcat:
|
||||
max-http-form-post-size: 16KB
|
||||
error:
|
||||
include-message: never
|
||||
include-stacktrace: never
|
||||
management:
|
||||
health:
|
||||
mail:
|
||||
enabled: ${AUTH_RECOVERY_ENABLED:false}
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health
|
||||
endpoint:
|
||||
health:
|
||||
show-details: never
|
||||
auth:
|
||||
issuer: ${JWT_ISSUER:http://localhost:8080}
|
||||
audience: ${JWT_AUDIENCE:genesis-api}
|
||||
public-key: ${JWT_PUBLIC_KEY:file:.secrets/public.pem}
|
||||
private-key: ${JWT_PRIVATE_KEY:file:.secrets/private.pem}
|
||||
access-ttl: 15m
|
||||
refresh-ttl: 7d
|
||||
allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:3000}
|
||||
policy:
|
||||
allow-legacy-passwords: ${AUTH_ALLOW_LEGACY_PASSWORDS:false}
|
||||
max-active-sessions: ${AUTH_MAX_ACTIVE_SESSIONS:5}
|
||||
password-min-length: ${PASSWORD_MIN_LENGTH:10}
|
||||
password-max-length: ${PASSWORD_MAX_LENGTH:128}
|
||||
password-min-classes: ${PASSWORD_MIN_CLASSES:3}
|
||||
password-require-complexity: ${PASSWORD_REQUIRE_COMPLEXITY:true}
|
||||
recovery:
|
||||
app-name: ${APP_NAME:Genesis}
|
||||
enabled: ${AUTH_RECOVERY_ENABLED:false}
|
||||
reset-url: ${PASSWORD_RESET_URL:http://localhost:3000/reset-password}
|
||||
from: ${MAIL_FROM:}
|
||||
@@ -0,0 +1,25 @@
|
||||
CREATE TABLE app_user (
|
||||
id UUID PRIMARY KEY,
|
||||
email VARCHAR(254) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
role VARCHAR(20) NOT NULL DEFAULT 'USER' CHECK (role IN ('USER','ADMIN')),
|
||||
failed_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
locked_until TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE auth_session (
|
||||
id UUID PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES app_user(id) ON DELETE CASCADE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE INDEX auth_session_user_idx ON auth_session(user_id);
|
||||
|
||||
-- Se retienen los tokens consumidos hasta que expire la sesión para detectar replay.
|
||||
CREATE TABLE refresh_token (
|
||||
token_hash CHAR(64) PRIMARY KEY,
|
||||
session_id UUID NOT NULL REFERENCES auth_session(id) ON DELETE CASCADE,
|
||||
consumed BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE INDEX refresh_token_session_idx ON refresh_token(session_id);
|
||||
@@ -0,0 +1,40 @@
|
||||
-- Esquema destino Java: no modifica ni presupone las tablas Sequelize.
|
||||
ALTER TABLE app_user ADD COLUMN legacy_id BIGINT UNIQUE;
|
||||
ALTER TABLE app_user ADD COLUMN name VARCHAR(150) NOT NULL DEFAULT '';
|
||||
ALTER TABLE app_user ADD COLUMN lastname VARCHAR(150) NOT NULL DEFAULT '';
|
||||
ALTER TABLE app_user ADD COLUMN acronym VARCHAR(30);
|
||||
ALTER TABLE app_user ADD COLUMN rate NUMERIC(19,4);
|
||||
ALTER TABLE app_user ADD COLUMN id_status INTEGER NOT NULL DEFAULT 1 CHECK (id_status IN (1,2));
|
||||
ALTER TABLE app_user ADD COLUMN reset_token_hash CHAR(64) UNIQUE;
|
||||
ALTER TABLE app_user ADD COLUMN reset_token_expires_at TIMESTAMPTZ;
|
||||
ALTER TABLE app_user ADD COLUMN reset_requested_at TIMESTAMPTZ;
|
||||
ALTER TABLE app_user ALTER COLUMN password_hash TYPE TEXT;
|
||||
ALTER TABLE auth_session ADD COLUMN created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP;
|
||||
|
||||
CREATE TABLE auth_login_attempt (
|
||||
email VARCHAR(254) PRIMARY KEY,
|
||||
failed_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
locked_until TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
INSERT INTO auth_login_attempt(email,failed_attempts,locked_until)
|
||||
SELECT email,failed_attempts,locked_until FROM app_user WHERE failed_attempts>0 OR locked_until IS NOT NULL;
|
||||
ALTER TABLE app_user DROP COLUMN failed_attempts;
|
||||
ALTER TABLE app_user DROP COLUMN locked_until;
|
||||
-- Cola durable: el token en claro solo existe en memoria al enviar el correo.
|
||||
CREATE TABLE password_reset_request (
|
||||
user_id UUID PRIMARY KEY REFERENCES app_user(id) ON DELETE CASCADE,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
available_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE auth_audit_event (
|
||||
id UUID PRIMARY KEY,
|
||||
action VARCHAR(64) NOT NULL,
|
||||
user_id UUID,
|
||||
reason VARCHAR(64),
|
||||
ip VARCHAR(64),
|
||||
user_agent VARCHAR(512),
|
||||
request_id VARCHAR(64),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX auth_audit_created_idx ON auth_audit_event(created_at);
|
||||
@@ -0,0 +1,98 @@
|
||||
-- Convierte únicamente el esquema provisional Java V1/V2. Para una base Node usar perfil node.
|
||||
CREATE TABLE rol (id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL);
|
||||
INSERT INTO rol(id,name) VALUES (1,'admin'),(2,'user');
|
||||
SELECT setval(pg_get_serial_sequence('rol','id'),3,FALSE);
|
||||
CREATE TABLE specialization (id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL);
|
||||
CREATE TABLE status (id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, _table VARCHAR(255) NOT NULL);
|
||||
INSERT INTO status(id,name,_table) VALUES (1,'Activo','users'),(2,'Deshabilitado','users');
|
||||
SELECT setval(pg_get_serial_sequence('status','id'),3,FALSE);
|
||||
|
||||
CREATE TABLE users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
lastname VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) NOT NULL UNIQUE,
|
||||
rate DOUBLE PRECISION NOT NULL,
|
||||
acronym VARCHAR(255) NOT NULL,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated TIMESTAMPTZ,
|
||||
reset_token_hash VARCHAR(255),
|
||||
reset_token_expires_at TIMESTAMPTZ,
|
||||
reset_requested_at TIMESTAMPTZ,
|
||||
id_specialization INTEGER REFERENCES specialization(id),
|
||||
id_rol INTEGER NOT NULL DEFAULT 2 REFERENCES rol(id),
|
||||
id_status INTEGER NOT NULL DEFAULT 1 REFERENCES status(id)
|
||||
);
|
||||
CREATE UNIQUE INDEX users_auth_normalized_email_uk ON users(lower(btrim(email)));
|
||||
CREATE UNIQUE INDEX users_auth_reset_token_uk ON users(reset_token_hash) WHERE reset_token_hash IS NOT NULL;
|
||||
-- Los IDs numéricos provisionales se conservan; los UUID sin legacy_id reciben un entero nuevo.
|
||||
SELECT setval(pg_get_serial_sequence('users','id'),GREATEST(COALESCE(MAX(legacy_id),0)+1,1),FALSE) FROM app_user;
|
||||
CREATE TEMP TABLE genesis_user_mapping ON COMMIT DROP AS
|
||||
SELECT id AS old_id, COALESCE(legacy_id::INTEGER,nextval(pg_get_serial_sequence('users','id'))::INTEGER) AS user_id FROM app_user;
|
||||
INSERT INTO users(id,name,lastname,email,rate,acronym,password,created,reset_token_hash,reset_token_expires_at,reset_requested_at,id_rol,id_status)
|
||||
SELECT m.user_id,u.name,u.lastname,u.email,COALESCE(u.rate,0)::DOUBLE PRECISION,COALESCE(u.acronym,''),
|
||||
u.password_hash,u.created_at,u.reset_token_hash,u.reset_token_expires_at,u.reset_requested_at,
|
||||
CASE WHEN u.role='ADMIN' THEN 1 ELSE 2 END,u.id_status
|
||||
FROM app_user u JOIN genesis_user_mapping m ON m.old_id=u.id;
|
||||
SELECT setval(pg_get_serial_sequence('users','id'),GREATEST(COALESCE(MAX(id),0)::BIGINT+1,1),FALSE) FROM users;
|
||||
|
||||
ALTER TABLE auth_session ADD COLUMN numeric_user_id INTEGER;
|
||||
UPDATE auth_session s SET numeric_user_id=m.user_id FROM genesis_user_mapping m WHERE s.user_id=m.old_id;
|
||||
ALTER TABLE auth_session DROP CONSTRAINT auth_session_user_id_fkey;
|
||||
ALTER TABLE auth_session DROP COLUMN user_id;
|
||||
ALTER TABLE auth_session RENAME COLUMN numeric_user_id TO user_id;
|
||||
ALTER TABLE auth_session ALTER COLUMN user_id SET NOT NULL;
|
||||
ALTER TABLE auth_session ADD CONSTRAINT auth_session_user_id_fkey FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE;
|
||||
CREATE INDEX auth_session_user_idx ON auth_session(user_id);
|
||||
-- El subject JWT cambia de UUID a entero: se requiere nuevo login tras la conversión.
|
||||
UPDATE auth_session SET revoked=TRUE;
|
||||
|
||||
CREATE TABLE refresh_tokens (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL,
|
||||
token_hash VARCHAR(255) NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
replaced_by_token_hash VARCHAR(255),
|
||||
created_by_ip VARCHAR(255),
|
||||
revoked_by_ip VARCHAR(255),
|
||||
user_agent VARCHAR(255),
|
||||
request_id VARCHAR(255),
|
||||
created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
session_id UUID REFERENCES auth_session(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE UNIQUE INDEX refresh_tokens_auth_hash_uk ON refresh_tokens(token_hash);
|
||||
CREATE INDEX refresh_tokens_auth_session_idx ON refresh_tokens(session_id);
|
||||
CREATE INDEX refresh_tokens_auth_user_idx ON refresh_tokens(user_id);
|
||||
INSERT INTO refresh_tokens(user_id,token_hash,expires_at,revoked_at,created,session_id)
|
||||
SELECT s.user_id,r.token_hash,s.expires_at,CURRENT_TIMESTAMP,s.created_at,s.id
|
||||
FROM refresh_token r JOIN auth_session s ON s.id=r.session_id;
|
||||
DROP TABLE refresh_token;
|
||||
|
||||
CREATE TABLE audit_events (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER,
|
||||
action VARCHAR(255) NOT NULL,
|
||||
ip VARCHAR(255),
|
||||
user_agent VARCHAR(255),
|
||||
request_id VARCHAR(255),
|
||||
metadata JSONB,
|
||||
created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
INSERT INTO audit_events(user_id,action,ip,user_agent,request_id,metadata,created)
|
||||
SELECT m.user_id,a.action,a.ip,LEFT(a.user_agent,255),a.request_id,
|
||||
jsonb_strip_nulls(jsonb_build_object('reason',a.reason,'previous_event_id',a.id)),a.created_at
|
||||
FROM auth_audit_event a LEFT JOIN genesis_user_mapping m ON m.old_id=a.user_id;
|
||||
CREATE INDEX audit_events_auth_created_idx ON audit_events(created);
|
||||
DROP TABLE auth_audit_event;
|
||||
|
||||
ALTER TABLE password_reset_request ADD COLUMN numeric_user_id INTEGER;
|
||||
UPDATE password_reset_request q SET numeric_user_id=m.user_id FROM genesis_user_mapping m WHERE q.user_id=m.old_id;
|
||||
ALTER TABLE password_reset_request DROP CONSTRAINT password_reset_request_user_id_fkey;
|
||||
ALTER TABLE password_reset_request DROP CONSTRAINT password_reset_request_pkey;
|
||||
ALTER TABLE password_reset_request DROP COLUMN user_id;
|
||||
ALTER TABLE password_reset_request RENAME COLUMN numeric_user_id TO user_id;
|
||||
ALTER TABLE password_reset_request ADD PRIMARY KEY(user_id);
|
||||
ALTER TABLE password_reset_request ADD FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE;
|
||||
DROP TABLE app_user;
|
||||
@@ -0,0 +1,34 @@
|
||||
-- Precondición: tablas del proyecto Node ya existentes. No crea ni reemplaza usuarios/catálogos.
|
||||
-- Se rechazan emails ambiguos en lugar de cambiar cuentas silenciosamente.
|
||||
CREATE UNIQUE INDEX users_auth_normalized_email_uk ON users(lower(btrim(email)));
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS reset_token_hash VARCHAR(255);
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS reset_token_expires_at TIMESTAMPTZ;
|
||||
ALTER TABLE users ADD COLUMN reset_requested_at TIMESTAMPTZ;
|
||||
CREATE UNIQUE INDEX users_auth_reset_token_uk ON users(reset_token_hash) WHERE reset_token_hash IS NOT NULL;
|
||||
|
||||
CREATE TABLE auth_session (
|
||||
id UUID PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX auth_session_user_idx ON auth_session(user_id);
|
||||
-- Los tokens históricos quedan con session_id NULL y Java no los acepta; no se alteran sus hashes.
|
||||
ALTER TABLE refresh_tokens ADD COLUMN session_id UUID REFERENCES auth_session(id) ON DELETE CASCADE;
|
||||
CREATE UNIQUE INDEX refresh_tokens_auth_hash_uk ON refresh_tokens(token_hash);
|
||||
CREATE INDEX refresh_tokens_auth_session_idx ON refresh_tokens(session_id);
|
||||
CREATE INDEX refresh_tokens_auth_user_idx ON refresh_tokens(user_id);
|
||||
|
||||
CREATE TABLE auth_login_attempt (
|
||||
email VARCHAR(254) PRIMARY KEY,
|
||||
failed_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
locked_until TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE password_reset_request (
|
||||
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
available_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX audit_events_auth_created_idx ON audit_events(created);
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
-- Algunos despliegues Node tienen los modelos, pero no llegaron a crear estas tablas.
|
||||
-- Preparación idempotente previa a V1: no cambia migraciones ya aplicadas ni datos existentes.
|
||||
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL,
|
||||
token_hash VARCHAR(255) NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
replaced_by_token_hash VARCHAR(255),
|
||||
created_by_ip VARCHAR(255),
|
||||
revoked_by_ip VARCHAR(255),
|
||||
user_agent VARCHAR(255),
|
||||
request_id VARCHAR(255),
|
||||
created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_events (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER,
|
||||
action VARCHAR(255) NOT NULL,
|
||||
ip VARCHAR(255),
|
||||
user_agent VARCHAR(255),
|
||||
request_id VARCHAR(255),
|
||||
metadata JSONB,
|
||||
created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
@@ -0,0 +1,46 @@
|
||||
<!doctype html>
|
||||
<html lang="es">
|
||||
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
|
||||
<body style="margin:0;background:#F6F7FB;padding:24px 0;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="border-collapse:collapse;">
|
||||
<tr><td align="center" style="padding:0 16px;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" width="600" style="max-width:600px;width:100%;border-collapse:collapse;">
|
||||
<tr><td style="background:#4B2E83;border-radius:16px 16px 0 0;padding:16px 18px;">
|
||||
<div style="font-family:Arial,sans-serif;color:#FFFFFF;">
|
||||
<div style="font-size:12px;letter-spacing:0.8px;opacity:0.9;">{{APP_NAME}}</div>
|
||||
<div style="font-size:18px;font-weight:700;margin-top:4px;">Restablecer contraseña</div>
|
||||
</div>
|
||||
</td></tr>
|
||||
<tr><td style="background:#FFFFFF;border-radius:0 0 16px 16px;padding:22px;box-shadow:0 10px 26px rgba(0,0,0,0.08);">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="border-collapse:collapse;margin-bottom:18px;">
|
||||
<tr>
|
||||
<td style="height:6px;background:#00A3E0;border-radius:8px 0 0 8px;"></td>
|
||||
<td style="width:10px;"></td>
|
||||
<td style="height:6px;background:#0033A0;border-radius:0 8px 8px 0;"></td>
|
||||
</tr>
|
||||
</table>
|
||||
<div style="font-family:Arial,sans-serif;color:#111827;">
|
||||
<p style="margin:0 0 10px;font-size:14px;line-height:22px;">Hola <strong>{{FULL_NAME}}</strong>,</p>
|
||||
<p style="margin:0 0 14px;font-size:14px;line-height:22px;color:#6B7280;">
|
||||
Recibimos una solicitud para restablecer tu contraseña. Este enlace es válido por
|
||||
<strong style="color:#111827;">{{EXPIRES_MINUTES}} minutos</strong>.
|
||||
</p>
|
||||
<div style="margin:18px 0;text-align:center;">
|
||||
<a href="{{RESET_URL}}" style="display:inline-block;background:#00A3E0;color:#FFFFFF;text-decoration:none;padding:12px 18px;border-radius:12px;font-family:Arial,sans-serif;font-size:14px;font-weight:700;">Restablecer contraseña</a>
|
||||
</div>
|
||||
<p style="margin:0 0 8px;font-size:12px;line-height:18px;color:#6B7280;">Si el botón no funciona, copia y pega este enlace en tu navegador:</p>
|
||||
<p style="margin:0;font-size:12px;line-height:18px;word-break:break-all;">
|
||||
<a href="{{RESET_URL}}" style="color:#0033A0;text-decoration:underline;">{{RESET_URL}}</a>
|
||||
</p>
|
||||
<hr style="border:none;border-top:1px solid #E5E7EB;margin:18px 0;">
|
||||
<p style="margin:0;font-size:12px;line-height:18px;color:#6B7280;">Si tú no solicitaste el cambio, puedes ignorar este correo. Tu contraseña actual seguirá siendo válida.</p>
|
||||
</div>
|
||||
</td></tr>
|
||||
<tr><td style="padding:14px 18px 0;text-align:center;">
|
||||
<p style="margin:0;font-family:Arial,sans-serif;font-size:11px;color:#6B7280;">Este es un mensaje automático. Por favor, no respondas.</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,332 @@
|
||||
package com.aellis.auth;
|
||||
|
||||
import com.aellis.auth.api.AuthDtos.*;
|
||||
import com.aellis.auth.api.AuthException;
|
||||
import com.aellis.auth.service.*;
|
||||
import java.net.URI;
|
||||
import java.net.http.*;
|
||||
import java.nio.file.*;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.*;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.mail.MailSendException;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.jwt.*;
|
||||
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import org.testcontainers.postgresql.PostgreSQLContainer;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/** TEST_DB_URL debe apuntar exclusivamente a una base desechable. Por defecto usa Docker. */
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
|
||||
"logging.level.root=WARN", "debug=false", "auth.policy.allow-legacy-passwords=true",
|
||||
"auth.policy.max-active-sessions=2", "auth.recovery.enabled=true", "auth.recovery.worker-enabled=false",
|
||||
"auth.recovery.from=test@example.com", "auth.recovery.reset-url=http://localhost:3000/reset-password"})
|
||||
class AuthFlowIT {
|
||||
static final PostgreSQLContainer DB = new PostgreSQLContainer("postgres:18");
|
||||
static Path keys;
|
||||
@DynamicPropertySource static void properties(DynamicPropertyRegistry registry) throws Exception {
|
||||
String externalUrl = System.getenv("TEST_DB_URL");
|
||||
if (externalUrl == null) DB.start();
|
||||
keys = Files.createTempDirectory("genesis-test-keys");
|
||||
var generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(3072);
|
||||
var pair = generator.generateKeyPair();
|
||||
Files.writeString(keys.resolve("private.pem"), pem("PRIVATE KEY", pair.getPrivate().getEncoded()));
|
||||
Files.writeString(keys.resolve("public.pem"), pem("PUBLIC KEY", pair.getPublic().getEncoded()));
|
||||
registry.add("spring.datasource.url", () -> externalUrl == null ? DB.getJdbcUrl() : externalUrl);
|
||||
registry.add("spring.datasource.username", () -> externalUrl == null ? DB.getUsername() : System.getenv("TEST_DB_USER"));
|
||||
registry.add("spring.datasource.password", () -> externalUrl == null ? DB.getPassword() : System.getenv("TEST_DB_PASSWORD"));
|
||||
registry.add("auth.private-key", () -> keys.resolve("private.pem").toUri().toString());
|
||||
registry.add("auth.public-key", () -> keys.resolve("public.pem").toUri().toString());
|
||||
}
|
||||
static String pem(String type, byte[] data) {
|
||||
return "-----BEGIN " + type + "-----\n" + Base64.getEncoder().encodeToString(data) + "\n-----END " + type + "-----";
|
||||
}
|
||||
@AfterAll static void cleanup() throws Exception {
|
||||
if (DB.isRunning()) DB.stop();
|
||||
if (keys != null) {
|
||||
Files.deleteIfExists(keys.resolve("private.pem")); Files.deleteIfExists(keys.resolve("public.pem")); Files.deleteIfExists(keys);
|
||||
}
|
||||
}
|
||||
@TestConfiguration static class MailConfig {
|
||||
@Bean @Primary CapturingMail testMail() { return new CapturingMail(); }
|
||||
}
|
||||
static class CapturingMail implements ResetMailSender {
|
||||
String token;
|
||||
String recipient;
|
||||
boolean failing;
|
||||
@Override public void send(String email, String name, String rawToken) {
|
||||
if (failing) throw new MailSendException("simulated");
|
||||
recipient = email; token = rawToken;
|
||||
}
|
||||
}
|
||||
@Autowired AuthService auth;
|
||||
@Autowired PasswordRecoveryService recovery;
|
||||
@Autowired RecoveryDeliveryService delivery;
|
||||
@Autowired CapturingMail mail;
|
||||
@Autowired JdbcClient jdbc;
|
||||
@Autowired PasswordEncoder passwords;
|
||||
@Autowired JwtDecoder decoder;
|
||||
@Autowired JwtEncoder encoder;
|
||||
@Autowired Environment environment;
|
||||
final HttpClient http = HttpClient.newHttpClient();
|
||||
final JsonMapper json = JsonMapper.builder().build();
|
||||
static final String PASSWORD = "A-strong-test-password-2026";
|
||||
static final String NEXT_PASSWORD = "Another-strong-password-2026";
|
||||
static final String EMAIL = "test@example.com";
|
||||
static final RequestMetadata META = new RequestMetadata("127.0.0.1", "integration-test", "request-test");
|
||||
|
||||
@BeforeEach void clear() {
|
||||
jdbc.sql("TRUNCATE users,auth_login_attempt,audit_events CASCADE").update();
|
||||
mail.token = null; mail.recipient = null; mail.failing = false;
|
||||
}
|
||||
long createUser(String hash) {
|
||||
long id = 42;
|
||||
jdbc.sql("""
|
||||
INSERT INTO users(id,email,password,name,lastname,acronym,rate)
|
||||
VALUES (:id,:email,:hash,'Ana','García','AG',12.50)
|
||||
""").param("id", id).param("email", EMAIL).param("hash", hash).update();
|
||||
return id;
|
||||
}
|
||||
TokenResponse createAndLogin() { createUser(passwords.encode(PASSWORD)); return login(PASSWORD); }
|
||||
TokenResponse login(String password) { return auth.login(new LoginRequest(EMAIL, password), META); }
|
||||
TokenResponse refresh(String token) { return auth.refresh(token, META); }
|
||||
|
||||
@Test void rotationDetectsReplayAndInvalidatesAccessTokens() {
|
||||
var first = createAndLogin();
|
||||
var next = refresh(first.refreshToken());
|
||||
assertThat(next.refreshToken()).isNotEqualTo(first.refreshToken());
|
||||
assertThat(decoder.decode(next.accessToken()).getSubject()).isNotBlank();
|
||||
assertThatThrownBy(() -> refresh(first.refreshToken())).isInstanceOf(AuthException.class);
|
||||
assertThatThrownBy(() -> refresh(next.refreshToken())).isInstanceOf(AuthException.class);
|
||||
assertThatThrownBy(() -> decoder.decode(next.accessToken())).isInstanceOf(JwtException.class);
|
||||
assertThat(jdbc.sql("SELECT metadata->>'reason' FROM audit_events WHERE metadata->>'reason'='replay'").query(String.class).single()).isEqualTo("replay");
|
||||
}
|
||||
@Test void logoutIsIdempotentAndPreservesOtherSessions() {
|
||||
var first = createAndLogin(); var second = login(PASSWORD);
|
||||
auth.logout(first.refreshToken(), META); auth.logout(first.refreshToken(), META); auth.logout("unknown", META);
|
||||
assertThatThrownBy(() -> decoder.decode(first.accessToken())).isInstanceOf(JwtException.class);
|
||||
assertThat(decoder.decode(second.accessToken())).isNotNull();
|
||||
}
|
||||
@Test void concurrentRefreshAllowsOneRotationThenRevokesSessionOnReplay() throws Exception {
|
||||
var original = createAndLogin(); var start = new CountDownLatch(1);
|
||||
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
Callable<Optional<TokenResponse>> rotate = () -> {
|
||||
start.await();
|
||||
try { return Optional.of(refresh(original.refreshToken())); }
|
||||
catch (AuthException expected) { return Optional.empty(); }
|
||||
};
|
||||
var first = executor.submit(rotate); var second = executor.submit(rotate); start.countDown();
|
||||
var results = List.of(first.get(10, TimeUnit.SECONDS), second.get(10, TimeUnit.SECONDS));
|
||||
assertThat(results.stream().filter(Optional::isPresent).count()).isEqualTo(1);
|
||||
var issued = results.stream().flatMap(Optional::stream).findFirst().orElseThrow();
|
||||
assertThatThrownBy(() -> decoder.decode(issued.accessToken())).isInstanceOf(JwtException.class);
|
||||
}
|
||||
}
|
||||
@Test void rejectsWrongAudienceIssuerExpiryAndTokenTypeEvenWithValidSignature() {
|
||||
var original = decoder.decode(createAndLogin().accessToken());
|
||||
for (String invalid : List.of("audience", "issuer", "expiry", "type")) {
|
||||
var claims = JwtClaimsSet.builder().claims(map -> map.putAll(original.getClaims()));
|
||||
switch (invalid) {
|
||||
case "audience" -> claims.audience(List.of("another-api"));
|
||||
case "issuer" -> claims.issuer("https://untrusted.example");
|
||||
case "expiry" -> claims.issuedAt(Instant.now().minusSeconds(600)).expiresAt(Instant.now().minusSeconds(300));
|
||||
case "type" -> claims.claim("token_use", "refresh");
|
||||
default -> throw new IllegalStateException();
|
||||
}
|
||||
String token = encoder.encode(JwtEncoderParameters.from(
|
||||
JwsHeader.with(SignatureAlgorithm.RS256).keyId("genesis-1").build(), claims.build())).getTokenValue();
|
||||
assertThatThrownBy(() -> decoder.decode(token)).isInstanceOf(JwtException.class);
|
||||
}
|
||||
var parts = original.getTokenValue().split("\\.");
|
||||
String tampered = parts[0] + "." + Base64.getUrlEncoder().withoutPadding().encodeToString(
|
||||
"{\"sub\":\"admin\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8)) + "." + parts[2];
|
||||
assertThatThrownBy(() -> decoder.decode(tampered)).isInstanceOf(JwtException.class);
|
||||
}
|
||||
@Test void passwordChangeRevokesAllSessionsAndRejectsReuse() {
|
||||
var first = createAndLogin(); var second = login(PASSWORD);
|
||||
var user = Long.parseLong(decoder.decode(first.accessToken()).getSubject());
|
||||
assertThatThrownBy(() -> auth.changePassword(user, new PasswordRequest(PASSWORD, PASSWORD), META)).isInstanceOf(AuthException.class);
|
||||
auth.changePassword(user, new PasswordRequest(PASSWORD, NEXT_PASSWORD), META);
|
||||
assertThatThrownBy(() -> decoder.decode(first.accessToken())).isInstanceOf(JwtException.class);
|
||||
assertThatThrownBy(() -> refresh(second.refreshToken())).isInstanceOf(AuthException.class);
|
||||
assertThatThrownBy(() -> login(PASSWORD)).isInstanceOf(AuthException.class);
|
||||
assertThat(login(NEXT_PASSWORD)).isNotNull();
|
||||
}
|
||||
@Test void failedAttemptsPersistForExistingAndUnknownAccounts() {
|
||||
createAndLogin();
|
||||
for (String email : List.of(EMAIL, "unknown@example.com")) {
|
||||
for (int i = 0; i < 5; i++) assertThatThrownBy(() -> auth.login(new LoginRequest(email, "wrong"), META)).isInstanceOf(AuthException.class);
|
||||
assertThatThrownBy(() -> auth.login(new LoginRequest(email, PASSWORD), META))
|
||||
.isInstanceOfSatisfying(AuthException.class, exception -> assertThat(exception.status()).isEqualTo(429));
|
||||
}
|
||||
jdbc.sql("UPDATE auth_login_attempt SET locked_until=CURRENT_TIMESTAMP-INTERVAL '1 minute'").update();
|
||||
assertThat(login(PASSWORD)).isNotNull();
|
||||
}
|
||||
@Test void bcryptLoginUpgradesHashAndPreservesNodeClaims() {
|
||||
createUser(new BCryptPasswordEncoder().encode(PASSWORD));
|
||||
var token = login(PASSWORD); var jwt = decoder.decode(token.accessToken());
|
||||
assertThat(jdbc.sql("SELECT password FROM users").query(String.class).single()).startsWith("{argon2}");
|
||||
assertThat(((Number) jwt.getClaim("id")).longValue()).isEqualTo(42);
|
||||
assertThat(jwt.getClaimAsString("displayName")).isEqualTo("Ana García");
|
||||
assertThat(jwt.getClaimAsString("rol")).isEqualTo("user");
|
||||
assertThat(jwt.getClaimAsString("acronym")).isEqualTo("AG");
|
||||
assertThat(((Number) jwt.getClaim("rate")).doubleValue()).isEqualTo(12.50);
|
||||
}
|
||||
@Test void explicitlyTaggedLegacyLoginUpgradesHash() {
|
||||
createUser("{legacy-plain}" + PASSWORD);
|
||||
assertThat(login(PASSWORD)).isNotNull();
|
||||
assertThat(jdbc.sql("SELECT password FROM users").query(String.class).single()).startsWith("{argon2}");
|
||||
}
|
||||
@Test void untaggedNodeMd5AndPlainLoginUpgradeOnlyAfterSuccessfulVerification() throws Exception {
|
||||
String md5 = HexFormat.of().formatHex(java.security.MessageDigest.getInstance("MD5")
|
||||
.digest(PASSWORD.getBytes(java.nio.charset.StandardCharsets.UTF_8)));
|
||||
createUser(md5);
|
||||
assertThatThrownBy(() -> login("wrong")).isInstanceOf(AuthException.class);
|
||||
assertThat(jdbc.sql("SELECT password FROM users").query(String.class).single()).isEqualTo(md5);
|
||||
assertThat(login(PASSWORD)).isNotNull();
|
||||
assertThat(jdbc.sql("SELECT password FROM users").query(String.class).single()).startsWith("{argon2}");
|
||||
jdbc.sql("UPDATE users SET password=:password").param("password", PASSWORD).update();
|
||||
assertThat(login(PASSWORD)).isNotNull();
|
||||
assertThat(jdbc.sql("SELECT password FROM users").query(String.class).single()).startsWith("{argon2}");
|
||||
}
|
||||
@Test void newPasswordPolicyAppliesToChangeAndResetButNotToLogin() {
|
||||
createUser(passwords.encode("old"));
|
||||
var tokens = login("old");
|
||||
long user = Long.parseLong(decoder.decode(tokens.accessToken()).getSubject());
|
||||
assertThatThrownBy(() -> auth.changePassword(user, new PasswordRequest("old", "abcdefghij"), META))
|
||||
.isInstanceOfSatisfying(AuthException.class, e -> assertThat(e.getMessage()).contains("at least 3"));
|
||||
assertThat(login("old")).isNotNull();
|
||||
auth.changePassword(user, new PasswordRequest("old", "Abcdefgh12"), META); // 10 caracteres, no 12
|
||||
assertThat(login("Abcdefgh12")).isNotNull();
|
||||
recovery.request(EMAIL, META); delivery.deliverNext();
|
||||
assertThatThrownBy(() -> recovery.reset(new ResetPasswordRequest(null, mail.token, "abcdefghij"), META))
|
||||
.isInstanceOfSatisfying(AuthException.class, e -> assertThat(e.getMessage()).contains("at least 3"));
|
||||
assertThat(login("Abcdefgh12")).isNotNull();
|
||||
recovery.reset(new ResetPasswordRequest(null, mail.token, "Xyzdefgh34"), META);
|
||||
assertThat(login("Xyzdefgh34")).isNotNull();
|
||||
}
|
||||
@Test void sessionLimitRevokesOldestAndDisabledUserCannotRefreshOrUseJwt() {
|
||||
var first = createAndLogin();
|
||||
jdbc.sql("UPDATE auth_session SET created_at=CURRENT_TIMESTAMP-INTERVAL '1 hour'").update();
|
||||
var second = login(PASSWORD); var third = login(PASSWORD);
|
||||
assertThatThrownBy(() -> decoder.decode(first.accessToken())).isInstanceOf(JwtException.class);
|
||||
assertThat(decoder.decode(second.accessToken())).isNotNull();
|
||||
jdbc.sql("UPDATE users SET id_status=2").update();
|
||||
assertThatThrownBy(() -> login(PASSWORD)).isInstanceOfSatisfying(AuthException.class, e -> assertThat(e.status()).isEqualTo(403));
|
||||
assertThatThrownBy(() -> refresh(third.refreshToken())).isInstanceOf(AuthException.class);
|
||||
assertThatThrownBy(() -> decoder.decode(second.accessToken())).isInstanceOf(JwtException.class);
|
||||
}
|
||||
@Test void refreshTokensAreHashedAndAuditContainsNoSecrets() {
|
||||
var tokens = createAndLogin();
|
||||
assertThat(jdbc.sql("SELECT token_hash FROM refresh_tokens").query(String.class).single()).hasSize(64).isNotEqualTo(tokens.refreshToken());
|
||||
assertThat(jdbc.sql("SELECT action FROM audit_events").query(String.class).single()).isEqualTo("login_success");
|
||||
assertThat(jdbc.sql("SELECT user_agent FROM audit_events").query(String.class).single()).isEqualTo("integration-test");
|
||||
assertThat(jdbc.sql("SELECT user_id FROM audit_events").query(Long.class).single()).isEqualTo(42L);
|
||||
assertThat(jdbc.sql("SELECT created_by_ip FROM refresh_tokens").query(String.class).single()).isEqualTo(META.ip());
|
||||
}
|
||||
@Test void refreshRotationPersistsNodeMetadataAndReplacementHash() {
|
||||
var original = createAndLogin();
|
||||
var rotated = refresh(original.refreshToken());
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM refresh_tokens WHERE revoked_at IS NOT NULL").query(Integer.class).single()).isEqualTo(1);
|
||||
String replacementHash = jdbc.sql("SELECT replaced_by_token_hash FROM refresh_tokens WHERE revoked_at IS NOT NULL")
|
||||
.query(String.class).single();
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM refresh_tokens WHERE token_hash=:hash AND revoked_at IS NULL")
|
||||
.param("hash", replacementHash).query(Integer.class).single()).isEqualTo(1);
|
||||
assertThat(decoder.decode(rotated.accessToken()).getSubject()).isEqualTo("42");
|
||||
}
|
||||
@Test void existingMixedCaseEmailAndRoleForeignKeyAreUsedDirectly() {
|
||||
createUser(passwords.encode(PASSWORD));
|
||||
// La numeración de rol no se asume: el nombre se obtiene mediante JOIN.
|
||||
jdbc.sql("INSERT INTO rol(id,name) VALUES (97,'admin')").update();
|
||||
jdbc.sql("UPDATE users SET email='TEST@Example.COM',id_rol=97").update();
|
||||
var token = login(PASSWORD);
|
||||
assertThat(decoder.decode(token.accessToken()).getClaimAsString("rol")).isEqualTo("admin");
|
||||
assertThat(decoder.decode(token.accessToken()).getClaimAsStringList("roles")).containsExactly("ADMIN");
|
||||
jdbc.sql("UPDATE users SET id_rol=2").update();
|
||||
jdbc.sql("DELETE FROM rol WHERE id=97").update();
|
||||
}
|
||||
@Test void recoveryStoresOnlyHashAndTokenIsSingleUseAndRevokesSessions() {
|
||||
var tokens = createAndLogin();
|
||||
recovery.request(EMAIL, META); recovery.request(EMAIL, META);
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM password_reset_request").query(Integer.class).single()).isEqualTo(1);
|
||||
assertThat(delivery.deliverNext()).isTrue();
|
||||
assertThat(mail.recipient).isEqualTo(EMAIL); assertThat(mail.token).matches("[a-f0-9]{64}");
|
||||
assertThat(jdbc.sql("SELECT reset_token_hash FROM users").query(String.class).single()).hasSize(64).isNotEqualTo(mail.token);
|
||||
assertThatThrownBy(() -> recovery.reset(new ResetPasswordRequest(null, mail.token, PASSWORD), META)).isInstanceOf(AuthException.class);
|
||||
recovery.reset(new ResetPasswordRequest(EMAIL, mail.token, NEXT_PASSWORD), META);
|
||||
assertThatThrownBy(() -> recovery.reset(new ResetPasswordRequest(null, mail.token, "A-third-strong-password-2026"), META)).isInstanceOf(AuthException.class);
|
||||
assertThatThrownBy(() -> decoder.decode(tokens.accessToken())).isInstanceOf(JwtException.class);
|
||||
assertThatThrownBy(() -> refresh(tokens.refreshToken())).isInstanceOf(AuthException.class);
|
||||
assertThat(login(NEXT_PASSWORD)).isNotNull();
|
||||
}
|
||||
@Test void resetRejectsExpiredTokenAndWrongEmail() {
|
||||
createAndLogin(); recovery.request(EMAIL, META); delivery.deliverNext();
|
||||
assertThatThrownBy(() -> recovery.reset(new ResetPasswordRequest("wrong@example.com", mail.token, NEXT_PASSWORD), META)).isInstanceOf(AuthException.class);
|
||||
jdbc.sql("UPDATE users SET reset_token_expires_at=CURRENT_TIMESTAMP-INTERVAL '1 minute'").update();
|
||||
assertThatThrownBy(() -> recovery.reset(new ResetPasswordRequest(null, mail.token, NEXT_PASSWORD), META)).isInstanceOf(AuthException.class);
|
||||
assertThat(login(PASSWORD)).isNotNull();
|
||||
}
|
||||
@Test void smtpFailuresRemainQueuedWithoutReplacingActiveResetToken() {
|
||||
createAndLogin(); recovery.request(EMAIL, META); mail.failing = true;
|
||||
assertThat(delivery.deliverNext()).isTrue();
|
||||
assertThat(jdbc.sql("SELECT attempts FROM password_reset_request").query(Integer.class).single()).isEqualTo(1);
|
||||
assertThat(jdbc.sql("SELECT reset_token_hash IS NULL FROM users").query(Boolean.class).single()).isTrue();
|
||||
mail.failing = false;
|
||||
jdbc.sql("UPDATE password_reset_request SET available_at=CURRENT_TIMESTAMP").update();
|
||||
assertThat(delivery.deliverNext()).isTrue(); assertThat(mail.token).isNotBlank();
|
||||
}
|
||||
@Test void httpContractMatchesNodeAndChangeRequiresBearer() throws Exception {
|
||||
createUser(passwords.encode(PASSWORD));
|
||||
var body = json.writeValueAsString(new LoginRequest(EMAIL, PASSWORD));
|
||||
var login = request("/auth/login", body, null);
|
||||
assertThat(login.statusCode()).isEqualTo(200);
|
||||
var loginJson = json.readTree(login.body());
|
||||
assertThat(loginJson.get("status").asText()).isEqualTo("success");
|
||||
var tokens = json.treeToValue(loginJson.get("data"), TokenResponse.class);
|
||||
var refresh = request("/api/v1/auth/refresh", json.writeValueAsString(new RefreshRequest(tokens.refreshToken())), null);
|
||||
assertThat(refresh.statusCode()).isEqualTo(200);
|
||||
assertThat(request("/auth/changepassword", json.writeValueAsString(new PasswordRequest(PASSWORD, NEXT_PASSWORD)), null).statusCode()).isEqualTo(401);
|
||||
// Un interceptor del frontend puede adjuntar un access token caducado a una ruta pública.
|
||||
var logout = request("/auth/logout", json.writeValueAsString(new RefreshRequest(tokens.refreshToken())), "invalid-or-expired-access-token");
|
||||
assertThat(logout.statusCode()).isEqualTo(200); assertThat(logout.body()).contains("Logout ok.", "success");
|
||||
assertThat(request("/auth/login", "{\"email\":\"bad\",\"password\":\"x\"}", null).statusCode()).isEqualTo(400);
|
||||
assertThat(request("/auth/register", body, null).statusCode()).isEqualTo(401);
|
||||
}
|
||||
@Test void forgotHttpResponseIsIdenticalForUnknownAndExistingEmail() throws Exception {
|
||||
createUser(passwords.encode(PASSWORD));
|
||||
var known = request("/auth/forgotpassword", json.writeValueAsString(new ForgotPasswordRequest(EMAIL)), null);
|
||||
var unknown = request("/auth/forgotpassword", json.writeValueAsString(new ForgotPasswordRequest("unknown@example.com")), null);
|
||||
assertThat(known.statusCode()).isEqualTo(200); assertThat(unknown.statusCode()).isEqualTo(200);
|
||||
assertThat(known.body()).isEqualTo(unknown.body());
|
||||
assertThat(known.headers().firstValue("Cache-Control")).hasValue("no-store");
|
||||
}
|
||||
@Test void changeAndResetHttpUseNodeFieldNamesAndValidateNewPassword() throws Exception {
|
||||
var tokens = createAndLogin();
|
||||
var change = request("/auth/changepassword", json.writeValueAsString(new PasswordRequest(PASSWORD, NEXT_PASSWORD)), tokens.accessToken());
|
||||
assertThat(change.statusCode()).isEqualTo(200); assertThat(change.body()).contains("success");
|
||||
recovery.request(EMAIL, META); delivery.deliverNext();
|
||||
var invalid = request("/auth/resetpassword", json.writeValueAsString(new ResetPasswordRequest(null, mail.token, "short")), null);
|
||||
assertThat(invalid.statusCode()).isEqualTo(400);
|
||||
var reset = request("/auth/resetpassword", json.writeValueAsString(new ResetPasswordRequest(null, mail.token, "A-third-strong-password-2026")), null);
|
||||
assertThat(reset.statusCode()).isEqualTo(200); assertThat(reset.body()).contains("success");
|
||||
var retry = request("/auth/resetpassword", json.writeValueAsString(new ResetPasswordRequest(null, mail.token, "A-fourth-strong-password-2026")), null);
|
||||
assertThat(retry.statusCode()).isEqualTo(400); assertThat(retry.body()).contains("error");
|
||||
}
|
||||
HttpResponse<String> request(String path, String body, String token) throws Exception {
|
||||
var request = HttpRequest.newBuilder(URI.create("http://localhost:" + environment.getProperty("local.server.port") + path))
|
||||
.header("Content-Type", "application/json");
|
||||
if (token != null) request.header("Authorization", "Bearer " + token);
|
||||
return http.send(request.POST(HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.aellis.auth;
|
||||
|
||||
import com.aellis.auth.api.AuthDtos.LoginRequest;
|
||||
import com.aellis.auth.service.*;
|
||||
import java.nio.file.*;
|
||||
import java.net.URI;
|
||||
import java.net.http.*;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.jdbc.datasource.init.ScriptUtils;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.*;
|
||||
import org.testcontainers.postgresql.PostgreSQLContainer;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/** Verifica application-node.yml y el login real sobre tablas Sequelize preexistentes. */
|
||||
@ActiveProfiles("node")
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = {"logging.level.root=WARN", "debug=false", "auth.recovery.enabled=false",
|
||||
"spring.mail.host=127.0.0.1", "spring.mail.port=1"})
|
||||
class NodeProfileIT {
|
||||
static final PostgreSQLContainer DB = new PostgreSQLContainer("postgres:18");
|
||||
static String url;
|
||||
static String username;
|
||||
static String password;
|
||||
static String schema;
|
||||
static Path keys;
|
||||
static final String USER_PASSWORD = "Existing-user-password-2026";
|
||||
@DynamicPropertySource static void existingDatabase(DynamicPropertyRegistry registry) throws Exception {
|
||||
url = System.getenv("TEST_DB_URL");
|
||||
if (url == null) { DB.start(); url = DB.getJdbcUrl(); username = DB.getUsername(); password = DB.getPassword(); }
|
||||
else { username = System.getenv("TEST_DB_USER"); password = System.getenv("TEST_DB_PASSWORD"); }
|
||||
schema = "node_profile_test_" + UUID.randomUUID().toString().replace("-", "");
|
||||
try (var connection = DriverManager.getConnection(url, username, password); var statement = connection.createStatement()) {
|
||||
statement.execute("CREATE SCHEMA " + schema);
|
||||
}
|
||||
String schemaUrl = url + (url.contains("?") ? "&" : "?") + "currentSchema=" + schema;
|
||||
var source = new DriverManagerDataSource(schemaUrl, username, password);
|
||||
try (var connection = source.getConnection()) {
|
||||
ScriptUtils.executeSqlScript(connection, new ClassPathResource("fixtures/sequelize-schema.sql"));
|
||||
}
|
||||
JdbcClient.create(source).sql("UPDATE users SET password=:hash WHERE id=9001")
|
||||
.param("hash", new BCryptPasswordEncoder().encode(USER_PASSWORD)).update();
|
||||
// Reproduce la base del primer arranque del usuario: users existe, refresh_tokens no.
|
||||
JdbcClient.create(source).sql("DROP TABLE refresh_tokens").update();
|
||||
keys = Files.createTempDirectory("genesis-node-test-keys");
|
||||
var generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(3072);
|
||||
var pair = generator.generateKeyPair();
|
||||
Files.writeString(keys.resolve("private.pem"), pem("PRIVATE KEY", pair.getPrivate().getEncoded()));
|
||||
Files.writeString(keys.resolve("public.pem"), pem("PUBLIC KEY", pair.getPublic().getEncoded()));
|
||||
registry.add("spring.datasource.url", () -> schemaUrl);
|
||||
registry.add("spring.datasource.username", () -> username);
|
||||
registry.add("spring.datasource.password", () -> password);
|
||||
registry.add("auth.private-key", () -> keys.resolve("private.pem").toUri().toString());
|
||||
registry.add("auth.public-key", () -> keys.resolve("public.pem").toUri().toString());
|
||||
}
|
||||
static String pem(String type, byte[] bytes) {
|
||||
return "-----BEGIN " + type + "-----\n" + Base64.getEncoder().encodeToString(bytes) + "\n-----END " + type + "-----";
|
||||
}
|
||||
@Autowired AuthService auth;
|
||||
@Autowired JdbcClient jdbc;
|
||||
@Autowired JwtDecoder decoder;
|
||||
@Autowired Environment environment;
|
||||
@Test void healthDoesNotContactSmtpWhenPasswordRecoveryIsDisabled() throws Exception {
|
||||
var request = HttpRequest.newBuilder(URI.create("http://localhost:" + environment.getProperty("local.server.port")
|
||||
+ "/actuator/health")).GET().build();
|
||||
var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).contains("\"status\":\"UP\"");
|
||||
}
|
||||
@Test void nodeProfileStartsWithoutRefreshTableAndPreservesUsersCatalogsAndAudit() {
|
||||
var token = auth.login(new LoginRequest("existing@example.com", USER_PASSWORD), RequestMetadata.system());
|
||||
var jwt = decoder.decode(token.accessToken());
|
||||
assertThat(jwt.getSubject()).isEqualTo("9001");
|
||||
assertThat(((Number) jwt.getClaim("id")).longValue()).isEqualTo(9001L);
|
||||
assertThat(jwt.getClaimAsString("rol")).isEqualTo("admin");
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM users").query(Integer.class).single()).isEqualTo(1);
|
||||
assertThat(jdbc.sql("SELECT id_rol FROM users WHERE id=9001").query(Integer.class).single()).isEqualTo(17);
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM rol").query(Integer.class).single()).isEqualTo(2);
|
||||
assertThat(jdbc.sql("SELECT password FROM users WHERE id=9001").query(String.class).single()).startsWith("{argon2}");
|
||||
assertThat(jdbc.sql("SELECT metadata->>'source' FROM audit_events WHERE id=88").query(String.class).single()).isEqualTo("node");
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM refresh_tokens WHERE user_id=9001 AND session_id IS NOT NULL AND revoked_at IS NULL")
|
||||
.query(Integer.class).single()).isEqualTo(1);
|
||||
assertThatThrownBy(() -> auth.refresh("old-node-token-without-session", RequestMetadata.system()))
|
||||
.isInstanceOf(com.aellis.auth.api.AuthException.class);
|
||||
auth.cleanup();
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM audit_events WHERE id=88").query(Integer.class).single()).isEqualTo(1);
|
||||
}
|
||||
@AfterAll static void cleanup() throws Exception {
|
||||
if (schema != null) {
|
||||
try (var connection = DriverManager.getConnection(url, username, password); var statement = connection.createStatement()) {
|
||||
statement.execute("DROP SCHEMA " + schema + " CASCADE");
|
||||
}
|
||||
}
|
||||
if (keys != null) { Files.deleteIfExists(keys.resolve("private.pem")); Files.deleteIfExists(keys.resolve("public.pem")); Files.deleteIfExists(keys); }
|
||||
if (DB.isRunning()) DB.stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.aellis.auth;
|
||||
|
||||
import com.aellis.auth.repository.UserRepository;
|
||||
import com.aellis.auth.service.*;
|
||||
import java.sql.*;
|
||||
import java.util.UUID;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.flywaydb.core.api.FlywayException;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.jdbc.datasource.init.ScriptUtils;
|
||||
import org.testcontainers.postgresql.PostgreSQLContainer;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/** Ensayos aislados por schema; nunca usa las tablas reales de la conexión compartida. */
|
||||
class SchemaMigrationIT {
|
||||
static final PostgreSQLContainer DB = new PostgreSQLContainer("postgres:18");
|
||||
static String url;
|
||||
static String username;
|
||||
static String password;
|
||||
String schema;
|
||||
DriverManagerDataSource source;
|
||||
JdbcClient jdbc;
|
||||
@BeforeAll static void database() {
|
||||
url = System.getenv("TEST_DB_URL");
|
||||
if (url == null) { DB.start(); url = DB.getJdbcUrl(); username = DB.getUsername(); password = DB.getPassword(); }
|
||||
else { username = System.getenv("TEST_DB_USER"); password = System.getenv("TEST_DB_PASSWORD"); }
|
||||
}
|
||||
@AfterAll static void stopDatabase() { if (DB.isRunning()) DB.stop(); }
|
||||
@BeforeEach void isolatedSchema() throws Exception {
|
||||
schema = "migration_test_" + UUID.randomUUID().toString().replace("-", "");
|
||||
try (var connection = DriverManager.getConnection(url, username, password); var statement = connection.createStatement()) {
|
||||
statement.execute("CREATE SCHEMA " + schema);
|
||||
}
|
||||
source = new DriverManagerDataSource(url + (url.contains("?") ? "&" : "?") + "currentSchema=" + schema, username, password);
|
||||
jdbc = JdbcClient.create(source);
|
||||
}
|
||||
@AfterEach void removeSchema() throws Exception {
|
||||
// schema se genera arriba con un prefijo fijo y UUID hexadecimal, nunca con entrada externa.
|
||||
try (var connection = DriverManager.getConnection(url, username, password); var statement = connection.createStatement()) {
|
||||
statement.execute("DROP SCHEMA " + schema + " CASCADE");
|
||||
}
|
||||
}
|
||||
void sequelizeFixture() throws Exception {
|
||||
try (var connection = source.getConnection()) {
|
||||
ScriptUtils.executeSqlScript(connection, new ClassPathResource("fixtures/sequelize-schema.sql"));
|
||||
}
|
||||
}
|
||||
Flyway nodeMigration() {
|
||||
return nodeMigration(false);
|
||||
}
|
||||
Flyway nodeMigration(boolean skipCallbacks) {
|
||||
return Flyway.configure().dataSource(source).schemas(schema).defaultSchema(schema)
|
||||
.locations("classpath:db/node-migration").table("genesis_auth_schema_history")
|
||||
.baselineOnMigrate(true).baselineVersion("0").skipDefaultCallbacks(skipCallbacks).load();
|
||||
}
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"refresh_tokens", "audit_events", "both"})
|
||||
void missingOptionalTablesCanRecoverFromTheOriginalFailedStartup(String missing) throws Exception {
|
||||
sequelizeFixture();
|
||||
// Solo tablas de la fixture, dentro del schema desechable generado por esta prueba.
|
||||
if (missing.equals("refresh_tokens") || missing.equals("both")) jdbc.sql("DROP TABLE refresh_tokens").update();
|
||||
if (missing.equals("audit_events") || missing.equals("both")) jdbc.sql("DROP TABLE audit_events").update();
|
||||
// Reproduce el arranque anterior sin preparación: V1 falla y se revierte, conservando baseline 0.
|
||||
assertThatThrownBy(() -> nodeMigration(true).migrate()).isInstanceOf(FlywayException.class);
|
||||
assertThat(jdbc.sql("SELECT to_regclass('auth_session') IS NULL").query(Boolean.class).single()).isTrue();
|
||||
nodeMigration().migrate();
|
||||
assertThat(jdbc.sql("SELECT to_regclass('refresh_tokens') IS NOT NULL AND to_regclass('audit_events') IS NOT NULL")
|
||||
.query(Boolean.class).single()).isTrue();
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM users").query(Integer.class).single()).isEqualTo(1);
|
||||
assertThat(jdbc.sql("SELECT password FROM users WHERE id=9001").query(String.class).single()).isEqualTo("hash-original");
|
||||
new AuditService(jdbc, JsonMapper.builder().build()).record("java_recovered", 9001L, null, RequestMetadata.system());
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM audit_events WHERE action='java_recovered'").query(Integer.class).single()).isEqualTo(1);
|
||||
assertThat(nodeMigration().migrate().migrationsExecuted).isZero();
|
||||
}
|
||||
@Test void existingNodeDataIdsAndMetadataSurviveAndRepositoryReadsAssociations() throws Exception {
|
||||
sequelizeFixture(); nodeMigration().migrate();
|
||||
var user = new UserRepository(jdbc).findByEmailForUpdate("existing@example.com").orElseThrow();
|
||||
assertThat(user.id()).isEqualTo(9001L);
|
||||
assertThat(user.passwordHash()).isEqualTo("hash-original");
|
||||
assertThat(user.roleId()).isEqualTo(17);
|
||||
assertThat(user.role()).isEqualTo("admin");
|
||||
assertThat(user.specializationId()).isEqualTo(8);
|
||||
assertThat(user.rate()).isEqualTo(12.3456789);
|
||||
assertThat(jdbc.sql("SELECT session_id IS NULL AND revoked_at IS NULL FROM refresh_tokens WHERE id=77")
|
||||
.query(Boolean.class).single()).isTrue();
|
||||
assertThat(jdbc.sql("SELECT metadata->>'source' FROM audit_events WHERE id=88").query(String.class).single()).isEqualTo("node");
|
||||
new AuditService(jdbc, JsonMapper.builder().build()).record("java_test", user.id(), "verified", RequestMetadata.system());
|
||||
assertThat(jdbc.sql("SELECT metadata->>'reason' FROM audit_events WHERE action='java_test'").query(String.class).single()).isEqualTo("verified");
|
||||
assertThat(jdbc.sql("SELECT reset_token_hash FROM users WHERE id=9001").query(String.class).single()).isEqualTo("a".repeat(64));
|
||||
assertThat(jdbc.sql("SELECT to_regclass('app_user') IS NULL").query(Boolean.class).single()).isTrue();
|
||||
assertThat(nodeMigration().migrate().migrationsExecuted).isZero();
|
||||
}
|
||||
@Test void ambiguousNormalizedEmailsAbortWithoutDeletingUsers() throws Exception {
|
||||
sequelizeFixture();
|
||||
jdbc.sql("""
|
||||
INSERT INTO users(name,lastname,email,rate,acronym,password,id_rol)
|
||||
VALUES ('Otra','Cuenta','existing@example.com',0,'OC','hash',23)
|
||||
""").update();
|
||||
assertThatThrownBy(() -> nodeMigration().migrate()).isInstanceOf(FlywayException.class);
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM users").query(Integer.class).single()).isEqualTo(2);
|
||||
assertThat(jdbc.sql("SELECT to_regclass('auth_session') IS NULL").query(Boolean.class).single()).isTrue();
|
||||
assertThat(jdbc.sql("SELECT password FROM users WHERE id=9001").query(String.class).single()).isEqualTo("hash-original");
|
||||
}
|
||||
@Test void developmentConversionPreservesAccountsQueuesAndAuditAndRevokesOldSessions() {
|
||||
Flyway.configure().dataSource(source).schemas(schema).defaultSchema(schema)
|
||||
.locations("classpath:db/migration").target("2").load().migrate();
|
||||
UUID previousUser = UUID.randomUUID(); UUID previousSession = UUID.randomUUID(); UUID previousEvent = UUID.randomUUID();
|
||||
jdbc.sql("""
|
||||
INSERT INTO app_user(id,email,password_hash,role,legacy_id,name,lastname,acronym,rate)
|
||||
VALUES (:id,'keep@example.com','unchanged-password','ADMIN',76,'Ana','Original','AO',3.5)
|
||||
""").param("id", previousUser).update();
|
||||
jdbc.sql("INSERT INTO app_user(id,email,password_hash) VALUES (:id,'new-id@example.com','other-password')")
|
||||
.param("id", UUID.randomUUID()).update();
|
||||
jdbc.sql("INSERT INTO auth_session(id,user_id,expires_at) VALUES (:session,:user,CURRENT_TIMESTAMP+INTERVAL '1 day')")
|
||||
.param("session", previousSession).param("user", previousUser).update();
|
||||
jdbc.sql("INSERT INTO refresh_token(token_hash,session_id) VALUES (:hash,:session)")
|
||||
.param("hash", "a".repeat(64)).param("session", previousSession).update();
|
||||
jdbc.sql("INSERT INTO password_reset_request(user_id) VALUES (:user)").param("user", previousUser).update();
|
||||
jdbc.sql("INSERT INTO auth_audit_event(id,user_id,action,reason) VALUES (:id,:user,'old_event','preserved')")
|
||||
.param("id", previousEvent).param("user", previousUser).update();
|
||||
Flyway.configure().dataSource(source).schemas(schema).defaultSchema(schema).locations("classpath:db/migration").load().migrate();
|
||||
assertThat(jdbc.sql("SELECT password FROM users WHERE id=76").query(String.class).single()).isEqualTo("unchanged-password");
|
||||
assertThat(jdbc.sql("SELECT id_rol FROM users WHERE id=76").query(Integer.class).single()).isEqualTo(1);
|
||||
assertThat(jdbc.sql("SELECT revoked FROM auth_session WHERE id=:id").param("id", previousSession).query(Boolean.class).single()).isTrue();
|
||||
assertThat(jdbc.sql("SELECT user_id FROM password_reset_request").query(Integer.class).single()).isEqualTo(76);
|
||||
assertThat(jdbc.sql("SELECT revoked_at IS NOT NULL FROM refresh_tokens").query(Boolean.class).single()).isTrue();
|
||||
assertThat(jdbc.sql("SELECT metadata->>'previous_event_id' FROM audit_events").query(String.class).single()).isEqualTo(previousEvent.toString());
|
||||
assertThat(jdbc.sql("SELECT metadata->>'reason' FROM audit_events").query(String.class).single()).isEqualTo("preserved");
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM users").query(Integer.class).single()).isEqualTo(2);
|
||||
assertThat(jdbc.sql("SELECT to_regclass('app_user') IS NULL").query(Boolean.class).single()).isTrue();
|
||||
}
|
||||
@Test void emptyDatabaseGetsTheSameNodeTableNamesAndIntegerKeys() {
|
||||
Flyway.configure().dataSource(source).schemas(schema).defaultSchema(schema).locations("classpath:db/migration").load().migrate();
|
||||
assertThat(jdbc.sql("SELECT data_type FROM information_schema.columns WHERE table_schema=:schema AND table_name='users' AND column_name='id'")
|
||||
.param("schema", schema).query(String.class).single()).isEqualTo("integer");
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM rol").query(Integer.class).single()).isEqualTo(2);
|
||||
assertThat(jdbc.sql("SELECT count(*) FROM users").query(Integer.class).single()).isZero();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.aellis.auth.config;
|
||||
|
||||
import java.time.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class LoginRateLimitFilterTest {
|
||||
@Test void limitsEachAddressIndependently() {
|
||||
var filter = new LoginRateLimitFilter(Clock.fixed(Instant.EPOCH, ZoneOffset.UTC));
|
||||
for (int i = 0; i < 20; i++) assertThat(filter.allow("127.0.0.1")).isTrue();
|
||||
assertThat(filter.allow("127.0.0.1")).isFalse();
|
||||
assertThat(filter.allow("127.0.0.2")).isTrue();
|
||||
}
|
||||
|
||||
@Test void allowsRequestsInNextWindow() {
|
||||
var clock = org.mockito.Mockito.mock(Clock.class);
|
||||
org.mockito.Mockito.when(clock.instant()).thenReturn(Instant.EPOCH);
|
||||
var filter = new LoginRateLimitFilter(clock);
|
||||
for (int i = 0; i < 21; i++) filter.allow("client");
|
||||
org.mockito.Mockito.when(clock.instant()).thenReturn(Instant.EPOCH.plusSeconds(60));
|
||||
assertThat(filter.allow("client")).isTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import com.aellis.auth.config.AuthPolicyProperties;
|
||||
import org.springframework.boot.context.properties.bind.*;
|
||||
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
class MigrationPasswordEncoderTest {
|
||||
@Test void encodesModernHashesAndAcceptsNodeBcrypt() {
|
||||
var encoder = new MigrationPasswordEncoder(false);
|
||||
var hash = encoder.encode("A-long-password-2026");
|
||||
assertThat(hash).startsWith("{argon2}");
|
||||
assertThat(encoder.matches("A-long-password-2026", hash)).isTrue();
|
||||
assertThat(encoder.matches("wrong", hash)).isFalse();
|
||||
String bcrypt = new BCryptPasswordEncoder(12).encode("node-password");
|
||||
assertThat(encoder.matches("node-password", bcrypt)).isTrue();
|
||||
assertThat(encoder.matches("node-password", bcrypt.replace("$2a$", "$2b$"))).isTrue();
|
||||
assertThat(encoder.matches("node-password", bcrypt.replace("$2a$", "$2y$"))).isTrue();
|
||||
assertThat(encoder.upgradeEncoding(bcrypt)).isTrue();
|
||||
assertThat(encoder.upgradeEncoding(hash)).isFalse();
|
||||
}
|
||||
@Test void requiresOptInAndAcceptsTheActualNodeLegacyFormats() throws Exception {
|
||||
var disabled = new MigrationPasswordEncoder(false);
|
||||
var enabled = new MigrationPasswordEncoder(true);
|
||||
String password = "old-password";
|
||||
String md5 = HexFormat.of().formatHex(MessageDigest.getInstance("MD5").digest(password.getBytes(StandardCharsets.UTF_8)));
|
||||
assertThat(disabled.matches(password, "{legacy-md5}" + md5)).isFalse();
|
||||
assertThat(disabled.matches(password, "{legacy-plain}" + password)).isFalse();
|
||||
assertThat(disabled.matches(password, md5)).isFalse();
|
||||
assertThat(disabled.matches(password, password)).isFalse();
|
||||
assertThat(enabled.matches(password, md5)).isTrue();
|
||||
assertThat(enabled.matches(password, md5.toUpperCase())).isTrue();
|
||||
assertThat(enabled.matches(password, password)).isTrue();
|
||||
assertThat(enabled.matches(password, "{legacy-md5}" + md5.toUpperCase())).isTrue();
|
||||
assertThat(enabled.matches(password, "{legacy-plain}" + password)).isTrue();
|
||||
assertThat(enabled.matches(md5, "{legacy-md5}" + md5)).isFalse();
|
||||
assertThat(enabled.matches(md5, md5)).isFalse();
|
||||
assertThat(enabled.matches(password, "{legacy-md5}not-a-hash")).isFalse();
|
||||
assertThat(enabled.matches("$2b$malformed", "$2b$malformed")).isFalse();
|
||||
}
|
||||
@Test void doesNotUpgradeBcryptUsingAnInputBeyondIts72ByteLimit() {
|
||||
var encoder = new MigrationPasswordEncoder(false);
|
||||
String password = "a".repeat(72);
|
||||
String hash = new BCryptPasswordEncoder().encode(password);
|
||||
assertThat(encoder.matches(password, hash)).isTrue();
|
||||
assertThat(encoder.matches(password + "different-suffix", hash)).isFalse();
|
||||
}
|
||||
@Test void defaultPolicyMatchesNodeLengthAndClassRules() {
|
||||
var policy = new AuthPolicyProperties(false, 5, 10, 128, 3, true);
|
||||
assertThat(policy.passwordPolicyError("Abcdefgh12")).isNull();
|
||||
assertThat(policy.passwordPolicyError("Abcdefgh!?")).isNull();
|
||||
assertThat(policy.passwordPolicyError("Abcdefg12")).isEqualTo("Password must be at least 10 characters long.");
|
||||
assertThat(policy.passwordPolicyError("abcdefghij")).isEqualTo(
|
||||
"Password must include at least 3 of: lowercase, uppercase, number, symbol.");
|
||||
assertThat(policy.passwordPolicyError("Aa1" + "x".repeat(125))).isNull();
|
||||
assertThat(policy.passwordPolicyError("Aa1" + "x".repeat(126))).isEqualTo("Password must be at most 128 characters long.");
|
||||
}
|
||||
@Test void configurableComplexityDoesNotTrimOrChangeThePassword() {
|
||||
var disabled = new AuthPolicyProperties(false, 5, 10, 128, 3, false);
|
||||
assertThat(disabled.passwordPolicyError(" ".repeat(10))).isNull();
|
||||
assertThat(disabled.passwordPolicyError("abcdefghij")).isNull();
|
||||
assertThat(disabled.passwordPolicyError("short")).isNotNull();
|
||||
var stricter = new AuthPolicyProperties(false, 5, 16, 32, 4, true);
|
||||
assertThat(stricter.passwordPolicyError("Aa1!".repeat(4))).isNull();
|
||||
assertThat(stricter.passwordPolicyError("Aa12".repeat(4))).contains("at least 4");
|
||||
}
|
||||
@Test void unicodeLengthAndCharacterClassesFollowJavascriptSemantics() {
|
||||
var policy = new AuthPolicyProperties(false, 5, 10, 10, 3, true);
|
||||
assertThat(policy.passwordPolicyError("Aa" + "😀".repeat(4))).isNull(); // 10 unidades UTF-16
|
||||
assertThat(policy.passwordPolicyError("Aa1" + "😀".repeat(4))).contains("at most 10");
|
||||
var fourClasses = new AuthPolicyProperties(false, 5, 10, 128, 4, true);
|
||||
assertThat(fourClasses.passwordPolicyError("Aa" + "١".repeat(8))).contains("at least 4"); // dígito no ASCII = símbolo
|
||||
}
|
||||
@Test void springBindingProvidesDefaultsAndAcceptsPolicyOverrides() {
|
||||
var defaults = new Binder(new MapConfigurationPropertySource(Map.of("auth.policy.max-active-sessions", "5")))
|
||||
.bind("auth.policy", Bindable.of(AuthPolicyProperties.class)).get();
|
||||
assertThat(defaults.passwordMinLength()).isEqualTo(10);
|
||||
assertThat(defaults.passwordMaxLength()).isEqualTo(128);
|
||||
assertThat(defaults.passwordMinClasses()).isEqualTo(3);
|
||||
assertThat(defaults.passwordRequireComplexity()).isTrue();
|
||||
var custom = new Binder(new MapConfigurationPropertySource(Map.of(
|
||||
"auth.policy.max-active-sessions", "5", "auth.policy.password-min-length", "16",
|
||||
"auth.policy.password-require-complexity", "false")))
|
||||
.bind("auth.policy", Bindable.of(AuthPolicyProperties.class)).get();
|
||||
assertThat(custom.passwordMinLength()).isEqualTo(16);
|
||||
assertThat(custom.passwordPolicyError("a".repeat(16))).isNull();
|
||||
assertThatThrownBy(() -> new AuthPolicyProperties(false, 5, 20, 10, 3, true)).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class ResetPasswordEmailTemplateTest {
|
||||
@Test void escapesDynamicHtmlAndDoesNotRecursivelySubstituteUserInput() throws Exception {
|
||||
var template = new ResetPasswordEmailTemplate();
|
||||
var content = template.build("<b>Ana & {{RESET_URL}}</b>", "https://example.com/reset?token=abc&x=1", 30, "A&B");
|
||||
assertThat(content.subject()).isEqualTo("A&B - Restablecer contraseña");
|
||||
assertThat(content.html()).contains("<b>Ana & {{RESET_URL}}</b>", "A&B", "abc&x=1");
|
||||
assertThat(content.html()).doesNotContain("<b>Ana");
|
||||
assertThat(content.text()).contains("Hola <b>Ana & {{RESET_URL}}</b>", "token=abc&x=1");
|
||||
}
|
||||
@Test void usesUsuarioWhenNoNameWasProvided() throws Exception {
|
||||
assertThat(new ResetPasswordEmailTemplate().build("", "https://example.com/reset", 30, "Genesis").text()).contains("Hola usuario");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.aellis.auth.service;
|
||||
|
||||
import com.aellis.auth.config.RecoveryProperties;
|
||||
import jakarta.mail.Multipart;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import java.net.URI;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class SmtpResetMailSenderTest {
|
||||
@Test void buildsAlternativeTextAndHtmlWithoutAllowingNameToInjectMarkup() throws Exception {
|
||||
var transport = new CapturingTransport();
|
||||
var properties = new RecoveryProperties(true, URI.create("https://example.com/reset-password"), "auth@example.com", "Genesis");
|
||||
var sender = new SmtpResetMailSender(transport, properties, new ResetPasswordEmailTemplate());
|
||||
sender.send("user@example.com", "<script>bad</script>", "a".repeat(64));
|
||||
transport.message.saveChanges();
|
||||
assertThat(transport.message.getSubject()).contains("Restablecer contraseña");
|
||||
assertThat(transport.message.getAllRecipients()[0].toString()).isEqualTo("user@example.com");
|
||||
String content = allText(transport.message.getContent());
|
||||
assertThat(content).contains("https://example.com/reset-password?token=" + "a".repeat(64), "<script>",
|
||||
"#4B2E83", "#00A3E0", "#0033A0", "30 minutos");
|
||||
}
|
||||
static String allText(Object part) throws Exception {
|
||||
if (part instanceof String text) return text;
|
||||
if (part instanceof Multipart multipart) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (int i = 0; i < multipart.getCount(); i++) text.append(allText(multipart.getBodyPart(i).getContent()));
|
||||
return text.toString();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
static class CapturingTransport extends JavaMailSenderImpl {
|
||||
MimeMessage message;
|
||||
@Override public void send(MimeMessage message) { this.message = message; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
-- Estructura de los modelos aportados. Los IDs de catálogo se eligen para detectar supuestos en Java.
|
||||
CREATE TABLE rol (id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL);
|
||||
CREATE TABLE specialization (id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL);
|
||||
CREATE TABLE status (id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, _table VARCHAR(255) NOT NULL);
|
||||
CREATE TABLE users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
lastname VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) NOT NULL UNIQUE,
|
||||
rate DOUBLE PRECISION NOT NULL,
|
||||
acronym VARCHAR(255) NOT NULL,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated TIMESTAMPTZ,
|
||||
reset_token_hash VARCHAR(255),
|
||||
reset_token_expires_at TIMESTAMPTZ,
|
||||
id_specialization INTEGER REFERENCES specialization(id),
|
||||
id_rol INTEGER NOT NULL DEFAULT 2 REFERENCES rol(id),
|
||||
id_status INTEGER NOT NULL DEFAULT 1 REFERENCES status(id)
|
||||
);
|
||||
CREATE TABLE refresh_tokens (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL,
|
||||
token_hash VARCHAR(255) NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
replaced_by_token_hash VARCHAR(255),
|
||||
created_by_ip VARCHAR(255),
|
||||
revoked_by_ip VARCHAR(255),
|
||||
user_agent VARCHAR(255),
|
||||
request_id VARCHAR(255),
|
||||
created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE audit_events (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER,
|
||||
action VARCHAR(255) NOT NULL,
|
||||
ip VARCHAR(255),
|
||||
user_agent VARCHAR(255),
|
||||
request_id VARCHAR(255),
|
||||
metadata JSONB,
|
||||
created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
INSERT INTO rol(id,name) VALUES (17,'admin'),(23,'user');
|
||||
INSERT INTO specialization(id,name) VALUES (8,'Especialidad original');
|
||||
INSERT INTO status(id,name,_table) VALUES (1,'Activo','users'),(2,'Deshabilitado','users');
|
||||
INSERT INTO users(id,name,lastname,email,rate,acronym,password,id_specialization,id_rol,id_status,reset_token_hash,reset_token_expires_at)
|
||||
VALUES (9001,'Usuario','Existente',' Existing@Example.com ',12.3456789,'UE','hash-original',8,17,1,repeat('a',64),CURRENT_TIMESTAMP+INTERVAL '30 minutes');
|
||||
INSERT INTO refresh_tokens(id,user_id,token_hash,expires_at,created_by_ip)
|
||||
VALUES (77,9001,'node-existing-refresh-hash',CURRENT_TIMESTAMP+INTERVAL '1 day','192.0.2.1');
|
||||
INSERT INTO audit_events(id,user_id,action,metadata)
|
||||
VALUES (88,9001,'node_login_success','{"source":"node","preserve":true}');
|
||||
-- Simula secuencias correctamente mantenidas por una base existente.
|
||||
SELECT setval(pg_get_serial_sequence('users','id'),9001,TRUE);
|
||||
SELECT setval(pg_get_serial_sequence('refresh_tokens','id'),77,TRUE);
|
||||
SELECT setval(pg_get_serial_sequence('audit_events','id'),88,TRUE);
|
||||
Reference in New Issue
Block a user