@@ -0,0 +1,6 @@
|
|||||||
|
.git
|
||||||
|
.env
|
||||||
|
.secrets
|
||||||
|
target
|
||||||
|
.idea
|
||||||
|
.tools
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
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,29 @@
|
|||||||
|
# La misma base que genesis_authv2. Este servicio NO crea ni modifica el esquema.
|
||||||
|
SERVER_PORT=8085
|
||||||
|
DB_URL=jdbc:postgresql://localhost:5432/genesis_auth
|
||||||
|
DB_USER=genesis
|
||||||
|
DB_PASSWORD=replace-with-your-postgresql-password
|
||||||
|
|
||||||
|
# Clave PUBLICA del auth Java. Nunca copies su clave privada a este servicio.
|
||||||
|
JWT_ALGORITHM=RS256
|
||||||
|
JWT_PUBLIC_KEY=file:.secrets/public.pem
|
||||||
|
JWT_ISSUER=http://localhost:8080
|
||||||
|
JWT_AUDIENCE=genesis-api
|
||||||
|
JWT_CHECK_SESSION=true
|
||||||
|
JWT_MAX_AGE=15m
|
||||||
|
|
||||||
|
# Solo para transición con auth Node antiguo: JWT_ALGORITHM=HS256, TOKEN_SECRET y JWT_CHECK_SESSION=false.
|
||||||
|
TOKEN_SECRET=
|
||||||
|
CORS_ALLOWED_ORIGINS=http://localhost:3000
|
||||||
|
|
||||||
|
# Redis es opcional; sin URL se utiliza el límite local por IP.
|
||||||
|
REDIS_URL=
|
||||||
|
RATE_LIMIT_MAX=300
|
||||||
|
RATE_LIMIT_WINDOW_MS=60000
|
||||||
|
RATE_LIMIT_MEMORY_MAX_KEYS=10000
|
||||||
|
RATE_LIMIT_REDIS_BACKOFF_MS=60000
|
||||||
|
RATE_LIMIT_PREFIX=genesis-client:rate
|
||||||
|
REQUEST_LOG_ENABLED=true
|
||||||
|
|
||||||
|
# Solo al usar Docker. localhost dentro del contenedor no es tu ordenador.
|
||||||
|
DOCKER_DB_URL=jdbc:postgresql://host.docker.internal:5432/genesis_auth
|
||||||
@@ -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
|
||||||
+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-client-0.0.1-SNAPSHOT.jar app.jar
|
||||||
|
USER app
|
||||||
|
EXPOSE 8085
|
||||||
|
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# Genesis Client Service — Java 25
|
||||||
|
|
||||||
|
Migración de `genesis_clientService` a Java 25 y Spring Boot. Comparte PostgreSQL y autenticación con los demás servicios Java.
|
||||||
|
|
||||||
|
## Arranque
|
||||||
|
|
||||||
|
Necesitas JDK 25 y la base existente del Node y del auth. Desde `genesis_clientv2`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
El script carga `.env` y arranca en **http://localhost:8085**. La primera ejecución necesita internet para descargar Maven y dependencias. Abre **http://localhost:8085/health**: devuelve `{"ok":true}`. `/actuator/health` comprueba también PostgreSQL. Detén el proceso con `Ctrl+C`.
|
||||||
|
|
||||||
|
El `.env` local se ha preparado con la conexión, issuer, audiencia y CORS del auth. Revisa el entorno de destino. Para otra instalación, copia `.env.example` como `.env` y completa los valores. Si arrancas directamente desde el IDE o con `java -jar`, configura allí las variables: Spring no carga este `.env` por sí solo.
|
||||||
|
|
||||||
|
No necesitas añadir columnas ni ejecutar un script de preparación. Se utilizan las tablas existentes `client`, `documenttype`, `users`, `status`, `cases`, `user_case`, `rol` y `auth_session`. El arranque comprueba las columnas necesarias y no modifica el esquema. La base debe contener el dominio del Node; el esquema inicial del auth por sí solo no incluye todas estas tablas. El SQL en `src/test/resources` es exclusivo para pruebas. No se ha modificado la base real.
|
||||||
|
|
||||||
|
## Autenticación
|
||||||
|
|
||||||
|
Obtén un access token del auth y envíalo así:
|
||||||
|
|
||||||
|
```http
|
||||||
|
Authorization: Bearer <access-token-del-auth>
|
||||||
|
```
|
||||||
|
|
||||||
|
El modo predeterminado es RS256 con la clave pública del auth en `.secrets/public.pem`; se ha copiado la actual. Nunca necesita la clave privada. Si rotas las claves, actualiza esta copia. `DB_URL`, `DB_USER`, `DB_PASSWORD`, `JWT_ISSUER` y `JWT_AUDIENCE` deben coincidir con el entorno del auth. Se validan la sesión `sid`, su vencimiento y revocación, además del usuario y su rol actuales. El refresh token se utiliza solo con el auth.
|
||||||
|
|
||||||
|
Se incluye el modo de transición explícito de los otros servicios: `JWT_ALGORITHM=HS256`, el mismo `TOKEN_SECRET` de al menos 32 bytes y `JWT_CHECK_SESSION=false` si el emisor no genera `sid`. Exige issuer, audiencia, `id`, `rol`, `iat` y `exp`; pierde la comprobación de revocación por sesión. Las pruebas usan RS256.
|
||||||
|
|
||||||
|
## Rutas y permisos
|
||||||
|
|
||||||
|
Se conservan las ocho rutas y el nombre original `recomended`. Las respuestas correctas usan HTTP 200 y `{ "data": ..., "status": "success" }`. Los errores incluyen `data.message` y `status: "error"`.
|
||||||
|
|
||||||
|
| Método | Ruta | Permiso y resultado |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| POST | `/clients/create` | admin; mensaje e `id_client` |
|
||||||
|
| PUT | `/clients/update/{id}` | admin; edición parcial |
|
||||||
|
| PATCH | `/clients/disable/{id}` | admin; baja lógica |
|
||||||
|
| GET | `/clients/all` | clientes activos visibles; `data.clients` |
|
||||||
|
| GET | `/clients/get/{id}` | cliente visible; `data.client` |
|
||||||
|
| GET | `/clients/recomended/{id}` | activos visibles recomendados por ese usuario |
|
||||||
|
| GET | `/clients/documenttypes` | admin o user; `data.documentTypes` |
|
||||||
|
| GET | `/clients/all/notfilter` | todos los estados, manteniendo el filtro de acceso |
|
||||||
|
|
||||||
|
**Cambio solicitado respecto al Node:** admin puede consultar todos los clientes; user solo puede consultar clientes vinculados a al menos un caso asignado mediante `user_case`. Este filtro se aplica en todas las lecturas de clientes, incluso el detalle, la búsqueda por recomendador y el listado sin filtro. Ser recomendador no concede acceso por sí solo. Un cliente inexistente o no autorizado devuelve 404.
|
||||||
|
|
||||||
|
Los casos asignados no se filtran adicionalmente por su estado en este servicio; la baja de un caso en `genesis_casev2` elimina sus asignaciones. Si varias asignaciones apuntan al mismo cliente, no se duplica la respuesta. Retirar la última asignación revoca ese acceso en la siguiente petición, sin cerrar la sesión. El catálogo de tipos de documento sigue disponible para cualquier admin o user autenticado.
|
||||||
|
|
||||||
|
## Datos y comportamiento
|
||||||
|
|
||||||
|
Crear requiere `identdocument`, `businessname` e `id_documenttype`. Admite `description` e `id_recomended` opcionales o NULL. Se recortan los espacios exteriores de los textos. El estado inicial es 3 y se establece `created`.
|
||||||
|
|
||||||
|
Actualizar acepta los mismos campos parcialmente; un campo omitido conserva su valor y un NULL explícito limpia descripción o recomendador. Se establece `updated`. No se permite enviar campos adicionales, `id_status`, fechas ni propiedades de usuarios. El tipo de documento y el recomendador, cuando se indica, deben existir. Se permite conservar o elegir un recomendador inactivo como referencia histórica, como en Node; eso no le permite autenticarse.
|
||||||
|
|
||||||
|
Los IDs y `identdocument` son enteros positivos de hasta 2147483647, compatibles con las columnas INTEGER existentes. Se acepta su representación numérica como cadena. `businessname` admite entre 1 y 255 caracteres; descripción entre 1 y 1000 o NULL. Si la columna real de descripción sigue siendo VARCHAR(255), se respeta ese límite y se devuelve 400 al superarlo. No se amplía automáticamente la columna. Las restricciones de unicidad existentes se respetan y sus conflictos devuelven 409, sin revelar SQL ni nombres internos de restricciones.
|
||||||
|
|
||||||
|
Las listas conservan `recommended`, `statusName` y `documentTypeName`. El detalle conserva `id_recomended`, `id_documenttype` y `documentType` con id y nombre. El recomendador solo expone nombre, apellido y acrónimo, nunca contraseñas o tokens. Los listados se ordenan por `businessname` y, en empates, por id.
|
||||||
|
|
||||||
|
Desactivar establece **id_status=8** y actualiza la fecha. No borra el cliente ni cambia sus casos, asignaciones, actividades, abonos o tarifas históricas. Desaparece de `/all` y `/recomended`, pero sigue disponible mediante detalle y `/all/notfilter` para quien conserve permiso. No se añade una ruta de reactivación que no existía en el Node.
|
||||||
|
|
||||||
|
## Organización y seguridad
|
||||||
|
|
||||||
|
`api/ClientController.java` recibe las rutas; `ClientDtos.java` valida entradas y define respuestas; `service/ClientService.java` aplica permisos y transacciones; `repository/ClientRepository.java` contiene SQL. `config/` contiene JWT, CORS, límites y configuración. `ClientsApplication.java` arranca y verifica tablas. `ApiExceptionHandler.java` transforma errores a JSON.
|
||||||
|
|
||||||
|
Incluye consultas parametrizadas, CORS con orígenes explícitos, cabeceras de seguridad, request ID y cuerpo máximo de 1 MiB. El límite predeterminado es 300 peticiones por IP cada 60 segundos. Redis es opcional para compartirlo entre instancias; si falla, se usa memoria local. No se confía automáticamente en cabeceras de proxy. Los logs de aplicación no incluyen cuerpos ni tokens; evita DEBUG en producción.
|
||||||
|
|
||||||
|
## Pruebas y Docker
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1 -Verify
|
||||||
|
```
|
||||||
|
|
||||||
|
Por defecto las pruebas necesitan Docker para levantar PostgreSQL 18 con Testcontainers. Como alternativa define `TEST_DB_URL`, `TEST_DB_USER` y `TEST_DB_PASSWORD` de una base de pruebas: se crea y elimina un esquema temporal exclusivo. No uses producción.
|
||||||
|
|
||||||
|
Han pasado **16 pruebas de integración** con Java 25 y PostgreSQL aislado: las ocho rutas, permisos por asignación, revocación de ese acceso, DTOs, catálogos, campos NULL, validación, límites de columnas, conflictos, conservación de casos y pagos, JWT, sesiones, CORS y límite del cuerpo. No se han usado datos reales ni probado un servidor Redis real.
|
||||||
|
|
||||||
|
Se incluyen Maven Wrapper, CI, Dockerfile y Compose. Configura `DOCKER_DB_URL` para acceder a la base desde el contenedor y conserva la clave pública disponible:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker compose up --build -d
|
||||||
|
```
|
||||||
|
|
||||||
|
El contenedor usa un usuario sin privilegios, no levanta otra base ni aplica migraciones. `.env`, `.secrets` y los artefactos locales están excluidos del control de versiones y del contexto de construcción.
|
||||||
|
|
||||||
|
|
||||||
|
## 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](../genesis_authv2/docs/business-audit.md).
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
services:
|
||||||
|
clients:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${SERVER_PORT:-8085}:8085"
|
||||||
|
environment:
|
||||||
|
SERVER_PORT: 8085
|
||||||
|
DB_URL: ${DOCKER_DB_URL:?Define DOCKER_DB_URL para PostgreSQL accesible desde Docker}
|
||||||
|
DB_USER: ${DB_USER:-genesis}
|
||||||
|
DB_PASSWORD: ${DB_PASSWORD:?Define DB_PASSWORD}
|
||||||
|
JWT_ALGORITHM: ${JWT_ALGORITHM:-RS256}
|
||||||
|
JWT_PUBLIC_KEY: file:/run/keys/public.pem
|
||||||
|
TOKEN_SECRET: ${TOKEN_SECRET:-}
|
||||||
|
JWT_ISSUER: ${JWT_ISSUER:-http://localhost:8080}
|
||||||
|
JWT_AUDIENCE: ${JWT_AUDIENCE:-genesis-api}
|
||||||
|
JWT_CHECK_SESSION: ${JWT_CHECK_SESSION:-true}
|
||||||
|
JWT_MAX_AGE: ${JWT_MAX_AGE:-15m}
|
||||||
|
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-http://localhost:3000}
|
||||||
|
REDIS_URL: ${REDIS_URL:-}
|
||||||
|
RATE_LIMIT_MAX: ${RATE_LIMIT_MAX:-300}
|
||||||
|
RATE_LIMIT_WINDOW_MS: ${RATE_LIMIT_WINDOW_MS:-60000}
|
||||||
|
RATE_LIMIT_MEMORY_MAX_KEYS: ${RATE_LIMIT_MEMORY_MAX_KEYS:-10000}
|
||||||
|
RATE_LIMIT_REDIS_BACKOFF_MS: ${RATE_LIMIT_REDIS_BACKOFF_MS:-60000}
|
||||||
|
RATE_LIMIT_PREFIX: ${RATE_LIMIT_PREFIX:-genesis-client:rate}
|
||||||
|
REQUEST_LOG_ENABLED: ${REQUEST_LOG_ENABLED:-true}
|
||||||
|
volumes:
|
||||||
|
- ./.secrets:/run/keys:ro
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp:size=64m
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: [no-new-privileges:true]
|
||||||
|
restart: unless-stopped
|
||||||
@@ -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,27 @@
|
|||||||
|
<?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-client</artifactId><version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>Genesis Client Service</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-jdbc</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-data-redis</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>runtime</scope></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,33 @@
|
|||||||
|
param([switch]$Verify)
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$projectRoot = Split-Path -Parent $PSScriptRoot
|
||||||
|
Set-Location -LiteralPath $projectRoot
|
||||||
|
|
||||||
|
if (Test-Path -LiteralPath '.env') {
|
||||||
|
foreach ($line in [System.IO.File]::ReadAllLines((Join-Path $projectRoot '.env'), [System.Text.Encoding]::UTF8)) {
|
||||||
|
if ($line -match '^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$') {
|
||||||
|
$settingName = $Matches[1]
|
||||||
|
$settingValue = $Matches[2].Trim()
|
||||||
|
if ($settingValue.Length -ge 2) {
|
||||||
|
if (($settingValue.StartsWith('"') -and $settingValue.EndsWith('"')) -or
|
||||||
|
($settingValue.StartsWith("'") -and $settingValue.EndsWith("'"))) {
|
||||||
|
$settingValue = $settingValue.Substring(1, $settingValue.Length - 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[Environment]::SetEnvironmentVariable($settingName, $settingValue, 'Process')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Write-Host 'No existe .env. Se usarán las variables del proceso; consulta .env.example.'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(Get-Command java -ErrorAction SilentlyContinue)) {
|
||||||
|
if ($env:JAVA_HOME -and (Test-Path -LiteralPath (Join-Path $env:JAVA_HOME 'bin/java.exe'))) {
|
||||||
|
$env:PATH = "$env:JAVA_HOME\bin;$env:PATH"
|
||||||
|
} else {
|
||||||
|
throw 'No se encuentra Java. Instala JDK 25 o configura JAVA_HOME.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($Verify) { & (Join-Path $projectRoot 'mvnw.cmd') verify }
|
||||||
|
else { & (Join-Path $projectRoot 'mvnw.cmd') spring-boot:run }
|
||||||
|
exit $LASTEXITCODE
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.aellis.clients;
|
||||||
|
|
||||||
|
import org.springframework.boot.*;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@ConfigurationPropertiesScan
|
||||||
|
public class ClientsApplication {
|
||||||
|
public static void main(String[] args) { SpringApplication.run(ClientsApplication.class,args); }
|
||||||
|
@Bean ApplicationRunner verifyDatabase(JdbcClient jdbc) {
|
||||||
|
return args -> {
|
||||||
|
jdbc.sql("SELECT id,identdocument,businessname,description,created,updated,id_status,id_documenttype,id_recomended FROM client WHERE FALSE").query().listOfRows();
|
||||||
|
jdbc.sql("SELECT id,name,description FROM documenttype WHERE FALSE").query().listOfRows();
|
||||||
|
jdbc.sql("SELECT id,name FROM status WHERE FALSE").query().listOfRows();
|
||||||
|
jdbc.sql("SELECT id,name,lastname,acronym FROM users WHERE FALSE").query().listOfRows();
|
||||||
|
jdbc.sql("SELECT id,id_client FROM cases WHERE FALSE").query().listOfRows();
|
||||||
|
jdbc.sql("SELECT id_case,id_user FROM user_case WHERE FALSE").query().listOfRows();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.aellis.clients.api;
|
||||||
|
|
||||||
|
public class ApiException extends RuntimeException {
|
||||||
|
private final int status;
|
||||||
|
public ApiException(int status, String message) { super(message); this.status = status; }
|
||||||
|
public int status() { return status; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.aellis.clients.api;
|
||||||
|
|
||||||
|
import com.aellis.clients.api.ClientDtos.ApiResponse;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.dao.*;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestControllerAdvice
|
||||||
|
public class ApiExceptionHandler {
|
||||||
|
@ExceptionHandler(ApiException.class) ResponseEntity<?> application(ApiException error) {
|
||||||
|
return ResponseEntity.status(error.status()).body(ApiResponse.fail(error.getMessage()));
|
||||||
|
}
|
||||||
|
@ExceptionHandler(DuplicateKeyException.class) ResponseEntity<?> duplicate() { return ResponseEntity.status(409).body(ApiResponse.fail("Conflict.")); }
|
||||||
|
@ExceptionHandler(DataIntegrityViolationException.class) ResponseEntity<?> constraint(DataIntegrityViolationException error) {
|
||||||
|
for(Throwable cause=error;cause!=null;cause=cause.getCause()) {
|
||||||
|
if(cause instanceof java.sql.SQLException sql && sql.getSQLState()!=null && sql.getSQLState().startsWith("22"))
|
||||||
|
return ResponseEntity.badRequest().body(ApiResponse.fail("Invalid data."));
|
||||||
|
}
|
||||||
|
return ResponseEntity.status(409).body(ApiResponse.fail("La operación entra en conflicto con datos relacionados."));
|
||||||
|
}
|
||||||
|
@ExceptionHandler(HttpMessageNotReadableException.class) ResponseEntity<?> invalid(HttpMessageNotReadableException error) {
|
||||||
|
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
|
||||||
|
if (cause instanceof com.aellis.clients.config.RequestFilter.BodyTooLargeException) return ResponseEntity.status(413).body(ApiResponse.fail("Request body too large."));
|
||||||
|
}
|
||||||
|
return ResponseEntity.badRequest().body(ApiResponse.fail("Invalid request."));
|
||||||
|
}
|
||||||
|
@ExceptionHandler(Exception.class) ResponseEntity<?> unexpected(Exception error) {
|
||||||
|
if (error instanceof org.springframework.web.ErrorResponse response) return ResponseEntity.status(response.getStatusCode())
|
||||||
|
.headers(response.getHeaders()).body(ApiResponse.fail("Invalid request."));
|
||||||
|
LoggerFactory.getLogger(getClass()).error("client_service_error type={}", error.getClass().getSimpleName());
|
||||||
|
return ResponseEntity.internalServerError().body(ApiResponse.fail("Internal server error."));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.aellis.clients.api;
|
||||||
|
|
||||||
|
import com.aellis.clients.api.ClientDtos.*;
|
||||||
|
import com.aellis.clients.service.ClientService;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
|
import org.springframework.security.oauth2.jwt.Jwt;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/clients")
|
||||||
|
public class ClientController {
|
||||||
|
private final ClientService clients;
|
||||||
|
public ClientController(ClientService clients) { this.clients=clients; }
|
||||||
|
@PostMapping("/create") public ApiResponse<?> create(@AuthenticationPrincipal Jwt jwt,@RequestBody Payload body) {
|
||||||
|
int id=clients.create(who(jwt),ClientDtos.parse(body,true)); return ApiResponse.ok(Map.of("message","Cliente registrado exitosamente.","id_client",id));
|
||||||
|
}
|
||||||
|
@PutMapping("/update/{id}") public ApiResponse<Message> update(@AuthenticationPrincipal Jwt jwt,@PathVariable String id,@RequestBody Payload body) {
|
||||||
|
clients.update(who(jwt),ClientDtos.positiveId(id),ClientDtos.parse(body,false)); return message("Cliente editado exitosamente.");
|
||||||
|
}
|
||||||
|
@PatchMapping("/disable/{id}") public ApiResponse<Message> disable(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) {
|
||||||
|
clients.disable(who(jwt),ClientDtos.positiveId(id)); return message("Cliente eliminado exitosamente.");
|
||||||
|
}
|
||||||
|
@GetMapping("/all") public ApiResponse<?> all(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("clients",clients.all(who(jwt),true))); }
|
||||||
|
@GetMapping("/get/{id}") public ApiResponse<?> find(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) {
|
||||||
|
return ApiResponse.ok(Map.of("client",clients.find(who(jwt),ClientDtos.positiveId(id))));
|
||||||
|
}
|
||||||
|
@GetMapping("/recomended/{id}") public ApiResponse<?> recommended(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) {
|
||||||
|
return ApiResponse.ok(Map.of("clients",clients.recommended(who(jwt),ClientDtos.positiveId(id))));
|
||||||
|
}
|
||||||
|
@GetMapping("/documenttypes") public ApiResponse<?> documentTypes() { return ApiResponse.ok(Map.of("documentTypes",clients.documentTypes())); }
|
||||||
|
@GetMapping("/all/notfilter") public ApiResponse<?> allNotFilter(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("clients",clients.all(who(jwt),false))); }
|
||||||
|
private static Requester who(Jwt jwt) { return new Requester(Integer.parseInt(jwt.getClaimAsString("id")),jwt.getClaimAsString("rol")); }
|
||||||
|
private static ApiResponse<Message> message(String text) { return ApiResponse.ok(new Message(text)); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.aellis.clients.api;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
public final class ClientDtos {
|
||||||
|
private ClientDtos() {}
|
||||||
|
public record ApiResponse<T>(T data,String status) {
|
||||||
|
public static <T> ApiResponse<T> ok(T data) { return new ApiResponse<>(data,"success"); }
|
||||||
|
public static ApiResponse<Message> fail(String message) { return new ApiResponse<>(new Message(message),"error"); }
|
||||||
|
}
|
||||||
|
public record Message(String message) {}
|
||||||
|
public record Requester(int id,String role) { public boolean admin() { return "admin".equals(role); } }
|
||||||
|
public record Input(Map<String,Object> fields) {}
|
||||||
|
public static class Payload extends LinkedHashMap<String,Object> {
|
||||||
|
@Override public String toString() { return "[client request body redacted]"; }
|
||||||
|
}
|
||||||
|
public static Input parse(Map<String,Object> body,boolean creating) {
|
||||||
|
if(body==null || body.isEmpty() || !Set.of("identdocument","businessname","description","id_recomended","id_documenttype").containsAll(body.keySet())
|
||||||
|
|| (creating && !body.keySet().containsAll(Set.of("identdocument","businessname","id_documenttype")))) throw invalid();
|
||||||
|
var fields=new LinkedHashMap<String,Object>();
|
||||||
|
for(var entry:body.entrySet()) {
|
||||||
|
String key=entry.getKey(); Object raw=entry.getValue();
|
||||||
|
if(raw==null && Set.of("description","id_recomended").contains(key)) fields.put(key,null);
|
||||||
|
else if(key.equals("businessname") || key.equals("description")) {
|
||||||
|
if(!(raw instanceof String text)) throw invalid();
|
||||||
|
String value=text.strip(); int max=key.equals("businessname")?255:1000;
|
||||||
|
if(value.isEmpty() || value.length()>max) throw invalid();
|
||||||
|
fields.put(key,value);
|
||||||
|
} else fields.put(key,positiveId(raw));
|
||||||
|
}
|
||||||
|
return new Input(Collections.unmodifiableMap(fields));
|
||||||
|
}
|
||||||
|
public static int positiveId(Object raw) {
|
||||||
|
try {
|
||||||
|
double n=raw instanceof Number number?number.doubleValue():raw instanceof String s?Double.parseDouble(s.strip()):Double.NaN;
|
||||||
|
if(!Double.isFinite(n) || n<=0 || n>Integer.MAX_VALUE || n!=Math.rint(n)) throw invalid();
|
||||||
|
return (int)n;
|
||||||
|
} catch(NumberFormatException exception) { throw invalid(); }
|
||||||
|
}
|
||||||
|
public static ApiException invalid() { return new ApiException(400,"Invalid request."); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.aellis.clients.api;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
public class HealthController {
|
||||||
|
@GetMapping("/health") public Map<String, Boolean> health() { return Map.of("ok", true); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.aellis.clients.audit;
|
||||||
|
|
||||||
|
import com.aellis.clients.api.ApiException;
|
||||||
|
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 ApiException(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.clients.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","clients").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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.aellis.clients.config;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.List;
|
||||||
|
import jakarta.validation.constraints.*;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
|
||||||
|
@Validated
|
||||||
|
@ConfigurationProperties("clients")
|
||||||
|
public record ClientProperties(@NotBlank String jwtAlgorithm, Resource publicKey, String tokenSecret,
|
||||||
|
@NotBlank String issuer, @NotBlank String audience, boolean checkSession, @NotNull Duration jwtMaxAge,
|
||||||
|
@NotEmpty List<String> allowedOrigins, @Min(0) int rateLimitMax, @Min(1) long rateLimitWindowMs,
|
||||||
|
@Min(1) int rateLimitMemoryMaxKeys, @Min(1000) long rateLimitRedisBackoffMs,
|
||||||
|
@NotBlank String rateLimitPrefix, String redisUrl, boolean requestLogEnabled) {
|
||||||
|
public ClientProperties {
|
||||||
|
if (!List.of("RS256", "HS256").contains(jwtAlgorithm)) throw new IllegalArgumentException("JWT_ALGORITHM debe ser RS256 o HS256");
|
||||||
|
if (jwtMaxAge != null && (jwtMaxAge.isNegative() || jwtMaxAge.isZero())) throw new IllegalArgumentException("JWT_MAX_AGE debe ser positivo");
|
||||||
|
if (allowedOrigins != null && allowedOrigins.contains("*")) throw new IllegalArgumentException("Configura origenes CORS explicitos");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package com.aellis.clients.config;
|
||||||
|
|
||||||
|
import jakarta.servlet.*;
|
||||||
|
import jakarta.servlet.http.*;
|
||||||
|
import java.io.*;
|
||||||
|
import java.time.Clock;
|
||||||
|
import java.util.*;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
|
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class RequestFilter extends OncePerRequestFilter {
|
||||||
|
private static final long MAX_BODY = 1024 * 1024;
|
||||||
|
private record Window(long count, long resetAt) {}
|
||||||
|
record Limit(long count, long resetAt, boolean allowed) {}
|
||||||
|
private static final DefaultRedisScript<List> REDIS_SCRIPT = new DefaultRedisScript<>("""
|
||||||
|
local count=redis.call('INCR',KEYS[1])
|
||||||
|
local ttl=redis.call('PTTL',KEYS[1])
|
||||||
|
if count==1 or ttl<0 then redis.call('PEXPIRE',KEYS[1],ARGV[1]); ttl=tonumber(ARGV[1]) end
|
||||||
|
return {count,ttl}
|
||||||
|
""", List.class);
|
||||||
|
private final Map<String, Window> memory = new LinkedHashMap<>();
|
||||||
|
private final ClientProperties properties;
|
||||||
|
private final Clock clock;
|
||||||
|
private final StringRedisTemplate redis;
|
||||||
|
private volatile long redisDisabledUntil;
|
||||||
|
public RequestFilter(ClientProperties properties, Clock clock, StringRedisTemplate redis) {
|
||||||
|
this.properties = properties; this.clock = clock; this.redis = redis;
|
||||||
|
}
|
||||||
|
synchronized Limit memoryLimit(String key) {
|
||||||
|
long now = clock.millis();
|
||||||
|
var window = memory.get(key);
|
||||||
|
if (window == null || window.resetAt() <= now) {
|
||||||
|
if (memory.size() >= properties.rateLimitMemoryMaxKeys()) {
|
||||||
|
memory.entrySet().removeIf(entry -> entry.getValue().resetAt() <= now);
|
||||||
|
if (memory.size() >= properties.rateLimitMemoryMaxKeys() && !memory.containsKey(key)) {
|
||||||
|
return new Limit(properties.rateLimitMax(), now + properties.rateLimitWindowMs(), false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window = new Window(1, now + properties.rateLimitWindowMs());
|
||||||
|
} else window = new Window(Math.min(window.count() + 1, properties.rateLimitMax() + 1L), window.resetAt());
|
||||||
|
memory.put(key, window);
|
||||||
|
return new Limit(window.count(), window.resetAt(), window.count() <= properties.rateLimitMax());
|
||||||
|
}
|
||||||
|
private Limit limit(String key) {
|
||||||
|
long now = clock.millis();
|
||||||
|
if (properties.redisUrl() != null && !properties.redisUrl().isBlank() && now >= redisDisabledUntil) {
|
||||||
|
try {
|
||||||
|
List<?> result = redis.execute(REDIS_SCRIPT, List.of(properties.rateLimitPrefix() + ":" + key), Long.toString(properties.rateLimitWindowMs()));
|
||||||
|
if (result != null && result.size() == 2) {
|
||||||
|
long count = ((Number) result.get(0)).longValue(); long ttl = ((Number) result.get(1)).longValue();
|
||||||
|
return new Limit(count, now + Math.max(ttl, 0), count <= properties.rateLimitMax());
|
||||||
|
}
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
redisDisabledUntil = now + properties.rateLimitRedisBackoffMs();
|
||||||
|
LoggerFactory.getLogger(getClass()).warn("redis_rate_limit_unavailable; using local limiter");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return memoryLimit(key);
|
||||||
|
}
|
||||||
|
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||||
|
throws ServletException, IOException {
|
||||||
|
String supplied = request.getHeader("X-Request-Id");
|
||||||
|
String requestId = supplied != null && supplied.matches("[A-Za-z0-9._:-]{1,128}") ? supplied : UUID.randomUUID().toString();
|
||||||
|
response.setHeader("X-Request-Id", requestId); response.setHeader("Cache-Control", "no-store");
|
||||||
|
response.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
|
||||||
|
response.setHeader("X-DNS-Prefetch-Control", "off");
|
||||||
|
if (properties.rateLimitMax() > 0) {
|
||||||
|
var limit = limit(request.getRemoteAddr());
|
||||||
|
response.setHeader("X-RateLimit-Limit", Integer.toString(properties.rateLimitMax()));
|
||||||
|
response.setHeader("X-RateLimit-Remaining", Long.toString(Math.max(0, properties.rateLimitMax() - limit.count())));
|
||||||
|
response.setHeader("X-RateLimit-Reset", Long.toString((limit.resetAt() + 999) / 1000));
|
||||||
|
if (!limit.allowed()) {
|
||||||
|
response.setHeader("Retry-After", Long.toString(Math.max(1, (limit.resetAt() - clock.millis() + 999) / 1000)));
|
||||||
|
error(response, 429, "Too many requests."); return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (request.getContentLengthLong() > MAX_BODY) { error(response, 413, "Request body too large."); return; }
|
||||||
|
long start = clock.millis();
|
||||||
|
try { chain.doFilter(new LimitedRequest(request), response); }
|
||||||
|
finally {
|
||||||
|
if (properties.requestLogEnabled()) LoggerFactory.getLogger(getClass()).info("request method={} path={} status={} durationMs={} requestId={}",
|
||||||
|
request.getMethod(), request.getServletPath(), response.getStatus(), clock.millis() - start, requestId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static void error(HttpServletResponse response, int status, String message) throws IOException {
|
||||||
|
response.setStatus(status); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json");
|
||||||
|
if (status == 401) response.setHeader("WWW-Authenticate", "Bearer");
|
||||||
|
response.getWriter().write("{\"data\":{\"message\":\"" + message + "\"},\"status\":\"error\"}");
|
||||||
|
}
|
||||||
|
@Bean FilterRegistrationBean<RequestFilter> disableDoubleRegistration() {
|
||||||
|
var registration = new FilterRegistrationBean<>(this); registration.setEnabled(false); return registration;
|
||||||
|
}
|
||||||
|
public static class BodyTooLargeException extends IOException {}
|
||||||
|
private static class LimitedRequest extends HttpServletRequestWrapper {
|
||||||
|
private ServletInputStream input;
|
||||||
|
LimitedRequest(HttpServletRequest request) { super(request); }
|
||||||
|
@Override public ServletInputStream getInputStream() throws IOException {
|
||||||
|
if (input == null) {
|
||||||
|
var original = super.getInputStream();
|
||||||
|
input = new ServletInputStream() {
|
||||||
|
long count;
|
||||||
|
private void check(int read) throws IOException { if (read > 0 && (count += read) > MAX_BODY) throw new BodyTooLargeException(); }
|
||||||
|
@Override public int read() throws IOException { int value = original.read(); check(value < 0 ? 0 : 1); return value; }
|
||||||
|
@Override public int read(byte[] bytes, int offset, int length) throws IOException { int value = original.read(bytes, offset, length); check(value); return value; }
|
||||||
|
@Override public boolean isFinished() { return original.isFinished(); }
|
||||||
|
@Override public boolean isReady() { return original.isReady(); }
|
||||||
|
@Override public void setReadListener(ReadListener listener) { original.setReadListener(listener); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return input;
|
||||||
|
}
|
||||||
|
@Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream(), java.nio.charset.StandardCharsets.UTF_8)); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package com.aellis.clients.config;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.KeyFactory;
|
||||||
|
import java.security.interfaces.RSAPublicKey;
|
||||||
|
import java.security.spec.X509EncodedKeySpec;
|
||||||
|
import java.time.*;
|
||||||
|
import java.util.*;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import org.springframework.context.annotation.*;
|
||||||
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.oauth2.core.*;
|
||||||
|
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
|
||||||
|
import org.springframework.security.oauth2.jwt.*;
|
||||||
|
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
|
||||||
|
import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.web.cors.*;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class SecurityConfig {
|
||||||
|
@Bean Clock clock() { return Clock.systemUTC(); }
|
||||||
|
|
||||||
|
@Bean JwtDecoder jwtDecoder(ClientProperties properties, JdbcClient jdbc, Clock clock) throws Exception {
|
||||||
|
NimbusJwtDecoder decoder;
|
||||||
|
if (properties.jwtAlgorithm().equals("HS256")) {
|
||||||
|
byte[] secret = properties.tokenSecret().getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (secret.length < 32) throw new IllegalArgumentException("TOKEN_SECRET debe tener al menos 32 bytes para HS256");
|
||||||
|
decoder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec(secret, "HmacSHA256")).macAlgorithm(MacAlgorithm.HS256).build();
|
||||||
|
} else {
|
||||||
|
byte[] encoded;
|
||||||
|
try (var input = properties.publicKey().getInputStream()) {
|
||||||
|
encoded = Base64.getDecoder().decode(new String(input.readAllBytes(), StandardCharsets.US_ASCII)
|
||||||
|
.replaceAll("-----[^-]+-----", "").replaceAll("\\s", ""));
|
||||||
|
}
|
||||||
|
var key = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(encoded));
|
||||||
|
if (key.getModulus().bitLength() < 3072) throw new IllegalArgumentException("La clave RSA debe tener al menos 3072 bits");
|
||||||
|
decoder = NimbusJwtDecoder.withPublicKey(key).build();
|
||||||
|
}
|
||||||
|
OAuth2TokenValidator<Jwt> claims = jwt -> {
|
||||||
|
try {
|
||||||
|
long id = Long.parseLong(jwt.getClaimAsString("id"));
|
||||||
|
String role = jwt.getClaimAsString("rol");
|
||||||
|
if (id <= 0 || id > Integer.MAX_VALUE || role == null || role.isBlank()
|
||||||
|
|| jwt.getExpiresAt() == null || jwt.getIssuedAt() == null
|
||||||
|
|| !jwt.getAudience().contains(properties.audience())
|
||||||
|
|| jwt.getIssuedAt().isAfter(clock.instant().plusSeconds(30))
|
||||||
|
|| jwt.getIssuedAt().plus(properties.jwtMaxAge()).isBefore(clock.instant().minusSeconds(30))
|
||||||
|
|| (jwt.getSubject() != null && !jwt.getSubject().equals(Long.toString(id)))
|
||||||
|
|| ("RS256".equals(properties.jwtAlgorithm()) && !"access".equals(jwt.getClaimAsString("token_use")))
|
||||||
|
|| (jwt.hasClaim("token_use") && !"access".equals(jwt.getClaimAsString("token_use")))) return invalid();
|
||||||
|
boolean active = jdbc.sql("""
|
||||||
|
SELECT EXISTS(SELECT 1 FROM users u JOIN rol r ON r.id=u.id_rol
|
||||||
|
WHERE u.id=:id AND u.id_status<>2 AND lower(r.name)=:role)
|
||||||
|
""").param("id", id).param("role", role).query(Boolean.class).single();
|
||||||
|
if (!active) return invalid();
|
||||||
|
if (properties.checkSession()) {
|
||||||
|
UUID session = UUID.fromString(jwt.getClaimAsString("sid"));
|
||||||
|
boolean valid = jdbc.sql("""
|
||||||
|
SELECT EXISTS(SELECT 1 FROM auth_session WHERE id=:session AND user_id=:id
|
||||||
|
AND NOT revoked AND expires_at>CURRENT_TIMESTAMP)
|
||||||
|
""").param("session", session).param("id", id).query(Boolean.class).single();
|
||||||
|
if (!valid) return invalid();
|
||||||
|
}
|
||||||
|
return OAuth2TokenValidatorResult.success();
|
||||||
|
} catch (IllegalArgumentException | NullPointerException exception) { return invalid(); }
|
||||||
|
};
|
||||||
|
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefaultWithIssuer(properties.issuer()), claims));
|
||||||
|
return decoder;
|
||||||
|
}
|
||||||
|
private static OAuth2TokenValidatorResult invalid() { return OAuth2TokenValidatorResult.failure(new OAuth2Error("invalid_token")); }
|
||||||
|
|
||||||
|
@Bean SecurityFilterChain security(HttpSecurity http, ClientProperties properties, RequestFilter filter) throws Exception {
|
||||||
|
var converter = new JwtAuthenticationConverter();
|
||||||
|
converter.setJwtGrantedAuthoritiesConverter(jwt -> List.of(new SimpleGrantedAuthority("ROLE_" + jwt.getClaimAsString("rol").toUpperCase(Locale.ROOT))));
|
||||||
|
return http.cors(cors -> cors.configurationSource(cors(properties)))
|
||||||
|
.csrf(csrf -> csrf.disable())
|
||||||
|
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
|
.requestCache(cache -> cache.disable()).formLogin(login -> login.disable()).httpBasic(basic -> basic.disable()).logout(logout -> logout.disable())
|
||||||
|
.headers(headers -> headers.contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'none'; frame-ancestors 'none'"))
|
||||||
|
.referrerPolicy(policy -> policy.policy(org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)))
|
||||||
|
.authorizeHttpRequests(auth -> auth
|
||||||
|
.requestMatchers(org.springframework.http.HttpMethod.GET, "/health", "/actuator/health").permitAll()
|
||||||
|
.requestMatchers(org.springframework.http.HttpMethod.POST, "/clients/create").hasRole("ADMIN")
|
||||||
|
.requestMatchers(org.springframework.http.HttpMethod.PUT, "/clients/update/*").hasRole("ADMIN")
|
||||||
|
.requestMatchers(org.springframework.http.HttpMethod.PATCH, "/clients/disable/*").hasRole("ADMIN")
|
||||||
|
.requestMatchers(org.springframework.http.HttpMethod.GET, "/clients/all", "/clients/get/*", "/clients/recomended/*", "/clients/documenttypes", "/clients/all/notfilter").hasAnyRole("ADMIN", "USER")
|
||||||
|
.anyRequest().denyAll())
|
||||||
|
.exceptionHandling(errors -> errors.authenticationEntryPoint((req, res, ex) -> RequestFilter.error(res, 401, "Unauthorized"))
|
||||||
|
.accessDeniedHandler((req, res, ex) -> RequestFilter.error(res, 403, "Forbidden")))
|
||||||
|
.oauth2ResourceServer(resource -> resource.jwt(jwt -> jwt.jwtAuthenticationConverter(converter))
|
||||||
|
.authenticationEntryPoint((req, res, ex) -> RequestFilter.error(res, 401, "Unauthorized")))
|
||||||
|
.addFilterBefore(filter, BearerTokenAuthenticationFilter.class).build();
|
||||||
|
}
|
||||||
|
private CorsConfigurationSource cors(ClientProperties properties) {
|
||||||
|
var configuration = new CorsConfiguration();
|
||||||
|
configuration.setAllowedOrigins(properties.allowedOrigins());
|
||||||
|
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||||
|
configuration.setAllowedHeaders(List.of("X-Audit-Reason", "Content-Type", "Authorization", "X-Request-Id"));
|
||||||
|
configuration.setExposedHeaders(List.of("X-Request-Id", "X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset", "Retry-After"));
|
||||||
|
configuration.setAllowCredentials(false);
|
||||||
|
var source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package com.aellis.clients.repository;
|
||||||
|
|
||||||
|
import com.aellis.clients.api.ClientDtos.*;
|
||||||
|
import java.sql.*;
|
||||||
|
import java.util.*;
|
||||||
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public class ClientRepository {
|
||||||
|
private static final String VIEW="""
|
||||||
|
SELECT c.id,c.identdocument,c.businessname,c.description,c.created,c.id_recomended,c.id_documenttype,
|
||||||
|
u.id AS recommended_id,u.name AS recommended_name,u.lastname AS recommended_lastname,u.acronym AS recommended_acronym,
|
||||||
|
s.name AS status_name,d.id AS documenttype_id,d.name AS documenttype_name
|
||||||
|
FROM client c LEFT JOIN users u ON u.id=c.id_recomended LEFT JOIN status s ON s.id=c.id_status
|
||||||
|
LEFT JOIN documenttype d ON d.id=c.id_documenttype
|
||||||
|
""";
|
||||||
|
private static final String ASSIGNED="""
|
||||||
|
EXISTS(SELECT 1 FROM cases ca JOIN user_case uc ON uc.id_case=ca.id
|
||||||
|
WHERE ca.id_client=c.id AND uc.id_user=:viewer)
|
||||||
|
""";
|
||||||
|
private static final Set<String> WRITABLE=Set.of("identdocument","businessname","description","id_recomended","id_documenttype","id_status");
|
||||||
|
private final JdbcClient jdbc;
|
||||||
|
public ClientRepository(JdbcClient jdbc) { this.jdbc=jdbc; }
|
||||||
|
public boolean exists(String field,int id) {
|
||||||
|
String table=switch(field) { case "id_recomended" -> "users"; case "id_documenttype" -> "documenttype"; case "id_status" -> "status"; default -> throw new IllegalArgumentException("Unknown catalog"); };
|
||||||
|
return jdbc.sql("SELECT EXISTS(SELECT 1 FROM "+table+" WHERE id=:id)").param("id",id).query(Boolean.class).single();
|
||||||
|
}
|
||||||
|
public boolean lock(int id) { return jdbc.sql("SELECT id FROM client WHERE id=:id FOR UPDATE").param("id",id).query(Integer.class).optional().isPresent(); }
|
||||||
|
public int create(Input input) {
|
||||||
|
var fields=input.fields();
|
||||||
|
return jdbc.sql("""
|
||||||
|
INSERT INTO client(identdocument,businessname,description,id_recomended,id_documenttype,id_status,created)
|
||||||
|
VALUES(:document,:name,:description,:recommended,:type,3,CURRENT_TIMESTAMP) RETURNING id
|
||||||
|
""").param("document",fields.get("identdocument")).param("name",fields.get("businessname"))
|
||||||
|
.param("description",fields.get("description")).param("recommended",fields.get("id_recomended"))
|
||||||
|
.param("type",fields.get("id_documenttype")).query(Integer.class).single();
|
||||||
|
}
|
||||||
|
public void update(int id,Map<String,Object> fields) {
|
||||||
|
if(fields.isEmpty() || !WRITABLE.containsAll(fields.keySet())) throw new IllegalArgumentException("Invalid update");
|
||||||
|
String assignments=String.join(",",fields.keySet().stream().map(key -> key+"=:"+key).toList());
|
||||||
|
jdbc.sql("UPDATE client SET "+assignments+",updated=CURRENT_TIMESTAMP WHERE id=:target").params(fields).param("target",id).update();
|
||||||
|
}
|
||||||
|
public Optional<Map<String,Object>> find(int id,Integer viewer) {
|
||||||
|
var query=jdbc.sql(VIEW+" WHERE c.id=:id"+(viewer==null?"":" AND "+ASSIGNED)).param("id",id);
|
||||||
|
if(viewer!=null) query.param("viewer",viewer);
|
||||||
|
return query.query((rs,row) -> mapClient(rs,true)).optional();
|
||||||
|
}
|
||||||
|
public List<Map<String,Object>> list(Integer viewer,boolean active,Integer recommended) {
|
||||||
|
String sql=VIEW+" WHERE TRUE"+(active?" AND c.id_status=3":"")+(viewer==null?"":" AND "+ASSIGNED)+(recommended==null?"":" AND c.id_recomended=:recommended");
|
||||||
|
var query=jdbc.sql(sql+" ORDER BY c.businessname ASC,c.id ASC");
|
||||||
|
if(viewer!=null) query.param("viewer",viewer);
|
||||||
|
if(recommended!=null) query.param("recommended",recommended);
|
||||||
|
return query.query((rs,row) -> mapClient(rs,false)).list();
|
||||||
|
}
|
||||||
|
public List<Map<String,Object>> documentTypes() {
|
||||||
|
return jdbc.sql("SELECT id,name,description FROM documenttype ORDER BY name ASC,id ASC")
|
||||||
|
.query((rs,row) -> map("id",rs.getInt("id"),"name",rs.getString("name"),"description",rs.getString("description"))).list();
|
||||||
|
}
|
||||||
|
private Map<String,Object> mapClient(ResultSet rs,boolean detail) throws SQLException {
|
||||||
|
var item=new LinkedHashMap<String,Object>();
|
||||||
|
for(String field:List.of("id","identdocument","businessname","description","created")) {
|
||||||
|
Object value=rs.getObject(field);
|
||||||
|
if(value instanceof Timestamp timestamp) value=timestamp.toInstant();
|
||||||
|
else if(value instanceof java.time.OffsetDateTime timestamp) value=timestamp.toInstant();
|
||||||
|
item.put(field,value);
|
||||||
|
}
|
||||||
|
item.put("recommended",rs.getObject("recommended_id")==null?null:map("name",rs.getString("recommended_name"),"lastname",rs.getString("recommended_lastname"),"acronym",rs.getString("recommended_acronym")));
|
||||||
|
item.put("statusName",rs.getString("status_name"));
|
||||||
|
if(detail) {
|
||||||
|
item.put("id_recomended",rs.getObject("id_recomended")); item.put("id_documenttype",rs.getObject("id_documenttype"));
|
||||||
|
item.put("documentType",rs.getObject("documenttype_id")==null?null:map("id",rs.getObject("documenttype_id"),"name",rs.getString("documenttype_name")));
|
||||||
|
} else item.put("documentTypeName",rs.getString("documenttype_name"));
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
private static Map<String,Object> map(Object... pairs) {
|
||||||
|
var result=new LinkedHashMap<String,Object>(); for(int i=0;i<pairs.length;i+=2) result.put((String)pairs[i],pairs[i+1]); return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package com.aellis.clients.service;
|
||||||
|
|
||||||
|
import com.aellis.clients.api.*;
|
||||||
|
import com.aellis.clients.audit.BusinessAudit;
|
||||||
|
import com.aellis.clients.api.ClientDtos.*;
|
||||||
|
import com.aellis.clients.repository.ClientRepository;
|
||||||
|
import java.util.*;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class ClientService {
|
||||||
|
private final ClientRepository clients;
|
||||||
|
private final BusinessAudit history;
|
||||||
|
public ClientService(ClientRepository clients,BusinessAudit history) { this.clients=clients; this.history=history; }
|
||||||
|
@Transactional public int create(Requester who,Input input) {
|
||||||
|
admin(who); validate(input.fields()); status(3); var context=history.context(who.id());
|
||||||
|
int id=clients.create(input); history.change(context,"client.create","client",id,null,Map.of(),history.snapshot("client",id)); return id;
|
||||||
|
}
|
||||||
|
@Transactional public void update(Requester who,int id,Input input) {
|
||||||
|
admin(who); if(!clients.lock(id)) throw missing(); var context=history.context(who.id()); var before=history.snapshot("client",id);
|
||||||
|
validate(input.fields()); clients.update(id,input.fields()); history.change(context,"client.update","client",id,null,before,history.snapshot("client",id));
|
||||||
|
}
|
||||||
|
@Transactional public void disable(Requester who,int id) {
|
||||||
|
admin(who); if(!clients.lock(id)) throw missing(); var context=history.context(who.id()); var before=history.snapshot("client",id);
|
||||||
|
status(8); clients.update(id,Map.of("id_status",8)); history.change(context,"client.disable","client",id,null,before,history.snapshot("client",id));
|
||||||
|
}
|
||||||
|
public Map<String,Object> find(Requester who,int id) { return clients.find(id,viewer(who)).orElseThrow(ClientService::missing); }
|
||||||
|
public List<Map<String,Object>> all(Requester who,boolean active) { return clients.list(viewer(who),active,null); }
|
||||||
|
public List<Map<String,Object>> recommended(Requester who,int user) { return clients.list(viewer(who),true,user); }
|
||||||
|
public List<Map<String,Object>> documentTypes() { return clients.documentTypes(); }
|
||||||
|
private void validate(Map<String,Object> fields) {
|
||||||
|
for(String field:List.of("id_recomended","id_documenttype")) {
|
||||||
|
Object id=fields.get(field);
|
||||||
|
if(id!=null && !clients.exists(field,(Integer)id)) throw new ApiException(400,field.equals("id_recomended")?"Usuario recomendado inválido.":"Tipo de documento inválido.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private void status(int id) { if(!clients.exists("id_status",id)) throw new ApiException(400,"Estado de cliente inválido."); }
|
||||||
|
private static Integer viewer(Requester who) { return who.admin()?null:who.id(); }
|
||||||
|
private static void admin(Requester who) { if(!who.admin()) throw new ApiException(403,"Forbidden."); }
|
||||||
|
private static ApiException missing() { return new ApiException(404,"Cliente no encontrado"); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
spring:
|
||||||
|
application:
|
||||||
|
name: genesis-client
|
||||||
|
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
|
||||||
|
data:
|
||||||
|
redis:
|
||||||
|
url: ${REDIS_URL:redis://localhost:6379}
|
||||||
|
connect-timeout: 500ms
|
||||||
|
timeout: 500ms
|
||||||
|
jackson:
|
||||||
|
deserialization:
|
||||||
|
fail-on-unknown-properties: true
|
||||||
|
server:
|
||||||
|
port: ${SERVER_PORT:8085}
|
||||||
|
shutdown: graceful
|
||||||
|
forward-headers-strategy: none
|
||||||
|
max-http-request-header-size: 16KB
|
||||||
|
error:
|
||||||
|
include-message: never
|
||||||
|
include-stacktrace: never
|
||||||
|
management:
|
||||||
|
endpoints:
|
||||||
|
web:
|
||||||
|
exposure:
|
||||||
|
include: health
|
||||||
|
endpoint:
|
||||||
|
health:
|
||||||
|
show-details: never
|
||||||
|
health:
|
||||||
|
redis:
|
||||||
|
enabled: false
|
||||||
|
clients:
|
||||||
|
jwt-algorithm: ${JWT_ALGORITHM:RS256}
|
||||||
|
public-key: ${JWT_PUBLIC_KEY:file:.secrets/public.pem}
|
||||||
|
token-secret: ${TOKEN_SECRET:}
|
||||||
|
issuer: ${JWT_ISSUER:http://localhost:8080}
|
||||||
|
audience: ${JWT_AUDIENCE:genesis-api}
|
||||||
|
check-session: ${JWT_CHECK_SESSION:true}
|
||||||
|
jwt-max-age: ${JWT_MAX_AGE:15m}
|
||||||
|
allowed-origins: ${CORS_ALLOWED_ORIGINS:${FRONTEND_URL:http://localhost:3000}}
|
||||||
|
rate-limit-max: ${RATE_LIMIT_MAX:300}
|
||||||
|
rate-limit-window-ms: ${RATE_LIMIT_WINDOW_MS:60000}
|
||||||
|
rate-limit-memory-max-keys: ${RATE_LIMIT_MEMORY_MAX_KEYS:10000}
|
||||||
|
rate-limit-redis-backoff-ms: ${RATE_LIMIT_REDIS_BACKOFF_MS:60000}
|
||||||
|
rate-limit-prefix: ${RATE_LIMIT_PREFIX:genesis-client:rate}
|
||||||
|
redis-url: ${REDIS_URL:}
|
||||||
|
request-log-enabled: ${REQUEST_LOG_ENABLED:true}
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
package com.aellis.clients;
|
||||||
|
|
||||||
|
import com.nimbusds.jose.jwk.*;
|
||||||
|
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.*;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.security.*;
|
||||||
|
import java.security.interfaces.RSAPublicKey;
|
||||||
|
import java.security.interfaces.RSAPrivateKey;
|
||||||
|
import java.sql.*;
|
||||||
|
import java.time.*;
|
||||||
|
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.env.Environment;
|
||||||
|
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.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
|
||||||
|
import org.springframework.security.oauth2.jwt.*;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
import org.springframework.test.context.*;
|
||||||
|
import org.testcontainers.postgresql.PostgreSQLContainer;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
|
||||||
|
"logging.level.root=WARN", "debug=false", "clients.request-log-enabled=false", "clients.rate-limit-max=10000", "clients.redis-url=", "clients.allowed-origins=http://localhost:3000", "spring.data.redis.port=1"})
|
||||||
|
class ClientServiceIT {
|
||||||
|
static final PostgreSQLContainer DB = new PostgreSQLContainer("postgres:18");
|
||||||
|
static String url, username, password, schema;
|
||||||
|
static Path keyDirectory;
|
||||||
|
static JwtEncoder signer;
|
||||||
|
@DynamicPropertySource static void database(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 = "clients_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("schema.sql")); }
|
||||||
|
var generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(3072); var pair = generator.generateKeyPair();
|
||||||
|
var key = new RSAKey.Builder((RSAPublicKey) pair.getPublic()).privateKey((RSAPrivateKey) pair.getPrivate()).keyID("test-auth").build();
|
||||||
|
signer = new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(key)));
|
||||||
|
keyDirectory = Files.createTempDirectory("genesis-clients-public-key");
|
||||||
|
Files.writeString(keyDirectory.resolve("public.pem"), "-----BEGIN PUBLIC KEY-----\n"
|
||||||
|
+ Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()) + "\n-----END PUBLIC KEY-----");
|
||||||
|
registry.add("spring.datasource.url", () -> schemaUrl);
|
||||||
|
registry.add("spring.datasource.username", () -> username);
|
||||||
|
registry.add("spring.datasource.password", () -> password);
|
||||||
|
registry.add("clients.public-key", () -> keyDirectory.resolve("public.pem").toUri().toString());
|
||||||
|
registry.add("clients.jwt-algorithm", () -> "RS256");
|
||||||
|
registry.add("clients.issuer", () -> "http://localhost:8080"); registry.add("clients.audience", () -> "genesis-api");
|
||||||
|
registry.add("clients.check-session", () -> true);
|
||||||
|
}
|
||||||
|
@AfterAll static void cleanup() throws Exception {
|
||||||
|
try (var connection = DriverManager.getConnection(url, username, password); var statement = connection.createStatement()) {
|
||||||
|
statement.execute("DROP SCHEMA " + schema + " CASCADE");
|
||||||
|
}
|
||||||
|
if (keyDirectory != null) { Files.deleteIfExists(keyDirectory.resolve("public.pem")); Files.deleteIfExists(keyDirectory); }
|
||||||
|
if (DB.isRunning()) DB.stop();
|
||||||
|
}
|
||||||
|
@Autowired JdbcClient jdbc;
|
||||||
|
@Autowired javax.sql.DataSource dataSource;
|
||||||
|
@Autowired Environment environment;
|
||||||
|
final HttpClient http = HttpClient.newHttpClient();
|
||||||
|
final JsonMapper json = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
|
||||||
|
@BeforeEach void seed() {
|
||||||
|
jdbc.sql("TRUNCATE business_audit_events RESTART IDENTITY").update();
|
||||||
|
jdbc.sql("TRUNCATE users,client RESTART IDENTITY CASCADE").update();
|
||||||
|
jdbc.sql("INSERT INTO users VALUES(1,'Admin','Prueba','AD','test-only-hash','test-only-reset',1,1),(2,'Ana','Prueba','AN','test-only-hash','test-only-reset',2,1),(3,'Luis','Prueba','LU','test-only-hash','test-only-reset',2,1),(4,'Inactivo','Prueba','IN','test-only-hash','test-only-reset',2,2),(5,'Supervisor','Prueba','SU','test-only-hash','test-only-reset',3,1),(6,'Libre','Prueba','LI','test-only-hash','test-only-reset',2,1)").update();
|
||||||
|
jdbc.sql("""
|
||||||
|
INSERT INTO client(id,identdocument,businessname,description,id_status,id_documenttype,id_recomended) VALUES
|
||||||
|
(1,111,'Zeta','Detalle',3,1,2),(2,222,'Alfa',NULL,3,2,3),(3,333,'Archivado',NULL,8,1,2),
|
||||||
|
(4,444,'Beta',NULL,9,1,NULL),(5,555,'Oculto',NULL,3,1,2)
|
||||||
|
""").update();
|
||||||
|
jdbc.sql("SELECT setval(pg_get_serial_sequence('client','id'),5,TRUE)").query(Long.class).single();
|
||||||
|
jdbc.sql("INSERT INTO cases VALUES(1,1,4),(2,2,4),(3,3,4),(4,4,4)").update();
|
||||||
|
jdbc.sql("INSERT INTO user_case(id_user,id_case) VALUES(2,1),(2,3),(3,2),(1,2)").update();
|
||||||
|
}
|
||||||
|
Map<String,Object> createBody() { return new LinkedHashMap<>(Map.of("identdocument","999","businessname"," Nuevo ","id_documenttype","1")); }
|
||||||
|
tools.jackson.databind.JsonNode data(HttpResponse<String> response) { return json.readTree(response.body()).get("data"); }
|
||||||
|
@Test void healthIsPublicAndAllEightRoutesRequireAuthentication() throws Exception {
|
||||||
|
assertThat(request("GET","/health",null,null).body()).contains("\"ok\":true");
|
||||||
|
assertThat(request("GET","/actuator/health",null,null).statusCode()).isEqualTo(200);
|
||||||
|
for(String route:List.of("all","get/1","recomended/2","documenttypes","all/notfilter"))
|
||||||
|
assertThat(request("GET","/clients/"+route,null,null).statusCode()).isEqualTo(401);
|
||||||
|
assertThat(request("POST","/clients/create",createBody(),null).statusCode()).isEqualTo(401);
|
||||||
|
assertThat(request("PUT","/clients/update/1",Map.of(),null).statusCode()).isEqualTo(401);
|
||||||
|
assertThat(request("PATCH","/clients/disable/1",null,null).statusCode()).isEqualTo(401);
|
||||||
|
}
|
||||||
|
@Test void adminCreatesNormalizedClientWithDefaultsAndReturnsId() throws Exception {
|
||||||
|
var body=createBody(); body.put("description"," Descripcion "); body.put("id_recomended","2");
|
||||||
|
var response=request("POST","/clients/create",body,token(1,"admin"));
|
||||||
|
assertThat(response.statusCode()).isEqualTo(200); assertThat(data(response).get("id_client").asInt()).isEqualTo(6);
|
||||||
|
assertThat(response.body()).contains("Cliente registrado exitosamente.");
|
||||||
|
assertThat(jdbc.sql("SELECT businessname='Nuevo' AND description='Descripcion' AND id_recomended=2 AND id_status=3 AND created IS NOT NULL AND updated IS NULL FROM client WHERE id=6").query(Boolean.class).single()).isTrue();
|
||||||
|
assertThat(request("POST","/clients/create",Map.of("identdocument",1000,"businessname","Sin recomendador","id_documenttype",1),token(1,"admin")).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(jdbc.sql("SELECT description IS NULL AND id_recomended IS NULL FROM client WHERE id=7").query(Boolean.class).single()).isTrue();
|
||||||
|
}
|
||||||
|
@Test void normalUsersCannotMutateClientsAndOtherRolesAreDenied() throws Exception {
|
||||||
|
String user=token(2,"user");
|
||||||
|
assertThat(request("POST","/clients/create",createBody(),user).statusCode()).isEqualTo(403);
|
||||||
|
assertThat(request("PUT","/clients/update/1",Map.of("businessname","Cambio"),user).statusCode()).isEqualTo(403);
|
||||||
|
assertThat(request("PATCH","/clients/disable/1",null,user).statusCode()).isEqualTo(403);
|
||||||
|
assertThat(request("GET","/clients/all",null,token(5,"supervisor")).statusCode()).isEqualTo(403);
|
||||||
|
}
|
||||||
|
@Test void activeAndUnfilteredListsAreScopedToAssignedCases() throws Exception {
|
||||||
|
String user=token(2,"user"),admin=token(1,"admin");
|
||||||
|
var active=data(request("GET","/clients/all",null,user)).get("clients");
|
||||||
|
assertThat(active.size()).isEqualTo(1); assertThat(active.get(0).get("id").asInt()).isEqualTo(1);
|
||||||
|
var all=data(request("GET","/clients/all/notfilter",null,user)).get("clients");
|
||||||
|
assertThat(all.size()).isEqualTo(2); assertThat(all.get(0).get("businessname").asString()).isEqualTo("Archivado");
|
||||||
|
assertThat(data(request("GET","/clients/all",null,admin)).get("clients").size()).isEqualTo(3);
|
||||||
|
assertThat(data(request("GET","/clients/all/notfilter",null,admin)).get("clients").size()).isEqualTo(5);
|
||||||
|
assertThat(data(request("GET","/clients/all",null,token(6,"user"))).get("clients").size()).isZero();
|
||||||
|
// Varias asignaciones al mismo cliente no duplican filas.
|
||||||
|
jdbc.sql("INSERT INTO cases VALUES(5,1,4)").update();
|
||||||
|
jdbc.sql("INSERT INTO user_case(id_user,id_case) VALUES(2,5),(2,1)").update();
|
||||||
|
assertThat(data(request("GET","/clients/all",null,user)).get("clients").size()).isEqualTo(1);
|
||||||
|
}
|
||||||
|
@Test void detailPreservesDtoAndHidesUnassignedAndMissingClientsWith404() throws Exception {
|
||||||
|
String user=token(2,"user"),admin=token(1,"admin");
|
||||||
|
var response=request("GET","/clients/get/1",null,user);
|
||||||
|
var item=data(response).get("client");
|
||||||
|
assertThat(response.statusCode()).isEqualTo(200); assertThat(item.get("id_recomended").asInt()).isEqualTo(2);
|
||||||
|
assertThat(item.get("recommended").get("name").asString()).isEqualTo("Ana");
|
||||||
|
assertThat(item.get("recommended").size()).isEqualTo(3);
|
||||||
|
assertThat(item.get("documentType").get("name").asString()).isEqualTo("Pasaporte");
|
||||||
|
assertThat(item.get("statusName").asString()).isEqualTo("Activo"); assertThat(item.get("created").asString()).contains("T");
|
||||||
|
assertThat(item.has("documentTypeName")).isFalse(); assertThat(item.has("id_status")).isFalse();
|
||||||
|
assertThat(response.body()).doesNotContain("test-only-hash","test-only-reset","password","reset_token_hash");
|
||||||
|
for(int id:List.of(2,5,999)) assertThat(request("GET","/clients/get/"+id,null,user).statusCode()).isEqualTo(404);
|
||||||
|
assertThat(request("GET","/clients/get/999",null,admin).statusCode()).isEqualTo(404);
|
||||||
|
assertThat(request("GET","/clients/get/3",null,user).statusCode()).isEqualTo(200);
|
||||||
|
}
|
||||||
|
@Test void listDtosUseFlattenedCatalogNamesAndNullableRecommended() throws Exception {
|
||||||
|
String admin=token(1,"admin");
|
||||||
|
var active=data(request("GET","/clients/all",null,admin)).get("clients");
|
||||||
|
assertThat(active.get(0).get("businessname").asString()).isEqualTo("Alfa");
|
||||||
|
assertThat(active.get(0).get("documentTypeName").asString()).isEqualTo("NIF");
|
||||||
|
assertThat(active.get(0).get("description").isNull()).isTrue();
|
||||||
|
assertThat(active.get(0).has("id_recomended")).isFalse(); assertThat(active.get(0).has("documentType")).isFalse();
|
||||||
|
var detail=data(request("GET","/clients/get/4",null,admin)).get("client");
|
||||||
|
assertThat(detail.get("recommended").isNull()).isTrue();
|
||||||
|
assertThat(detail.get("id_recomended").isNull()).isTrue();
|
||||||
|
}
|
||||||
|
@Test void recommendedFiltersCannotExposeClientsOutsideAssignments() throws Exception {
|
||||||
|
String user=token(2,"user"),admin=token(1,"admin");
|
||||||
|
var own=data(request("GET","/clients/recomended/2",null,user)).get("clients");
|
||||||
|
assertThat(own.size()).isEqualTo(1); assertThat(own.get(0).get("id").asInt()).isEqualTo(1);
|
||||||
|
assertThat(data(request("GET","/clients/recomended/2",null,admin)).get("clients").size()).isEqualTo(2);
|
||||||
|
assertThat(data(request("GET","/clients/recomended/3",null,user)).get("clients").size()).isZero();
|
||||||
|
assertThat(data(request("GET","/clients/recomended/999",null,admin)).get("clients").size()).isZero();
|
||||||
|
// Ser recomendador no concede acceso si no hay caso asignado.
|
||||||
|
assertThat(request("GET","/clients/get/5",null,user).statusCode()).isEqualTo(404);
|
||||||
|
}
|
||||||
|
@Test void removingAssignmentsRevokesAllClientReadsWithoutLoggingOut() throws Exception {
|
||||||
|
String user=token(2,"user");
|
||||||
|
assertThat(request("GET","/clients/get/1",null,user).statusCode()).isEqualTo(200);
|
||||||
|
jdbc.sql("DELETE FROM user_case WHERE id_user=2 AND id_case=1").update();
|
||||||
|
assertThat(request("GET","/clients/get/1",null,user).statusCode()).isEqualTo(404);
|
||||||
|
assertThat(data(request("GET","/clients/all",null,user)).get("clients").size()).isZero();
|
||||||
|
assertThat(data(request("GET","/clients/recomended/2",null,user)).get("clients").size()).isZero();
|
||||||
|
assertThat(data(request("GET","/clients/all/notfilter",null,user)).get("clients").size()).isEqualTo(1);
|
||||||
|
}
|
||||||
|
@Test void updateIsPartialAndCanExplicitlyClearNullableFields() throws Exception {
|
||||||
|
String admin=token(1,"admin"); var body=new LinkedHashMap<String,Object>(); body.put("description",null); body.put("id_recomended",null);
|
||||||
|
assertThat(request("PUT","/clients/update/1",body,admin).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(jdbc.sql("SELECT description IS NULL AND id_recomended IS NULL AND businessname='Zeta' AND identdocument=111 AND updated IS NOT NULL FROM client WHERE id=1").query(Boolean.class).single()).isTrue();
|
||||||
|
assertThat(request("PUT","/clients/update/1",Map.of("businessname"," Editado ","id_documenttype",2),admin).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(jdbc.sql("SELECT businessname='Editado' AND id_documenttype=2 FROM client WHERE id=1").query(Boolean.class).single()).isTrue();
|
||||||
|
assertThat(request("PUT","/clients/update/999",Map.of("description","Algo"),admin).statusCode()).isEqualTo(404);
|
||||||
|
}
|
||||||
|
@Test void disablingIsLogicalAndPreservesCasesAssignmentsAndBilling() throws Exception {
|
||||||
|
jdbc.sql("INSERT INTO activities(id_case,id_paytype,amount,payment) VALUES(1,1,20,TRUE),(1,4,30,NULL)").update();
|
||||||
|
String admin=token(1,"admin"),user=token(2,"user");
|
||||||
|
var response=request("PATCH","/clients/disable/1",null,admin);
|
||||||
|
assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body()).contains("Cliente eliminado exitosamente.");
|
||||||
|
assertThat(jdbc.sql("SELECT id_status=8 AND updated IS NOT NULL FROM client WHERE id=1").query(Boolean.class).single()).isTrue();
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM cases WHERE id_client=1").query(Integer.class).single()).isEqualTo(1);
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM user_case WHERE id_case=1").query(Integer.class).single()).isEqualTo(1);
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM activities WHERE id_case=1").query(Integer.class).single()).isEqualTo(2);
|
||||||
|
assertThat(jdbc.sql("SELECT payment FROM activities WHERE id_paytype=1").query(Boolean.class).single()).isTrue();
|
||||||
|
assertThat(data(request("GET","/clients/all",null,user)).get("clients").size()).isZero();
|
||||||
|
assertThat(request("GET","/clients/get/1",null,user).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(request("PATCH","/clients/disable/999",null,admin).statusCode()).isEqualTo(404);
|
||||||
|
}
|
||||||
|
@Test void documentCatalogIsSortedAndAvailableEvenWithoutClientAssignments() throws Exception {
|
||||||
|
var types=data(request("GET","/clients/documenttypes",null,token(6,"user"))).get("documentTypes");
|
||||||
|
assertThat(types.size()).isEqualTo(2); assertThat(types.get(0).get("name").asString()).isEqualTo("NIF");
|
||||||
|
assertThat(types.get(0).has("description")).isTrue(); assertThat(types.get(0).size()).isEqualTo(3);
|
||||||
|
}
|
||||||
|
@Test void strictValidationRejectsUnknownFieldsBadIdsAndBlankStrings() throws Exception {
|
||||||
|
String admin=token(1,"admin");
|
||||||
|
for(var body:List.of(Map.of(),Map.of("identdocument",1,"id_documenttype",1),Map.of("identdocument",1,"id_documenttype",1,"businessname"," "),Map.of("identdocument",2147483648L,"id_documenttype",1,"businessname","Grande"),Map.of("identdocument",1,"id_documenttype",1,"businessname","Nombre","id_status",8)))
|
||||||
|
assertThat(request("POST","/clients/create",body,admin).statusCode()).isEqualTo(400);
|
||||||
|
for(var body:List.of(Map.of(),Map.of("id_recomended",0),Map.of("identdocument",1.5),Map.of("description"," "),Map.of("description","x".repeat(1001)),Map.of("businessname","x".repeat(256)),Map.of("extra",1)))
|
||||||
|
assertThat(request("PUT","/clients/update/1",body,admin).statusCode()).isEqualTo(400);
|
||||||
|
var nullName=new HashMap<String,Object>(); nullName.put("businessname",null);
|
||||||
|
assertThat(request("PUT","/clients/update/1",nullName,admin).statusCode()).isEqualTo(400);
|
||||||
|
for(String id:List.of("0","-1","1.5","NaN","abc","2147483648")) assertThat(request("GET","/clients/get/"+id,null,admin).statusCode()).isEqualTo(400);
|
||||||
|
}
|
||||||
|
@Test void invalidForeignKeysAndDuplicateDocumentsRollbackWithoutLeakingDatabaseErrors() throws Exception {
|
||||||
|
String admin=token(1,"admin");
|
||||||
|
for(var changes:List.of(Map.of("id_documenttype",999),Map.of("id_recomended",999))) {
|
||||||
|
var body=createBody(); body.putAll(changes);
|
||||||
|
assertThat(request("POST","/clients/create",body,admin).statusCode()).isEqualTo(400);
|
||||||
|
assertThat(request("PUT","/clients/update/1",changes,admin).statusCode()).isEqualTo(400);
|
||||||
|
}
|
||||||
|
var duplicate=createBody(); duplicate.put("identdocument",111);
|
||||||
|
var response=request("POST","/clients/create",duplicate,admin);
|
||||||
|
assertThat(response.statusCode()).isEqualTo(409); assertThat(response.body()).contains("Conflict.").doesNotContain("constraint","SQL");
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM client").query(Integer.class).single()).isEqualTo(5);
|
||||||
|
assertThat(jdbc.sql("SELECT updated IS NULL FROM client WHERE id=1").query(Boolean.class).single()).isTrue();
|
||||||
|
}
|
||||||
|
@Test void descriptionsRespectApiLimitAndExistingDatabaseColumnSize() throws Exception {
|
||||||
|
String admin=token(1,"admin");
|
||||||
|
assertThat(request("PUT","/clients/update/1",Map.of("description","x".repeat(1000)),admin).statusCode()).isEqualTo(200);
|
||||||
|
jdbc.sql("UPDATE client SET description=NULL").update();
|
||||||
|
jdbc.sql("ALTER TABLE client ALTER COLUMN description TYPE VARCHAR(255)").update();
|
||||||
|
try {
|
||||||
|
var response=request("PUT","/clients/update/1",Map.of("description","x".repeat(256)),admin);
|
||||||
|
assertThat(response.statusCode()).isEqualTo(400); assertThat(response.body()).contains("Invalid data.");
|
||||||
|
assertThat(jdbc.sql("SELECT description IS NULL FROM client WHERE id=1").query(Boolean.class).single()).isTrue();
|
||||||
|
} finally { jdbc.sql("ALTER TABLE client ALTER COLUMN description TYPE VARCHAR(1000)").update(); }
|
||||||
|
}
|
||||||
|
@Test void invalidTokensRevokedExpiredSessionsAndDisabledUsersAreRejected() throws Exception {
|
||||||
|
String revoked=token(2,"user"); jdbc.sql("UPDATE auth_session SET revoked=TRUE").update();
|
||||||
|
assertThat(request("GET","/clients/all",null,revoked).statusCode()).isEqualTo(401);
|
||||||
|
assertThat(request("GET","/clients/all",null,token(4,"user")).statusCode()).isEqualTo(401);
|
||||||
|
assertThat(request("GET","/clients/all",null,token(2,"admin")).statusCode()).isEqualTo(401);
|
||||||
|
for(String invalid:List.of("issuer","audience","expiry","age","type","session")) {
|
||||||
|
UUID sid=UUID.randomUUID();
|
||||||
|
if(!invalid.equals("session")) jdbc.sql("INSERT INTO auth_session(id,user_id,expires_at) VALUES(:id,2,CURRENT_TIMESTAMP+INTERVAL '1 day')").param("id",sid).update();
|
||||||
|
String jwt=sign(2,"user",sid,invalid.equals("issuer")?"bad":"http://localhost:8080",invalid.equals("audience")?"bad":"genesis-api",
|
||||||
|
Instant.now().minusSeconds(invalid.equals("age")||invalid.equals("expiry")?3600:0),invalid.equals("expiry")?Instant.now().minusSeconds(120):Instant.now().plusSeconds(900),invalid.equals("type")?"refresh":"access");
|
||||||
|
assertThat(request("GET","/clients/all",null,jwt).statusCode()).isEqualTo(401);
|
||||||
|
}
|
||||||
|
String expired=token(2,"user"); jdbc.sql("UPDATE auth_session SET expires_at=CURRENT_TIMESTAMP-INTERVAL '1 day'").update();
|
||||||
|
assertThat(request("GET","/clients/all",null,expired).statusCode()).isEqualTo(401);
|
||||||
|
String[] parts=token(1,"admin").split("\\.");
|
||||||
|
String forged=parts[0]+"."+Base64.getUrlEncoder().withoutPadding().encodeToString("{\"id\":2}".getBytes())+"."+parts[2];
|
||||||
|
assertThat(request("GET","/clients/all",null,forged).statusCode()).isEqualTo(401);
|
||||||
|
}
|
||||||
|
@Test void corsBodySizeAndSecurityHeadersAreApplied() throws Exception {
|
||||||
|
var allowed=http.send(HttpRequest.newBuilder(URI.create(base()+"/clients/all")).header("Origin","http://localhost:3000").header("Access-Control-Request-Method","GET")
|
||||||
|
.method("OPTIONS",HttpRequest.BodyPublishers.noBody()).build(),HttpResponse.BodyHandlers.ofString());
|
||||||
|
assertThat(allowed.statusCode()).isEqualTo(200); assertThat(allowed.headers().firstValue("Access-Control-Allow-Origin")).hasValue("http://localhost:3000");
|
||||||
|
var blocked=http.send(HttpRequest.newBuilder(URI.create(base()+"/clients/all")).header("Origin","https://untrusted.example").header("Access-Control-Request-Method","GET")
|
||||||
|
.method("OPTIONS",HttpRequest.BodyPublishers.noBody()).build(),HttpResponse.BodyHandlers.ofString());
|
||||||
|
assertThat(blocked.statusCode()).isEqualTo(403);
|
||||||
|
assertThat(request("POST","/clients/create",Map.of("businessname","x".repeat(1024*1024+1)),token(1,"admin")).statusCode()).isEqualTo(413);
|
||||||
|
var health=request("GET","/health",null,null);
|
||||||
|
assertThat(health.headers().firstValue("X-Request-Id")).isPresent();
|
||||||
|
assertThat(health.headers().firstValue("Cache-Control")).hasValue("no-store");
|
||||||
|
}
|
||||||
|
String token(long id, String role) {
|
||||||
|
UUID session = UUID.randomUUID();
|
||||||
|
jdbc.sql("INSERT INTO auth_session(id,user_id,expires_at) VALUES(:session,:id,CURRENT_TIMESTAMP+INTERVAL '1 day')")
|
||||||
|
.param("session", session).param("id", id).update();
|
||||||
|
return sign(id, role, session, "http://localhost:8080", "genesis-api", Instant.now(), Instant.now().plusSeconds(900), "access");
|
||||||
|
}
|
||||||
|
String sign(long id, String role, UUID session, String issuer, String audience, Instant issued, Instant expires, String use) {
|
||||||
|
var claims = JwtClaimsSet.builder().issuer(issuer).subject(Long.toString(id)).audience(List.of(audience))
|
||||||
|
.issuedAt(issued).expiresAt(expires).claim("id", id).claim("rol", role).claim("token_use", use)
|
||||||
|
.claim("sid", session.toString()).build();
|
||||||
|
return signer.encode(JwtEncoderParameters.from(JwsHeader.with(SignatureAlgorithm.RS256).keyId("test-auth").build(), claims)).getTokenValue();
|
||||||
|
}
|
||||||
|
String base() { return "http://localhost:" + environment.getProperty("local.server.port"); }
|
||||||
|
HttpResponse<String> request(String method, String path, Object body, String token) throws Exception {
|
||||||
|
var request = HttpRequest.newBuilder(URI.create(base() + path)).header("Content-Type", "application/json").timeout(Duration.ofSeconds(30));
|
||||||
|
if (token != null) request.header("Authorization", "Bearer " + token);
|
||||||
|
return http.send(request.method(method, body == null ? HttpRequest.BodyPublishers.noBody()
|
||||||
|
: HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body))).build(), HttpResponse.BodyHandlers.ofString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void clientHistoryIncludesCreationChangesAndState() throws Exception {
|
||||||
|
String admin=token(1,"admin");
|
||||||
|
assertThat(request("POST","/clients/create",createBody(),admin).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(request("PUT","/clients/update/6",Map.of("businessname","Corregido"),admin).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(request("PATCH","/clients/disable/6",null,admin).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events WHERE entity_type='client' AND entity_id=6").query(Integer.class).single()).isEqualTo(3);
|
||||||
|
assertThat(jdbc.sql("SELECT after_values->>'id_status' FROM business_audit_events WHERE action='client.disable'").query(String.class).single()).isEqualTo("8");
|
||||||
|
}
|
||||||
|
@Test void clientHistoryFailureRollsBackTheBusinessChange() throws Exception {
|
||||||
|
jdbc.sql("ALTER TABLE business_audit_events ADD CONSTRAINT reject_audit CHECK(action='never')").update();
|
||||||
|
try {
|
||||||
|
assertThat(request("PUT","/clients/update/1",Map.of("businessname","Corregido"),token(1,"admin")).statusCode()).isGreaterThanOrEqualTo(400);
|
||||||
|
assertThat(jdbc.sql("SELECT businessname FROM client WHERE id=1").query(String.class).single()).isNotEqualTo("Corregido");
|
||||||
|
} finally { jdbc.sql("ALTER TABLE business_audit_events DROP CONSTRAINT reject_audit").update(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
CREATE TABLE rol(id INTEGER PRIMARY KEY,name VARCHAR(255) NOT NULL);
|
||||||
|
INSERT INTO rol VALUES(1,'admin'),(2,'user'),(3,'supervisor');
|
||||||
|
CREATE TABLE users(id INTEGER PRIMARY KEY,name VARCHAR(255),lastname VARCHAR(255),acronym VARCHAR(255),
|
||||||
|
password VARCHAR(255),reset_token_hash VARCHAR(255),id_rol INTEGER NOT NULL REFERENCES rol(id),id_status INTEGER 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);
|
||||||
|
CREATE TABLE status(id INTEGER PRIMARY KEY,name VARCHAR(255));
|
||||||
|
INSERT INTO status VALUES(3,'Activo'),(8,'Deshabilitado'),(9,'Otro');
|
||||||
|
CREATE TABLE documenttype(id INTEGER PRIMARY KEY,name VARCHAR(255) NOT NULL,description VARCHAR(255) NOT NULL);
|
||||||
|
INSERT INTO documenttype VALUES(1,'Pasaporte','Documento internacional'),(2,'NIF','Identificacion fiscal');
|
||||||
|
CREATE TABLE client(id SERIAL PRIMARY KEY,identdocument INTEGER NOT NULL,businessname VARCHAR(255) NOT NULL,description VARCHAR(1000),
|
||||||
|
created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,updated TIMESTAMPTZ,id_status INTEGER NOT NULL DEFAULT 3 REFERENCES status(id),
|
||||||
|
id_documenttype INTEGER NOT NULL REFERENCES documenttype(id),id_recomended INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
UNIQUE(identdocument,id_documenttype));
|
||||||
|
CREATE TABLE cases(id INTEGER PRIMARY KEY,id_client INTEGER REFERENCES client(id),id_status INTEGER NOT NULL);
|
||||||
|
CREATE TABLE user_case(id SERIAL PRIMARY KEY,id_user INTEGER REFERENCES users(id),id_case INTEGER REFERENCES cases(id));
|
||||||
|
CREATE TABLE activities(id SERIAL PRIMARY KEY,id_case INTEGER REFERENCES cases(id),id_paytype INTEGER,amount DOUBLE PRECISION,payment BOOLEAN);
|
||||||
|
|
||||||
|
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);
|
||||||
Reference in New Issue
Block a user