Implement business audit feature with database schema, service integration, and validation

This commit is contained in:
2026-10-23 15:36:34 +02:00
parent 4cf48101c4
commit 577b6df693
12 changed files with 420 additions and 6 deletions
+5
View File
@@ -126,3 +126,8 @@ Las pruebas de migración crean schemas aislados para verificar las tablas Seque
GitHub Actions ejecuta `verify` con Java 25. Docker Compose requiere validarse en una máquina con Docker. 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). 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).
## Historial de negocio
Las operaciones de escritura generan eventos transaccionales. La consulta de administradores se realiza en Reporting mediante `GET /reporting/audit`. Antes de desplegar, instala el esquema del historial desde Auth. Consulta [activacion, API y contrato](docs/business-audit.md).
+157
View File
@@ -0,0 +1,157 @@
# Historial de negocio
El historial explica quién cambió los datos, cuándo y cuáles fueron los valores anteriores y nuevos.
Se guarda en PostgreSQL y se consulta desde Reporting. No necesita otro microservicio.
## Activación
1. Realizar una copia de seguridad y verificar la migración en una copia aislada de la base.
2. Crear el esquema antes de desplegar los servicios instrumentados:
- Con Flyway: arrancar Auth con el mismo perfil que utiliza actualmente la instalación. La nueva migración es V4 en la instalación habitual o V2 en el perfil `node`. No cambiar de perfil para instalar el historial.
- Con gestión manual del esquema: ejecutar `genesis_authv2/scripts/business-audit-schema.sql` en la base y esquema correctos, en una transacción. El script contiene exactamente el mismo DDL que ambas migraciones.
3. Desplegar los siete servicios actualizados. Cada uno verifica la estructura al arrancar.
4. Realizar una modificación controlada y consultar su evento como administrador.
Utilizar un solo camino de gestión del esquema. Si se ejecuta el SQL manualmente en una instalación que después seguirá usando Flyway, debe coordinarse la migración con su responsable antes de ese arranque; el script no actualiza el historial de Flyway.
Durante un despliegue gradual únicamente registran eventos los servicios actualizados. No se reconstruyen cambios anteriores, ni se auditan modificaciones hechas directamente por SQL o por aplicaciones anteriores.
Si se vuelve a una versión anterior del código, conservar la tabla: los eventos existentes siguen siendo válidos, aunque esa versión deje de producir eventos nuevos.
No hay eliminación automática ni caducidad. El historial debe incluirse en las copias de seguridad y en la política de conservación de datos.
## Consultar
Petición a Reporting (puerto local habitual 8086):
```http
GET /reporting/audit?caseId=12&limit=50
Authorization: Bearer <access-token-administrador>
```
La respuesta respeta el envoltorio `status/data`:
```json
{
"status": "success",
"data": {
"events": [
{
"id": 125,
"occurredAt": "2026-10-23T12:30:00Z",
"service": "activities",
"action": "activity.update",
"entityType": "activity",
"entityId": 42,
"actorId": 3,
"actorName": "Ana Garcia",
"caseId": 12,
"before": { "amount": 120 },
"after": { "amount": 150 },
"reason": "Correccion de horas",
"operationId": "ba5e3db1-41b5-4ba3-a2e7-b7b86131d103",
"requestId": "peticion-123",
"formatVersion": 1
}
],
"nextCursor": null
}
}
```
Filtros combinables:
| Parámetro | Significado |
|---|---|
| entityType | `case`, `assignment`, `activity`, `payment`, `client`, `user` o `specialization`. |
| entityId | Identificador de la entidad. Para una asignación, es el caso; el usuario asignado está en before/after. |
| caseId | Reúne operaciones del caso, asignaciones, actividades y abonos relacionados. |
| actorId | Usuario que ejecutó la operación. |
| action | Acción exacta de la tabla siguiente. |
| operationId | UUID común de una operación y sus efectos automáticos. |
| from / to | Instantes ISO 8601 con zona: inicio inclusivo y fin exclusivo. |
| beforeId | Cursor exclusivo de la página siguiente. |
| limit | 50 por defecto, entre 1 y 100. |
Se ordena por `id` descendente. Para continuar, enviar `beforeId=nextCursor` conservando los demás filtros. Un cursor nulo indica el final.
Para ver eventos nuevos, refrescar la primera página. Los identificadores pueden tener saltos después de un rollback.
Los filtros inválidos devuelven 400. Sin autenticación se devuelve 401; con un usuario que no sea administrador, 403.
No existen rutas para modificar o borrar eventos.
## Añadir un motivo
El frontend existente sigue funcionando. Opcionalmente puede enviar:
```http
PUT /activities/update/42
Authorization: Bearer <access-token>
Content-Type: application/json
X-Audit-Reason: Correccion de horas
{"amount":150}
```
El motivo admite hasta 500 unidades UTF-16, sin caracteres de control ni encabezados repetidos. CORS permite este encabezado.
No modifica los cuerpos ni las respuestas de las operaciones existentes.
El actor procede de la identidad validada; el motivo nunca permite seleccionar otro usuario.
En recuperación de contraseña, el actor representa la cuenta cuyo token de recuperación ha sido validado, y no una sesión iniciada.
El identificador de petición se toma del encabezado de respuesta validado/generado por los filtros existentes. Auth utiliza su RequestMetadata para vincularlo también a sus eventos de seguridad; no garantiza por sí solo que dos peticiones sean la misma operación.
## Acciones y campos
| Servicio | Acciones |
|---|---|
| cases | `case.create`, `case.update`, `case.disable`, `case.assign`, `case.unassign`. |
| activities | `activity.create`, `activity.update`, `activity.disable`, `activity.payment_reconciled`, `payment.create`, `payment.disable`. |
| clients | `client.create`, `client.update`, `client.disable`. |
| users | `user.create`, `user.update`, `user.disable`, `user.delete`, `user.password_changed`. |
| specializations | `specialization.create`, `specialization.update`, `specialization.delete`. |
| auth | `user.password_changed`, `user.password_reset`. Mantiene además su auditoría de seguridad existente. |
| reporting | Consulta el historial; las lecturas y exportaciones no añaden eventos. |
La instrumentación cubre las operaciones que ya existen. No añade rutas de creación de créditos o gastos que el servicio no ofrezca.
Las ediciones y desactivaciones de los movimientos existentes registran su tipo y campos permitidos.
Listas permitidas:
- Casos: name, description, id_client, id_status, id_created.
- Asignaciones: id_user, id_case.
- Actividades y abonos: description, hours, rate, amount, payment, id_case, id_category, id_paytype, id_status, id_created.
- Clientes: identdocument, businessname, description, id_recomended, id_documenttype, id_status.
- Usuarios: name, lastname, email, rate, acronym, id_specialization, id_rol, id_status.
- Especializaciones: name.
Las actualizaciones incluyen solo campos modificados; `null` se conserva como valor explícito. Los números se comparan por su valor, sin generar eventos por diferencias de escala.
En creación, `before={}`; en eliminación física, `after={}`. No se añaden eventos por una edición que solo altere la fecha técnica de actualización.
Los cambios de contraseña se representan mediante su acción, con ambos objetos vacíos. Nunca se guardan contraseñas, hashes ni tokens.
El nombre del actor conserva el valor que tenía al realizar la operación, aunque después cambie su nombre o se elimine su cuenta.
## Atomicidad y pagos
Cada servicio escribe en `business_audit_events` dentro de la misma transacción que modifica los datos.
Se capturan instantáneas después de adquirir los bloqueos de la entidad y antes/después de persistir el cambio.
Si falla una modificación o la escritura de un evento, se revierte todo. Una excepción de auditoría no se ignora ni se reintenta fuera de la transacción.
Una operación obtiene un UUID y lo propaga explícitamente a sus efectos. Ejemplo: crear un abono genera `payment.create` y un `activity.payment_reconciled` por cada actividad cuyo estado cambie.
Retirar ese abono puede producir nuevos cambios, agrupados con otro UUID.
Una repetición idempotente de un abono ya confirmado no añade eventos.
Las asignaciones masivas generan eventos por cada relación añadida realmente; desactivar un caso registra también las relaciones retiradas.
No se cambian la política FIFO, los tipos de movimientos ni las tarifas históricas.
## Estructura y límites
Contrato de evento versión 1: identidad incremental, fecha `TIMESTAMPTZ`, servicio/acción/entidad, actor y nombre, caso opcional, before/after JSONB, motivo opcional, UUID de operación e identificador de petición opcional.
Las referencias históricas no tienen claves foráneas: eliminar datos operativos no borra ni invalida los eventos.
Se indexa por entidad, caso, actor, fecha y operación.
El componente `audit/BusinessAudit` exige una transacción activa. Cada servicio mantiene su copia del contrato para conservar los builds independientes.
`audit/AuditReasonValidation` valida el encabezado en MVC. Reporting publica la consulta mediante `audit/AuditController`.
La aplicación no ofrece edición ni borrado del historial. La tabla no tiene una protección criptográfica ni impide cambios a un administrador de PostgreSQL.
En despliegue, limitar los permisos de las cuentas de servicio a lo necesario y restringir el acceso directo.
Los valores históricos pueden contener información personal: el acceso es solo administrativo y la política de conservación debe contemplarlos.
## Verificación
Las pruebas de integración usan esquemas desechables en PostgreSQL, mediante Testcontainers o `TEST_DB_URL`, `TEST_DB_USER` y `TEST_DB_PASSWORD`.
Ejecutar `mvn verify` con JDK 25 en cada servicio.
Cubren rollback de datos y eventos, reconciliación e idempotencia, asignaciones, concurrencia, eliminaciones, exclusión de secretos, motivos opcionales, permisos, filtros, cursores, comprobación de arranque y ambas rutas de migración.
+22
View File
@@ -0,0 +1,22 @@
CREATE TABLE business_audit_events (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
service VARCHAR(40) NOT NULL,
action VARCHAR(80) NOT NULL,
entity_type VARCHAR(40) NOT NULL,
entity_id BIGINT NOT NULL,
actor_id BIGINT NOT NULL,
actor_name VARCHAR(600) NOT NULL,
case_id BIGINT,
before_values JSONB NOT NULL,
after_values JSONB NOT NULL,
reason VARCHAR(500),
operation_id UUID NOT NULL,
request_id VARCHAR(128),
format_version INTEGER NOT NULL DEFAULT 1 CHECK (format_version=1)
);
CREATE INDEX business_audit_entity_idx ON business_audit_events(entity_type,entity_id,id DESC);
CREATE INDEX business_audit_case_idx ON business_audit_events(case_id,id DESC);
CREATE INDEX business_audit_actor_idx ON business_audit_events(actor_id,id DESC);
CREATE INDEX business_audit_date_idx ON business_audit_events(occurred_at,id DESC);
CREATE INDEX business_audit_operation_idx ON business_audit_events(operation_id,id);
@@ -0,0 +1,23 @@
package com.aellis.auth.audit;
import com.aellis.auth.api.AuthException;
import jakarta.servlet.http.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class AuditReasonValidation implements WebMvcConfigurer {
@Override public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) {
var headers=request.getHeaders("X-Audit-Reason");
if(!headers.hasMoreElements()) return true;
String reason=headers.nextElement();
if(headers.hasMoreElements() || reason.length()>500 || reason.codePoints().anyMatch(Character::isISOControl))
throw new AuthException(400,"X-Audit-Reason debe tener como maximo 500 caracteres y no contener caracteres de control.");
return true;
}
});
}
}
@@ -0,0 +1,112 @@
package com.aellis.auth.audit;
import java.math.BigDecimal;
import java.util.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.context.request.*;
import tools.jackson.databind.json.JsonMapper;
/** Contract v1: allowlisted persisted values, atomic with the business transaction. */
@Component
public class BusinessAudit implements ApplicationRunner {
public record Context(long actorId, String actorName, UUID operationId, String requestId, String reason) {}
private static final Map<String,List<String>> FIELDS = Map.of(
"cases", List.of("name","description","id_client","id_status","id_created"),
"activities", List.of("description","hours","rate","amount","payment","id_case","id_category","id_paytype","id_status","id_created"),
"client", List.of("identdocument","businessname","description","id_recomended","id_documenttype","id_status"),
"users", List.of("name","lastname","email","rate","acronym","id_specialization","id_rol","id_status"),
"specialization", List.of("name"));
private final JdbcClient jdbc;
private final JsonMapper json;
public BusinessAudit(JdbcClient jdbc, JsonMapper json) { this.jdbc=jdbc; this.json=json; }
@Override public void run(ApplicationArguments args) {
try {
jdbc.sql("SELECT id,occurred_at,service,action,entity_type,entity_id,actor_id,actor_name,case_id,before_values,after_values,reason,operation_id,request_id,format_version FROM business_audit_events WHERE FALSE").query().listOfRows();
} catch (RuntimeException e) { throw new IllegalStateException("Falta el esquema de historial de negocio. Aplica business-audit-schema.sql o la migracion de Auth antes de arrancar.", e); }
}
public Context context() {
var authentication=SecurityContextHolder.getContext().getAuthentication();
if(authentication==null || !(authentication.getPrincipal() instanceof Jwt jwt))
throw new IllegalStateException("Business audit requires an authenticated actor");
return context(Long.parseLong(jwt.getClaimAsString("id")));
}
public Context context(long actor) {
requireTransaction();
String name=jdbc.sql("SELECT concat_ws(' ',to_jsonb(u)->>'name',to_jsonb(u)->>'lastname') FROM users u WHERE id=:id").param("id",actor).query(String.class).optional().orElse("Usuario "+actor);
if(name.isBlank()) name="Usuario "+actor;
String requestId=null, reason=null;
if(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) {
HttpServletRequest request=attributes.getRequest();
requestId=attributes.getResponse()==null?null:attributes.getResponse().getHeader("X-Request-Id");
reason=request.getHeader("X-Audit-Reason");
}
return new Context(actor,name,UUID.randomUUID(),requestId,reason);
}
/** Preserve the caller's validated metadata for non-HTTP invocations too. */
public Context context(long actor,String requestId) {
var context=context(actor);
String effective=context.requestId()!=null?context.requestId():requestId;
if(effective!=null && !effective.matches("[A-Za-z0-9._:-]{1,128}"))
throw new IllegalArgumentException("Invalid audit request identifier");
return new Context(context.actorId(),context.actorName(),context.operationId(),effective,context.reason());
}
@SuppressWarnings("unchecked")
public Map<String,Object> snapshot(String table,long id) {
requireTransaction();
var fields=FIELDS.get(table);
if(fields==null) throw new IllegalArgumentException("Unknown audited table");
String projection=String.join(",",fields.stream().map(field->"'"+field+"',to_jsonb(t)->'"+field+"'").toList());
return jdbc.sql("SELECT jsonb_build_object("+projection+")::text FROM "+table+" t WHERE id=:id")
.param("id",id).query((rs,row)->(Map<String,Object>)json.readValue(rs.getString(1),Map.class)).optional()
.orElseThrow(()->new IllegalStateException("Missing audited entity"));
}
public void change(Context context,String action,String type,long id,Integer caseId,Map<String,Object> before,Map<String,Object> after) {
requireTransaction();
List<String> allowed=FIELDS.get(switch(type) {
case "case" -> "cases"; case "activity","payment" -> "activities"; case "client" -> "client";
case "user" -> "users"; case "specialization" -> "specialization";
case "assignment" -> ""; default -> throw new IllegalArgumentException("Unknown audited entity type");
});
if(type.equals("assignment")) allowed=List.of("id_user","id_case");
if(allowed==null || !allowed.containsAll(before.keySet()) || !allowed.containsAll(after.keySet()))
throw new IllegalArgumentException("Disallowed audit fields");
var oldValues=new LinkedHashMap<String,Object>();
var newValues=new LinkedHashMap<String,Object>();
var keys=new LinkedHashSet<>(before.keySet()); keys.addAll(after.keySet());
for(String key:keys) {
if(before.containsKey(key)==after.containsKey(key) && equal(before.get(key),after.get(key))) continue;
if(before.containsKey(key)) oldValues.put(key,before.get(key));
if(after.containsKey(key)) newValues.put(key,after.get(key));
}
if(oldValues.isEmpty() && newValues.isEmpty()) return;
insert(context,action,type,id,caseId,oldValues,newValues);
}
public void passwordChanged(Context context,long id,String action) {
insert(context,action,"user",id,null,Map.of(),Map.of());
}
private static boolean equal(Object first,Object second) {
if(first instanceof Number && second instanceof Number)
return new BigDecimal(first.toString()).compareTo(new BigDecimal(second.toString()))==0;
return Objects.equals(first,second);
}
private void insert(Context context,String action,String type,long id,Integer caseId,Map<String,Object> before,Map<String,Object> after) {
requireTransaction();
jdbc.sql("""
INSERT INTO business_audit_events(service,action,entity_type,entity_id,actor_id,actor_name,case_id,before_values,after_values,reason,operation_id,request_id)
VALUES(:service,:action,:type,:id,:actor,:name,:caseId,CAST(:before AS JSONB),CAST(:after AS JSONB),:reason,:operation,:request)
""").param("service","auth").param("action",action).param("type",type).param("id",id)
.param("actor",context.actorId()).param("name",context.actorName()).param("caseId",caseId)
.param("before",json.writeValueAsString(before)).param("after",json.writeValueAsString(after))
.param("reason",context.reason()).param("operation",context.operationId()).param("request",context.requestId()).update();
}
private static void requireTransaction() {
if(!TransactionSynchronizationManager.isActualTransactionActive()) throw new IllegalStateException("Business audit requires an active transaction");
}
}
@@ -126,7 +126,7 @@ public class SecurityConfig {
var config = new CorsConfiguration(); var config = new CorsConfiguration();
config.setAllowedOrigins(props.allowedOrigins()); config.setAllowedOrigins(props.allowedOrigins());
config.setAllowedMethods(List.of("GET", "POST", "OPTIONS")); config.setAllowedMethods(List.of("GET", "POST", "OPTIONS"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type")); config.setAllowedHeaders(List.of("X-Audit-Reason", "Authorization", "Content-Type"));
config.setAllowCredentials(false); config.setAllowCredentials(false);
var source = new UrlBasedCorsConfigurationSource(); var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config); source.registerCorsConfiguration("/**", config);
@@ -2,6 +2,7 @@ package com.aellis.auth.service;
import com.aellis.auth.api.AuthDtos.*; import com.aellis.auth.api.AuthDtos.*;
import com.aellis.auth.api.AuthException; import com.aellis.auth.api.AuthException;
import com.aellis.auth.audit.BusinessAudit;
import com.aellis.auth.config.*; import com.aellis.auth.config.*;
import com.aellis.auth.domain.UserAccount; import com.aellis.auth.domain.UserAccount;
import com.aellis.auth.repository.UserRepository; import com.aellis.auth.repository.UserRepository;
@@ -30,6 +31,7 @@ public class AuthService {
private final AuthPolicyProperties policy; private final AuthPolicyProperties policy;
private final Clock clock; private final Clock clock;
private final AuditService audit; private final AuditService audit;
private final BusinessAudit history;
private final LoginAttemptService attempts; private final LoginAttemptService attempts;
private final UserRepository users; private final UserRepository users;
private final SecureRandom random = new SecureRandom(); private final SecureRandom random = new SecureRandom();
@@ -37,10 +39,10 @@ public class AuthService {
public AuthService(JdbcClient jdbc, PasswordEncoder passwords, JwtEncoder encoder, AuthProperties props, public AuthService(JdbcClient jdbc, PasswordEncoder passwords, JwtEncoder encoder, AuthProperties props,
AuthPolicyProperties policy, Clock clock, AuditService audit, LoginAttemptService attempts, AuthPolicyProperties policy, Clock clock, AuditService audit, LoginAttemptService attempts,
UserRepository users) { UserRepository users, BusinessAudit history) {
this.jdbc = jdbc; this.passwords = passwords; this.encoder = encoder; this.props = props; 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.policy = policy; this.clock = clock; this.audit = audit; this.attempts = attempts;
this.users = users; this.users = users; this.history=history;
dummyHash = passwords.encode(UUID.randomUUID().toString()); dummyHash = passwords.encode(UUID.randomUUID().toString());
} }
@@ -165,9 +167,11 @@ public class AuthService {
if (passwords.matches(request.password(), user.passwordHash())) { if (passwords.matches(request.password(), user.passwordHash())) {
throw new AuthException(400, "La nueva contraseña debe ser diferente."); throw new AuthException(400, "La nueva contraseña debe ser diferente.");
} }
var context=history.context(userId,metadata.requestId());
users.updatePasswordAndClearReset(userId, passwords.encode(request.password())); users.updatePasswordAndClearReset(userId, passwords.encode(request.password()));
invalidateCredentials(userId, email); invalidateCredentials(userId, email);
audit.record("password_changed", userId, null, metadata); audit.record("password_changed", userId, null, metadata);
history.passwordChanged(context,userId,"user.password_changed");
} }
// El llamador ya tiene bloqueados el intento y el usuario, en ese orden. // El llamador ya tiene bloqueados el intento y el usuario, en ese orden.
@@ -2,6 +2,7 @@ package com.aellis.auth.service;
import com.aellis.auth.api.AuthDtos.ResetPasswordRequest; import com.aellis.auth.api.AuthDtos.ResetPasswordRequest;
import com.aellis.auth.api.AuthException; import com.aellis.auth.api.AuthException;
import com.aellis.auth.audit.BusinessAudit;
import com.aellis.auth.config.RecoveryProperties; import com.aellis.auth.config.RecoveryProperties;
import com.aellis.auth.config.AuthPolicyProperties; import com.aellis.auth.config.AuthPolicyProperties;
import java.time.Clock; import java.time.Clock;
@@ -18,15 +19,16 @@ public class PasswordRecoveryService {
private final RecoveryProperties properties; private final RecoveryProperties properties;
private final Clock clock; private final Clock clock;
private final AuditService audit; private final AuditService audit;
private final BusinessAudit history;
private final LoginAttemptService attempts; private final LoginAttemptService attempts;
private final AuthService auth; private final AuthService auth;
private final AuthPolicyProperties policy; private final AuthPolicyProperties policy;
public PasswordRecoveryService(JdbcClient jdbc, PasswordEncoder passwords, RecoveryProperties properties, public PasswordRecoveryService(JdbcClient jdbc, PasswordEncoder passwords, RecoveryProperties properties,
Clock clock, AuditService audit, LoginAttemptService attempts, AuthService auth, Clock clock, AuditService audit, LoginAttemptService attempts, AuthService auth,
AuthPolicyProperties policy) { AuthPolicyProperties policy, BusinessAudit history) {
this.jdbc = jdbc; this.passwords = passwords; this.properties = properties; this.jdbc = jdbc; this.passwords = passwords; this.properties = properties;
this.clock = clock; this.audit = audit; this.attempts = attempts; this.auth = auth; this.clock = clock; this.audit = audit; this.attempts = attempts; this.auth = auth;
this.policy = policy; this.policy = policy; this.history=history;
} }
@Transactional @Transactional
public void request(String email, RequestMetadata metadata) { public void request(String email, RequestMetadata metadata) {
@@ -65,11 +67,13 @@ public class PasswordRecoveryService {
if (passwords.matches(request.password(), user.passwordHash())) { if (passwords.matches(request.password(), user.passwordHash())) {
throw new AuthException(400, "La nueva contraseña debe ser diferente."); throw new AuthException(400, "La nueva contraseña debe ser diferente.");
} }
var context=history.context(user.id(),metadata.requestId());
jdbc.sql(""" jdbc.sql("""
UPDATE users SET password=:password,reset_token_hash=NULL,reset_token_expires_at=NULL,updated=CURRENT_TIMESTAMP WHERE id=:id 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(); """).param("password", passwords.encode(request.password())).param("id", user.id()).update();
auth.invalidateCredentials(user.id(), AuthService.normalize(user.email())); auth.invalidateCredentials(user.id(), AuthService.normalize(user.email()));
audit.record("password_reset_completed", user.id(), null, metadata); audit.record("password_reset_completed", user.id(), null, metadata);
history.passwordChanged(context,user.id(),"user.password_reset");
} }
private void enabled() { private void enabled() {
if (!properties.enabled()) throw new AuthException(503, "Recuperación por correo no configurada"); if (!properties.enabled()) throw new AuthException(503, "Recuperación por correo no configurada");
@@ -0,0 +1,22 @@
CREATE TABLE business_audit_events (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
service VARCHAR(40) NOT NULL,
action VARCHAR(80) NOT NULL,
entity_type VARCHAR(40) NOT NULL,
entity_id BIGINT NOT NULL,
actor_id BIGINT NOT NULL,
actor_name VARCHAR(600) NOT NULL,
case_id BIGINT,
before_values JSONB NOT NULL,
after_values JSONB NOT NULL,
reason VARCHAR(500),
operation_id UUID NOT NULL,
request_id VARCHAR(128),
format_version INTEGER NOT NULL DEFAULT 1 CHECK (format_version=1)
);
CREATE INDEX business_audit_entity_idx ON business_audit_events(entity_type,entity_id,id DESC);
CREATE INDEX business_audit_case_idx ON business_audit_events(case_id,id DESC);
CREATE INDEX business_audit_actor_idx ON business_audit_events(actor_id,id DESC);
CREATE INDEX business_audit_date_idx ON business_audit_events(occurred_at,id DESC);
CREATE INDEX business_audit_operation_idx ON business_audit_events(operation_id,id);
@@ -0,0 +1,22 @@
CREATE TABLE business_audit_events (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
service VARCHAR(40) NOT NULL,
action VARCHAR(80) NOT NULL,
entity_type VARCHAR(40) NOT NULL,
entity_id BIGINT NOT NULL,
actor_id BIGINT NOT NULL,
actor_name VARCHAR(600) NOT NULL,
case_id BIGINT,
before_values JSONB NOT NULL,
after_values JSONB NOT NULL,
reason VARCHAR(500),
operation_id UUID NOT NULL,
request_id VARCHAR(128),
format_version INTEGER NOT NULL DEFAULT 1 CHECK (format_version=1)
);
CREATE INDEX business_audit_entity_idx ON business_audit_events(entity_type,entity_id,id DESC);
CREATE INDEX business_audit_case_idx ON business_audit_events(case_id,id DESC);
CREATE INDEX business_audit_actor_idx ON business_audit_events(actor_id,id DESC);
CREATE INDEX business_audit_date_idx ON business_audit_events(occurred_at,id DESC);
CREATE INDEX business_audit_operation_idx ON business_audit_events(operation_id,id);
+24 -1
View File
@@ -87,7 +87,7 @@ class AuthFlowIT {
static final RequestMetadata META = new RequestMetadata("127.0.0.1", "integration-test", "request-test"); static final RequestMetadata META = new RequestMetadata("127.0.0.1", "integration-test", "request-test");
@BeforeEach void clear() { @BeforeEach void clear() {
jdbc.sql("TRUNCATE users,auth_login_attempt,audit_events CASCADE").update(); jdbc.sql("TRUNCATE users,auth_login_attempt,audit_events,business_audit_events CASCADE").update();
mail.token = null; mail.recipient = null; mail.failing = false; mail.token = null; mail.recipient = null; mail.failing = false;
} }
long createUser(String hash) { long createUser(String hash) {
@@ -329,4 +329,27 @@ class AuthFlowIT {
if (token != null) request.header("Authorization", "Bearer " + token); if (token != null) request.header("Authorization", "Bearer " + token);
return http.send(request.POST(HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString()); return http.send(request.POST(HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString());
} }
@Test void completedPasswordOperationsCreateOnlySecretFreeBusinessMarkers() {
var tokens=createAndLogin();
auth.changePassword(42,new PasswordRequest(PASSWORD,NEXT_PASSWORD),META);
recovery.request(EMAIL,META); assertThat(delivery.deliverNext()).isTrue();
recovery.reset(new ResetPasswordRequest(null,mail.token,"A-third-strong-password-2026"),META);
var actions=jdbc.sql("SELECT action FROM business_audit_events ORDER BY id").query(String.class).list();
assertThat(actions).containsExactly("user.password_changed","user.password_reset");
assertThat(jdbc.sql("SELECT DISTINCT request_id FROM business_audit_events").query(String.class).single()).isEqualTo(META.requestId());
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events WHERE actor_id=42 AND before_values='{}'::jsonb AND after_values='{}'::jsonb").query(Integer.class).single()).isEqualTo(2);
String values=String.join("",jdbc.sql("SELECT before_values::text||after_values::text FROM business_audit_events").query(String.class).list());
assertThat(values).doesNotContain(PASSWORD,NEXT_PASSWORD,mail.token,"argon2");
}
@Test void businessHistoryFailureRollsBackPasswordAndSessionRevocation() {
var tokens=createAndLogin();
jdbc.sql("ALTER TABLE business_audit_events ADD CONSTRAINT reject_audit CHECK(action='never')").update();
try {
assertThatThrownBy(()->auth.changePassword(42,new PasswordRequest(PASSWORD,NEXT_PASSWORD),META)).isInstanceOf(RuntimeException.class);
assertThat(passwords.matches(PASSWORD,jdbc.sql("SELECT password FROM users WHERE id=42").query(String.class).single())).isTrue();
assertThat(decoder.decode(tokens.accessToken()).getSubject()).isEqualTo("42");
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events").query(Integer.class).single()).isZero();
} finally { jdbc.sql("ALTER TABLE business_audit_events DROP CONSTRAINT reject_audit").update(); }
}
} }
@@ -142,4 +142,24 @@ class SchemaMigrationIT {
assertThat(jdbc.sql("SELECT count(*) FROM rol").query(Integer.class).single()).isEqualTo(2); 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(); assertThat(jdbc.sql("SELECT count(*) FROM users").query(Integer.class).single()).isZero();
} }
@ParameterizedTest @ValueSource(booleans={false,true})
void auditMigrationExistsForBothInstallationPaths(boolean node) throws Exception {
if(node) { sequelizeFixture(); nodeMigration().migrate(); }
else Flyway.configure().dataSource(source).schemas(schema).defaultSchema(schema).locations("classpath:db/migration").load().migrate();
assertThat(jdbc.sql("SELECT count(*) FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='business_audit_events'").query(Integer.class).single()).isEqualTo(15);
assertThat(jdbc.sql("SELECT count(*) FROM pg_indexes WHERE schemaname=current_schema() AND tablename='business_audit_events'").query(Integer.class).single()).isEqualTo(6);
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events").query(Integer.class).single()).isZero();
if(node) assertThat(nodeMigration().migrate().migrationsExecuted).isZero();
}
@Test void manualAuditScriptMatchesBothFlywayScripts() throws Exception {
String standard=new ClassPathResource("db/migration/V4__business_audit.sql").getContentAsString(java.nio.charset.StandardCharsets.UTF_8);
String node=new ClassPathResource("db/node-migration/V2__business_audit.sql").getContentAsString(java.nio.charset.StandardCharsets.UTF_8);
String manual=java.nio.file.Files.readString(java.nio.file.Path.of("scripts/business-audit-schema.sql"));
assertThat(node).isEqualTo(standard); assertThat(manual).isEqualTo(standard);
try(var connection=source.getConnection()) {
ScriptUtils.executeSqlScript(connection,new org.springframework.core.io.FileSystemResource("scripts/business-audit-schema.sql"));
}
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events").query(Integer.class).single()).isZero();
}
} }