first commit
verify / verify (push) Canceled after 0s

This commit is contained in:
2026-10-23 15:30:54 +02:00
commit 7c0f58373d
30 changed files with 1936 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
.git
.env
.secrets
target
.idea
.tools
+10
View File
@@ -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
+29
View File
@@ -0,0 +1,29 @@
# La misma base que genesis_authv2. Este servicio NO crea ni modifica el esquema.
SERVER_PORT=8084
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-case: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
+6
View File
@@ -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
+15
View File
@@ -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
+8
View File
@@ -0,0 +1,8 @@
/target/
/.tools/
/.secrets/
/.env
/.idea/
*.iml
*.log
.DS_Store
+4
View File
@@ -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
View File
@@ -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-case-0.0.1-SNAPSHOT.jar app.jar
USER app
EXPOSE 8084
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
+108
View File
@@ -0,0 +1,108 @@
# Genesis Case Service — Java 25
Migración de `genesis_caseService` a Java 25 y Spring Boot. Comparte PostgreSQL y autenticación con los otros servicios Java.
## Arranque
Necesitas JDK 25 y la base existente del Node y del auth. Desde `genesis_casev2`:
```powershell
powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1
```
El script carga `.env` y arranca en **http://localhost:8084**. La primera ejecución necesita internet para descargar Maven y dependencias. Abre **http://localhost:8084/health** para comprobar que responde `{"ok":true}`. `/actuator/health` comprueba también PostgreSQL. Detén el proceso con `Ctrl+C`.
El `.env` local se ha preparado con los valores compartidos del auth. Revisa el entorno de destino. Para otra instalación, copia `.env.example` a `.env` y completa sus 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 nuevas columnas ni un script de preparación. Se utilizan las tablas existentes `cases`, `user_case`, `client`, `users`, `status`, `rol` y `auth_session`. `cases` necesita los campos del modelo Node: `id`, `name`, `description`, `created`, `updated`, `id_status`, `id_created`, `id_client`. De `user_case` solo se utilizan `id_user` e `id_case`, por lo que puede tener clave compuesta o un `id` adicional.
El arranque verifica el esquema sin modificarlo. Una base nueva con solo las tablas iniciales del auth todavía no tiene este dominio: utiliza la base existente del Node. El esquema de `src/test/resources` es exclusivo para pruebas. No se ha modificado la base real.
## Autenticación
Inicia sesión en el auth y envía su access token:
```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 su clave privada. Al rotar claves, actualiza esta copia. La conexión, `JWT_ISSUER` y `JWT_AUDIENCE` deben coincidir con el entorno del auth. Se valida 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.
Existe el modo de transición explícito HS256 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 utilizan RS256.
## Rutas conservadas
Se mantienen las 15 combinaciones de método y ruta, incluidos los nombres `assing` y `unassing`. Las respuestas correctas usan HTTP 200 y `{ "data": ..., "status": "success" }`; los errores incluyen `data.message` y `status: "error"`.
| Método | Ruta | Permiso |
| --- | --- | --- |
| POST | `/cases/create` | admin; devuelve mensaje e `id_case` |
| PUT | `/cases/update/{id}` | admin |
| GET, PATCH | `/cases/disable/{id}` | admin |
| GET | `/cases/all` | admin: activos; user: activos asignados |
| GET | `/cases/get/{id}` | admin o user asignado |
| GET | `/cases/all/notfilter` | todos los estados; user sigue limitado a sus asignaciones |
| GET | `/cases/assing/{id}` | admin o el propio usuario |
| POST | `/cases/assing` | admin; lote de asignaciones |
| POST | `/cases/unassing` | admin |
| GET | `/cases/client/assing` | clientes de las asignaciones del usuario autenticado, también para admin |
| GET | `/cases/client/case/assing/{id}` | casos activos propios asignados para ese cliente |
| GET | `/cases/client/{id}` | admin; casos activos del cliente |
| GET | `/cases/case/assing/{id}` | admin; usuarios activos asignados |
| GET | `/cases/case/unassing/{id}` | admin; usuarios activos disponibles |
Crear requiere `name` e `id_client`; admite `description` nullable e `id_status`, predeterminado 4. Nombre y descripción tienen un máximo de 255 caracteres; el nombre no puede estar en blanco. Se rechazan campos desconocidos y se validan cliente y estado. Se guarda el administrador autenticado como `id_created`, sin permitir suplantarlo. Actualizar acepta los mismos campos de forma parcial y establece `updated`.
Se conservan las vistas con el cliente anidado y el formato de `/assing/{id}` con `id_user` y `case`. Las listas de usuarios solo exponen `id`, `name`, `lastname` y `acronym`. Para mantener el contrato Node, un admin que consulta un ID inexistente mediante `/get/{id}` recibe 200 con `case:null`; un user sin asignación recibe 404. Actualizar o desactivar un caso inexistente devuelve 404.
## Asignaciones y bajas
`POST /cases/assing` recibe entre 1 y 100 objetos:
```json
[
{ "id_user": 2, "id_case": 10 },
{ "id_user": 3, "id_case": 10 }
]
```
Solo se asignan usuarios activos (estado 1) a casos activos (estado 4). Se eliminan duplicados del cuerpo y se omiten asociaciones existentes. Cualquier error revierte el lote completo. Los bloqueos de PostgreSQL evitan duplicados entre peticiones concurrentes del servicio, incluso sin un índice UNIQUE sobre el par.
`POST /cases/unassing` recibe un solo objeto con `id_user` e `id_case`; si no existe la asignación, devuelve 404.
Desactivar cambia el caso al estado **7** y retira todas sus asignaciones dentro de una transacción. Editar `id_status` a 7 hace la misma limpieza. **No borra el caso, sus actividades, sus abonos ni los datos facturados.** Si falla la limpieza, se revierte también el estado. Reactivar no restaura asignaciones automáticamente.
El GET de baja se conserva por compatibilidad. Las respuestas llevan `Cache-Control: no-store`. Las mutaciones se auditan en logs después del commit con actor y request ID, sin añadir tablas de auditoría. No se han trasladado auxiliares sin uso de correo ni contraseñas.
## Integración con actividades
Se ha actualizado `genesis_activityv2` para reconocer `user_case`: un admin, el creador del caso o un usuario asignado puede acceder a sus actividades según los permisos de las rutas. Retirar la asignación elimina ese permiso en la siguiente petición; el permiso independiente por creador se conserva. Los informes personales siguen limitados al creador de la actividad y los abonos siguen siendo exclusivos de admin.
Actividades necesita ahora también la tabla `user_case` existente. Reinicia ese servicio para aplicar el cambio. Los bloqueos de caso coordinan sus escrituras con las asignaciones y bajas. No mantengas el Node y Java escribiendo asignaciones simultáneamente ni modifiques las tablas directamente si necesitas estas garantías.
## Organización y pruebas
`api/CaseController.java` recibe las rutas; `CaseDtos.java` valida cuerpos y define respuestas; `service/CaseService.java` aplica permisos y transacciones; `repository/CaseRepository.java` contiene SQL; `config/` contiene JWT, CORS y límites. `CasesApplication.java` arranca y verifica tablas. Los errores se convierten a JSON en `ApiExceptionHandler.java`.
Incluye cuerpo máximo de 1 MiB, CORS con orígenes explícitos, cabeceras de seguridad, request ID y límite predeterminado de 300 peticiones por IP cada 60 segundos. Redis es opcional para compartir el límite; si falla, se usa memoria local. No se confía automáticamente en cabeceras de proxy.
```powershell
powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1 -Verify
```
Por defecto las pruebas necesitan Docker para levantar PostgreSQL 18 con Testcontainers. Alternativamente 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 **17 pruebas de casos y 33 de actividades**, incluidas concurrencia, revocación del acceso por asignación, pagos y tarifas históricas. No se han utilizado datos reales ni un servidor Redis real.
Se incluyen Maven Wrapper, CI, Dockerfile y Compose. Para Docker configura `DOCKER_DB_URL` accesible 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 se excluyen 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
View File
@@ -0,0 +1,33 @@
services:
cases:
build: .
ports:
- "127.0.0.1:${SERVER_PORT:-8084}:8084"
environment:
SERVER_PORT: 8084
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-case: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
Vendored
+295
View File
@@ -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 "$@"
Vendored
+189
View File
@@ -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"
+27
View File
@@ -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-case</artifactId><version>0.0.1-SNAPSHOT</version>
<name>Genesis Case 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>
+33
View File
@@ -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,22 @@
package com.aellis.cases;
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 CasesApplication {
public static void main(String[] args) { SpringApplication.run(CasesApplication.class,args); }
@Bean ApplicationRunner verifyDatabase(JdbcClient jdbc) {
return args -> {
jdbc.sql("SELECT id,name,description,created,updated,id_created,id_client,id_status FROM cases WHERE FALSE").query().listOfRows();
jdbc.sql("SELECT id_user,id_case FROM user_case WHERE FALSE").query().listOfRows();
jdbc.sql("SELECT id,identdocument,businessname,id_documenttype FROM client WHERE FALSE").query().listOfRows();
jdbc.sql("SELECT id,name,lastname,acronym,id_status FROM users WHERE FALSE").query().listOfRows();
jdbc.sql("SELECT id FROM status WHERE FALSE").query().listOfRows();
};
}
}
@@ -0,0 +1,7 @@
package com.aellis.cases.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,31 @@
package com.aellis.cases.api;
import com.aellis.cases.api.CaseDtos.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() {
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.cases.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("case_service_error type={}", error.getClass().getSimpleName());
return ResponseEntity.internalServerError().body(ApiResponse.fail("Internal server error."));
}
}
@@ -0,0 +1,46 @@
package com.aellis.cases.api;
import com.aellis.cases.api.CaseDtos.*;
import com.aellis.cases.repository.CaseRepository;
import com.aellis.cases.service.CaseService;
import jakarta.servlet.http.HttpServletResponse;
import java.util.*;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/cases")
public class CaseController {
private final CaseService cases;
public CaseController(CaseService cases) { this.cases=cases; }
@PostMapping("/create") public ApiResponse<?> create(@AuthenticationPrincipal Jwt jwt,@RequestBody Payload body,HttpServletResponse response) {
int id=cases.create(who(jwt),CaseDtos.parse(body,true),requestId(response));
return ApiResponse.ok(Map.of("message","Caso registrado exitosamente.","id_case",id));
}
@PutMapping("/update/{id}") public ApiResponse<?> update(@AuthenticationPrincipal Jwt jwt,@PathVariable String id,@RequestBody Payload body,HttpServletResponse response) {
cases.update(who(jwt),CaseDtos.positiveId(id),CaseDtos.parse(body,false),requestId(response)); return message("Caso editado exitosamente.");
}
@RequestMapping(value="/disable/{id}",method={RequestMethod.GET,RequestMethod.PATCH})
public ApiResponse<?> disable(@AuthenticationPrincipal Jwt jwt,@PathVariable String id,HttpServletResponse response) {
cases.disable(who(jwt),CaseDtos.positiveId(id),requestId(response)); return message("Caso eliminado exitosamente.");
}
@GetMapping("/all") public ApiResponse<?> all(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("cases",cases.all(who(jwt),true))); }
@GetMapping("/all/notfilter") public ApiResponse<?> allNotFilter(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("cases",cases.all(who(jwt),false))); }
@GetMapping("/get/{id}") public ApiResponse<?> find(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(CaseRepository.map("case",cases.find(who(jwt),CaseDtos.positiveId(id)))); }
@GetMapping("/assing/{id}") public ApiResponse<?> assigned(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("cases",cases.assigned(who(jwt),CaseDtos.positiveId(id)))); }
@PostMapping("/assing") public ApiResponse<?> assign(@AuthenticationPrincipal Jwt jwt,@RequestBody List<Payload> body,HttpServletResponse response) {
cases.assign(who(jwt),CaseDtos.assignments(body),requestId(response)); return message("Casos asignados exitosamente.");
}
@PostMapping("/unassing") public ApiResponse<?> unassign(@AuthenticationPrincipal Jwt jwt,@RequestBody Payload body,HttpServletResponse response) {
cases.unassign(who(jwt),CaseDtos.assignment(body),requestId(response)); return message("Caso desasignado exitosamente.");
}
@GetMapping("/client/assing") public ApiResponse<?> clients(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("clients",cases.clients(who(jwt)))); }
@GetMapping("/client/case/assing/{id}") public ApiResponse<?> assignedByClient(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("cases",cases.assignedByClient(who(jwt),CaseDtos.positiveId(id)))); }
@GetMapping("/client/{id}") public ApiResponse<?> byClient(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("cases",cases.byClient(who(jwt),CaseDtos.positiveId(id)))); }
@GetMapping("/case/assing/{id}") public ApiResponse<?> users(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("users",cases.users(who(jwt),CaseDtos.positiveId(id),true))); }
@GetMapping("/case/unassing/{id}") public ApiResponse<?> otherUsers(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("users",cases.users(who(jwt),CaseDtos.positiveId(id),false))); }
private static Requester who(Jwt jwt) { return new Requester(Integer.parseInt(jwt.getClaimAsString("id")),jwt.getClaimAsString("rol")); }
private static String requestId(HttpServletResponse response) { return response.getHeader("X-Request-Id"); }
private static ApiResponse<Message> message(String text) { return ApiResponse.ok(new Message(text)); }
}
@@ -0,0 +1,49 @@
package com.aellis.cases.api;
import java.util.*;
public final class CaseDtos {
private CaseDtos() {}
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 record Assignment(int userId,int caseId) {}
public static class Payload extends LinkedHashMap<String,Object> {
@Override public String toString() { return "[case request body redacted]"; }
}
public static Input parse(Map<String,Object> body,boolean creating) {
if (body==null || body.isEmpty() || !Set.of("name","description","id_client","id_status").containsAll(body.keySet())
|| (creating && !body.keySet().containsAll(Set.of("name","id_client")))) throw invalid();
var fields = new LinkedHashMap<String,Object>();
for (var entry:body.entrySet()) {
String key=entry.getKey(); Object raw=entry.getValue();
if (key.startsWith("id_")) fields.put(key,positiveId(raw));
else if (key.equals("description") && raw==null) fields.put(key,null);
else {
if (!(raw instanceof String value) || value.length()>255 || (key.equals("name") && value.isBlank())) throw invalid();
fields.put(key,value);
}
}
return new Input(Collections.unmodifiableMap(fields));
}
public static Assignment assignment(Map<String,Object> body) {
if (body==null || !body.keySet().equals(Set.of("id_user","id_case"))) throw invalid();
return new Assignment(positiveId(body.get("id_user")),positiveId(body.get("id_case")));
}
public static List<Assignment> assignments(List<Payload> body) {
if (body==null || body.isEmpty() || body.size()>100) throw invalid();
return body.stream().map(CaseDtos::assignment).distinct().toList();
}
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.cases.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.cases.audit;
import com.aellis.cases.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.cases.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","cases").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.cases.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("cases")
public record CaseProperties(@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 CaseProperties {
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.cases.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 CaseProperties properties;
private final Clock clock;
private final StringRedisTemplate redis;
private volatile long redisDisabledUntil;
public RequestFilter(CaseProperties 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,109 @@
package com.aellis.cases.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(CaseProperties 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, CaseProperties 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, "/cases/create", "/cases/assing", "/cases/unassing").hasRole("ADMIN")
.requestMatchers(org.springframework.http.HttpMethod.PUT, "/cases/update/*").hasRole("ADMIN")
.requestMatchers(org.springframework.http.HttpMethod.PATCH, "/cases/disable/*").hasRole("ADMIN")
.requestMatchers(org.springframework.http.HttpMethod.GET, "/cases/client/assing").hasAnyRole("ADMIN", "USER")
.requestMatchers(org.springframework.http.HttpMethod.GET, "/cases/disable/*", "/cases/client/*", "/cases/case/assing/*", "/cases/case/unassing/*").hasRole("ADMIN")
.requestMatchers(org.springframework.http.HttpMethod.GET, "/cases/all", "/cases/get/*", "/cases/assing/*", "/cases/all/notfilter", "/cases/client/case/assing/*").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(CaseProperties 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,107 @@
package com.aellis.cases.repository;
import com.aellis.cases.api.CaseDtos.*;
import java.sql.*;
import java.util.*;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;
@Repository
public class CaseRepository {
private static final String FIELDS="ca.id,ca.name,ca.description,ca.created,ca.updated,ca.id_status,ca.id_created,ca.id_client";
private static final String CLIENT="cl.id AS client_id,cl.identdocument,cl.businessname,cl.id_documenttype";
private static final String JOIN=" LEFT JOIN client cl ON cl.id=ca.id_client";
private static final String ASSIGNED="EXISTS(SELECT 1 FROM user_case uc WHERE uc.id_case=ca.id AND uc.id_user=:viewer)";
private static final Set<String> WRITABLE=Set.of("name","description","id_client","id_status");
private final JdbcClient jdbc;
public CaseRepository(JdbcClient jdbc) { this.jdbc=jdbc; }
public boolean catalog(String field,int id) {
String table=switch(field) { case "id_client" -> "client"; 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 int create(Input input,int creator) {
var values=input.fields();
return jdbc.sql("""
INSERT INTO cases(name,description,id_client,id_status,id_created,created)
VALUES(:name,:description,:client,:status,:creator,CURRENT_TIMESTAMP) RETURNING id
""").param("name",values.get("name")).param("description",values.get("description")).param("client",values.get("id_client"))
.param("status",values.getOrDefault("id_status",4)).param("creator",creator).query(Integer.class).single();
}
public Optional<Integer> lock(int id) { return jdbc.sql("SELECT id_status FROM cases WHERE id=:id FOR UPDATE").param("id",id).query(Integer.class).optional(); }
public boolean lockActiveUser(int id) {
return jdbc.sql("SELECT id FROM users WHERE id=:id AND id_status=1 FOR SHARE").param("id",id).query(Integer.class).optional().isPresent();
}
public void update(int id,Map<String,Object> values) {
if (values.isEmpty() || !WRITABLE.containsAll(values.keySet())) throw new IllegalArgumentException("Invalid update");
String fields=String.join(",",values.keySet().stream().map(key -> key+"=:"+key).toList());
jdbc.sql("UPDATE cases SET "+fields+",updated=CURRENT_TIMESTAMP WHERE id=:target").params(values).param("target",id).update();
}
public List<Integer> assignmentUserIds(int id) { return jdbc.sql("SELECT DISTINCT id_user FROM user_case WHERE id_case=:id ORDER BY id_user").param("id",id).query(Integer.class).list(); }
public int clearAssignments(int id) { return jdbc.sql("DELETE FROM user_case WHERE id_case=:id").param("id",id).update(); }
public int unassign(Assignment item) { return jdbc.sql("DELETE FROM user_case WHERE id_user=:user AND id_case=:caseId").param("user",item.userId()).param("caseId",item.caseId()).update(); }
public int assign(Assignment item) {
return jdbc.sql("""
INSERT INTO user_case(id_user,id_case) SELECT :user,:caseId
WHERE NOT EXISTS(SELECT 1 FROM user_case WHERE id_user=:user AND id_case=:caseId)
""").param("user",item.userId()).param("caseId",item.caseId()).update();
}
public List<Map<String,Object>> list(Integer viewer,boolean activeOnly,boolean client,Integer clientId) {
String sql="SELECT "+FIELDS+(client?","+CLIENT:"")+" FROM cases ca"+(client?JOIN:"")+" WHERE TRUE";
if (activeOnly) sql+=" AND ca.id_status=4";
if (viewer!=null) sql+=" AND "+ASSIGNED;
if (clientId!=null) sql+=" AND ca.id_client=:clientId";
var query=jdbc.sql(sql+" ORDER BY ca.name ASC,ca.id ASC");
if (viewer!=null) query.param("viewer",viewer);
if (clientId!=null) query.param("clientId",clientId);
return query.query((rs,row) -> mapCase(rs,client)).list();
}
public boolean assigned(int user,int id) { return jdbc.sql("SELECT EXISTS(SELECT 1 FROM user_case WHERE id_user=:user AND id_case=:id)").param("user",user).param("id",id).query(Boolean.class).single(); }
public Optional<Map<String,Object>> find(int id) {
return jdbc.sql("SELECT "+FIELDS+","+CLIENT+" FROM cases ca"+JOIN+" WHERE ca.id=:id").param("id",id).query((rs,row) -> mapCase(rs,true)).optional();
}
public List<Map<String,Object>> assignedCases(int user) {
return jdbc.sql("SELECT ca.id,ca.name,ca.id_client,"+CLIENT+" FROM cases ca"+JOIN+" WHERE ca.id_status=4 AND "+ASSIGNED+" ORDER BY ca.name,ca.id")
.param("viewer",user).query((rs,row) -> {
var mini=map("id",rs.getInt("id"),"name",rs.getString("name"),"id_client",rs.getObject("id_client"),"client",mapClient(rs));
return map("id_user",user,"case",mini);
}).list();
}
public List<Map<String,Object>> assignedClients(int user) {
return rows("""
SELECT DISTINCT cl.id,cl.identdocument,cl.businessname,cl.id_documenttype FROM client cl
JOIN cases ca ON ca.id_client=cl.id JOIN user_case uc ON uc.id_case=ca.id
WHERE uc.id_user=:user ORDER BY cl.businessname,cl.id
""",Map.of("user",user));
}
public List<Map<String,Object>> assignedByClient(int user,int client) {
return rows("SELECT ca.id,ca.name FROM cases ca WHERE ca.id_status=4 AND ca.id_client=:client AND "+ASSIGNED+" ORDER BY ca.name,ca.id",Map.of("client",client,"viewer",user));
}
public List<Map<String,Object>> users(int caseId,boolean assigned) {
return rows("SELECT u.id,u.name,u.lastname,u.acronym FROM users u WHERE u.id_status=1 AND "+(assigned?"":"NOT ")
+"EXISTS(SELECT 1 FROM user_case uc WHERE uc.id_user=u.id AND uc.id_case=:id) ORDER BY u.name,u.id",Map.of("id",caseId));
}
private List<Map<String,Object>> rows(String sql,Map<String,Object> params) {
return jdbc.sql(sql).params(params).query((rs,row) -> {
var result=new LinkedHashMap<String,Object>(); var metadata=rs.getMetaData();
for(int i=1;i<=metadata.getColumnCount();i++) result.put(metadata.getColumnLabel(i),rs.getObject(i));
return (Map<String,Object>)result;
}).list();
}
private Map<String,Object> mapCase(ResultSet rs,boolean client) throws SQLException {
var item=new LinkedHashMap<String,Object>();
for(String field:List.of("id","name","description","created","updated","id_status","id_created","id_client")) {
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);
}
if(client) item.put("client",mapClient(rs));
return item;
}
private Map<String,Object> mapClient(ResultSet rs) throws SQLException {
return rs.getObject("client_id")==null?null:map("id",rs.getObject("client_id"),"identdocument",rs.getObject("identdocument"),"businessname",rs.getString("businessname"),"id_documenttype",rs.getObject("id_documenttype"));
}
public 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,75 @@
package com.aellis.cases.service;
import com.aellis.cases.api.*;
import com.aellis.cases.api.CaseDtos.*;
import com.aellis.cases.repository.CaseRepository;
import java.util.*;
import com.aellis.cases.audit.BusinessAudit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CaseService {
private final CaseRepository cases;
private final BusinessAudit history;
public CaseService(CaseRepository cases,BusinessAudit history) { this.cases=cases; this.history=history; }
@Transactional public int create(Requester who,Input input,String requestId) {
admin(who); var fields=new LinkedHashMap<>(input.fields()); fields.putIfAbsent("id_status",4); validate(fields);
var context=history.context(who.id(),requestId);
int id=cases.create(new Input(fields),who.id()); history.change(context,"case.create","case",id,id,Map.of(),history.snapshot("cases",id)); return id;
}
@Transactional public void update(Requester who,int id,Input input,String requestId) {
admin(who); cases.lock(id).orElseThrow(CaseService::missing); var context=history.context(who.id(),requestId);
var before=history.snapshot("cases",id); validate(input.fields()); cases.update(id,input.fields());
if(Integer.valueOf(7).equals(input.fields().get("id_status"))) clearAssignments(context,id);
history.change(context,"case.update","case",id,id,before,history.snapshot("cases",id));
}
@Transactional public void disable(Requester who,int id,String requestId) {
admin(who); cases.lock(id).orElseThrow(CaseService::missing); validate(Map.of("id_status",7));
var context=history.context(who.id(),requestId); var before=history.snapshot("cases",id);
cases.update(id,Map.of("id_status",7)); clearAssignments(context,id);
history.change(context,"case.disable","case",id,id,before,history.snapshot("cases",id));
}
@Transactional public void assign(Requester who,List<Assignment> items,String requestId) {
admin(who);
for(int id:items.stream().map(Assignment::userId).distinct().sorted().toList())
if(!cases.lockActiveUser(id)) throw new ApiException(400,"Usuarios inválidos.");
for(int id:items.stream().map(Assignment::caseId).distinct().sorted().toList())
if(cases.lock(id).orElse(-1)!=4) throw new ApiException(400,"Casos inválidos.");
var context=history.context(who.id(),requestId);
for(var item:items) if(cases.assign(item)>0) assignment(context,item,true);
}
@Transactional public void unassign(Requester who,Assignment item,String requestId) {
admin(who); cases.lock(item.caseId());
var context=history.context(who.id(),requestId);
if(cases.unassign(item)==0) throw new ApiException(404,"Asignación no encontrada.");
assignment(context,item,false);
}
public List<Map<String,Object>> all(Requester who,boolean active) { return cases.list(who.admin()?null:who.id(),active,active,null); }
public Map<String,Object> find(Requester who,int id) {
if(!who.admin() && !cases.assigned(who.id(),id)) throw missing();
return cases.find(id).orElse(null);
}
public List<Map<String,Object>> assigned(Requester who,int user) {
if(!who.admin() && who.id()!=user) throw new ApiException(403,"Forbidden."); return cases.assignedCases(user);
}
public List<Map<String,Object>> clients(Requester who) { return cases.assignedClients(who.id()); }
public List<Map<String,Object>> assignedByClient(Requester who,int client) { return cases.assignedByClient(who.id(),client); }
public List<Map<String,Object>> byClient(Requester who,int client) { admin(who); return cases.list(null,true,false,client); }
public List<Map<String,Object>> users(Requester who,int id,boolean assigned) { admin(who); return cases.users(id,assigned); }
private void validate(Map<String,Object> fields) {
if(fields.containsKey("id_client") && !cases.catalog("id_client",(Integer)fields.get("id_client"))) throw new ApiException(400,"Cliente inválido");
if(fields.containsKey("id_status") && !cases.catalog("id_status",(Integer)fields.get("id_status"))) throw new ApiException(400,"Estado inválido");
}
private static void admin(Requester who) { if(!who.admin()) throw new ApiException(403,"Forbidden."); }
private static ApiException missing() { return new ApiException(404,"Caso no encontrado"); }
private void clearAssignments(BusinessAudit.Context context,int id) {
for(int user:cases.assignmentUserIds(id)) assignment(context,new Assignment(user,id),false);
cases.clearAssignments(id);
}
private void assignment(BusinessAudit.Context context,Assignment item,boolean added) {
var values=Map.<String,Object>of("id_user",item.userId(),"id_case",item.caseId());
history.change(context,added?"case.assign":"case.unassign","assignment",item.caseId(),item.caseId(),
added?Map.of():values,added?values:Map.of());
}
}
+53
View File
@@ -0,0 +1,53 @@
spring:
application:
name: genesis-case
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:8084}
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
cases:
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-case:rate}
redis-url: ${REDIS_URL:}
request-log-enabled: ${REQUEST_LOG_ENABLED:true}
@@ -0,0 +1,336 @@
package com.aellis.cases;
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", "cases.request-log-enabled=false", "cases.rate-limit-max=10000", "cases.redis-url=", "cases.allowed-origins=http://localhost:3000", "spring.data.redis.port=1"})
class CaseServiceIT {
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 = "cases_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-cases-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("cases.public-key", () -> keyDirectory.resolve("public.pem").toUri().toString());
registry.add("cases.jwt-algorithm", () -> "RS256");
registry.add("cases.issuer", () -> "http://localhost:8080"); registry.add("cases.audience", () -> "genesis-api");
registry.add("cases.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,cases,user_case RESTART IDENTITY CASCADE").update();
jdbc.sql("INSERT INTO users VALUES(1,'Admin','Prueba','AD',1,1),(2,'Ana','Prueba','AN',2,1),(3,'Luis','Prueba','LU',2,1),(4,'Inactivo','Prueba','IN',2,2),(5,'Supervisor','Prueba','SU',3,1),(6,'Libre','Prueba','LI',2,1)").update();
jdbc.sql("INSERT INTO cases(id,name,id_client,id_status,id_created) VALUES(1,'Zeta',1,4,1),(2,'Alfa',2,4,3),(3,'Archivado',1,7,1),(4,'Beta',1,8,1)").update();
jdbc.sql("SELECT setval(pg_get_serial_sequence('cases','id'),4,TRUE)").query(Long.class).single();
jdbc.sql("INSERT INTO user_case(id_user,id_case) VALUES(2,1),(2,4),(3,2),(1,2)").update();
}
tools.jackson.databind.JsonNode data(HttpResponse<String> response) { return json.readTree(response.body()).get("data"); }
Map<String,Object> assignment(int user,int caseId) { return Map.of("id_user",user,"id_case",caseId); }
@Test void healthAndAllFifteenBusinessRoutesHaveExpectedAuthentication() 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("disable/1","all","get/1","assing/2","client/assing","client/case/assing/1","client/1","case/assing/1","case/unassing/1","all/notfilter"))
assertThat(request("GET","/cases/"+route,null,null).statusCode()).isEqualTo(401);
for(String route:List.of("create","assing","unassing")) assertThat(request("POST","/cases/"+route,Map.of(),null).statusCode()).isEqualTo(401);
assertThat(request("PUT","/cases/update/1",Map.of(),null).statusCode()).isEqualTo(401);
assertThat(request("PATCH","/cases/disable/1",null,null).statusCode()).isEqualTo(401);
}
@Test void adminCreatesWithDefaultsAndAuthenticatedCreatorAndReturnsId() throws Exception {
var response=request("POST","/cases/create",Map.of("name","Nuevo","description","Detalle","id_client","1"),token(1,"admin"));
assertThat(response.statusCode()).isEqualTo(200);
assertThat(data(response).get("id_case").asInt()).isEqualTo(5);
assertThat(response.body()).contains("Caso registrado exitosamente.");
assertThat(jdbc.sql("SELECT id_status=4 AND id_created=1 AND created IS NOT NULL FROM cases WHERE id=5").query(Boolean.class).single()).isTrue();
assertThat(request("POST","/cases/create",Map.of("name","Otro","id_client",2,"id_status",8),token(1,"admin")).statusCode()).isEqualTo(200);
assertThat(jdbc.sql("SELECT id_status FROM cases WHERE id=6").query(Integer.class).single()).isEqualTo(8);
}
@Test void strictValidationAndInvalidCatalogsProduce400WithoutWrites() throws Exception {
String admin=token(1,"admin");
for(var body:List.of(Map.of(),Map.of("name","Nuevo"),Map.of("name"," ","id_client",1),Map.of("name","x".repeat(256),"id_client",1),Map.of("name","x","id_client",999),Map.of("name","x","id_client",1,"id_status",999),Map.of("name","x","id_client",1,"id_created",3)))
assertThat(request("POST","/cases/create",body,admin).statusCode()).isEqualTo(400);
for(var body:List.of(Map.of(),Map.of("extra",1),Map.of("id_client",0),Map.of("id_status",1.5)))
assertThat(request("PUT","/cases/update/1",body,admin).statusCode()).isEqualTo(400);
var nullName=new HashMap<String,Object>(); nullName.put("name",null);
assertThat(request("PUT","/cases/update/1",nullName,admin).statusCode()).isEqualTo(400);
for(String id:List.of("0","abc","-1","1.5","2147483648")) assertThat(request("GET","/cases/get/"+id,null,admin).statusCode()).isEqualTo(400);
assertThat(jdbc.sql("SELECT count(*) FROM cases").query(Integer.class).single()).isEqualTo(4);
}
@Test void onlyAdminsCanMutateAndReadAdministrativeLists() throws Exception {
String user=token(2,"user");
assertThat(request("POST","/cases/create",Map.of("name","Nuevo","id_client",1),user).statusCode()).isEqualTo(403);
assertThat(request("PUT","/cases/update/1",Map.of("name","Cambio"),user).statusCode()).isEqualTo(403);
assertThat(request("POST","/cases/assing",List.of(assignment(2,2)),user).statusCode()).isEqualTo(403);
assertThat(request("POST","/cases/unassing",assignment(2,1),user).statusCode()).isEqualTo(403);
assertThat(request("PATCH","/cases/disable/1",null,user).statusCode()).isEqualTo(403);
for(String route:List.of("disable/1","client/1","case/assing/1","case/unassing/1"))
assertThat(request("GET","/cases/"+route,null,user).statusCode()).isEqualTo(403);
assertThat(request("GET","/cases/all",null,token(5,"supervisor")).statusCode()).isEqualTo(403);
}
@Test void usersSeeOnlyAssignmentsAndNonfilteredListDoesNotBypassPermissions() throws Exception {
String user=token(2,"user"),admin=token(1,"admin");
var all=data(request("GET","/cases/all",null,user)).get("cases");
assertThat(all.size()).isEqualTo(1); assertThat(all.get(0).get("id").asInt()).isEqualTo(1);
assertThat(all.get(0).get("client").get("identdocument").asInt()).isEqualTo(111);
assertThat(all.get(0).get("created").asString()).contains("T");
var unfiltered=data(request("GET","/cases/all/notfilter",null,user)).get("cases");
assertThat(unfiltered.size()).isEqualTo(2); assertThat(unfiltered.get(0).get("name").asString()).isEqualTo("Beta");
assertThat(unfiltered.get(0).has("client")).isFalse();
assertThat(data(request("GET","/cases/all/notfilter",null,admin)).get("cases").size()).isEqualTo(4);
assertThat(data(request("GET","/cases/all",null,admin)).get("cases").get(0).get("name").asString()).isEqualTo("Alfa");
assertThat(data(request("GET","/cases/all",null,token(6,"user"))).get("cases").size()).isZero();
}
@Test void detailHidesUnassignedCasesAndPreservesAdminNullContract() throws Exception {
String user=token(2,"user"),admin=token(1,"admin");
assertThat(data(request("GET","/cases/get/1",null,user)).get("case").get("id").asInt()).isEqualTo(1);
assertThat(request("GET","/cases/get/2",null,user).statusCode()).isEqualTo(404);
assertThat(request("GET","/cases/get/999",null,user).statusCode()).isEqualTo(404);
var missing=request("GET","/cases/get/999",null,admin);
assertThat(missing.statusCode()).isEqualTo(200); assertThat(data(missing).get("case").isNull()).isTrue();
assertThat(request("GET","/cases/get/4",null,user).statusCode()).isEqualTo(200);
}
@Test void updateIsPartialAndDisablingViaStatusAlsoClearsAssignments() throws Exception {
String admin=token(1,"admin"); var body=new LinkedHashMap<String,Object>(); body.put("name","Editado"); body.put("description",null);
assertThat(request("PUT","/cases/update/1",body,admin).statusCode()).isEqualTo(200);
assertThat(jdbc.sql("SELECT name='Editado' AND description IS NULL AND updated IS NOT NULL AND id_client=1 FROM cases WHERE id=1").query(Boolean.class).single()).isTrue();
assertThat(request("PUT","/cases/update/1",Map.of("id_client",999),admin).statusCode()).isEqualTo(400);
assertThat(request("PUT","/cases/update/999",Map.of("name","Nada"),admin).statusCode()).isEqualTo(404);
assertThat(request("PUT","/cases/update/1",Map.of("id_status",7),admin).statusCode()).isEqualTo(200);
assertThat(jdbc.sql("SELECT count(*) FROM user_case WHERE id_case=1").query(Integer.class).single()).isZero();
}
@Test void disablingIsAtomicAndPreservesActivitiesAndPayments() 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");
assertThat(request("PATCH","/cases/disable/1",null,admin).statusCode()).isEqualTo(200);
assertThat(jdbc.sql("SELECT id_status FROM cases WHERE id=1").query(Integer.class).single()).isEqualTo(7);
assertThat(jdbc.sql("SELECT count(*) FROM user_case WHERE id_case=1").query(Integer.class).single()).isZero();
assertThat(jdbc.sql("SELECT count(*) FROM activities WHERE id_case=1 AND id_status=5").query(Integer.class).single()).isEqualTo(2);
assertThat(jdbc.sql("SELECT payment FROM activities WHERE id_paytype=1").query(Boolean.class).single()).isTrue();
assertThat(request("GET","/cases/disable/2",null,admin).statusCode()).isEqualTo(200);
assertThat(request("GET","/cases/disable/999",null,admin).statusCode()).isEqualTo(404);
}
@Test void failedAssignmentCleanupRollsBackCaseStatus() throws Exception {
jdbc.sql("INSERT INTO assignment_reference(assignment_id) VALUES(1)").update();
assertThat(request("PATCH","/cases/disable/1",null,token(1,"admin")).statusCode()).isEqualTo(409);
assertThat(jdbc.sql("SELECT id_status FROM cases WHERE id=1").query(Integer.class).single()).isEqualTo(4);
assertThat(jdbc.sql("SELECT count(*) FROM user_case WHERE id_case=1").query(Integer.class).single()).isEqualTo(1);
}
@Test void assignmentBatchDeduplicatesAndValidatesEverythingBeforeInserting() throws Exception {
String admin=token(1,"admin"); var item=assignment(6,1);
assertThat(request("POST","/cases/assing",List.of(item,item,assignment(2,1)),admin).statusCode()).isEqualTo(200);
assertThat(request("POST","/cases/assing",List.of(item),admin).statusCode()).isEqualTo(200);
assertThat(jdbc.sql("SELECT count(*) FROM user_case WHERE id_user=6 AND id_case=1").query(Integer.class).single()).isEqualTo(1);
for(var invalid:List.of(assignment(4,1),assignment(999,1),assignment(6,3),assignment(6,999)))
assertThat(request("POST","/cases/assing",List.of(assignment(6,2),invalid),admin).statusCode()).isEqualTo(400);
assertThat(jdbc.sql("SELECT count(*) FROM user_case WHERE id_user=6 AND id_case=2").query(Integer.class).single()).isZero();
for(var invalid:List.of(List.of(),Collections.nCopies(101,item),List.of(Map.of("id_user",2,"id_case",1,"extra",1))))
assertThat(request("POST","/cases/assing",invalid,admin).statusCode()).isEqualTo(400);
}
@Test void assignmentQueriesPreserveNestedShapeAndRestrictOtherUsers() throws Exception {
String user=token(2,"user"),admin=token(1,"admin");
var list=data(request("GET","/cases/assing/2",null,user)).get("cases");
assertThat(list.size()).isEqualTo(1); assertThat(list.get(0).get("id_user").asInt()).isEqualTo(2);
assertThat(list.get(0).get("case").get("client").get("businessname").asString()).isEqualTo("Cliente uno");
assertThat(request("GET","/cases/assing/3",null,user).statusCode()).isEqualTo(403);
assertThat(data(request("GET","/cases/assing/3",null,admin)).get("cases").get(0).get("case").get("id").asInt()).isEqualTo(2);
assertThat(request("POST","/cases/unassing",assignment(2,1),admin).statusCode()).isEqualTo(200);
assertThat(request("GET","/cases/get/1",null,user).statusCode()).isEqualTo(404);
assertThat(request("POST","/cases/unassing",assignment(2,1),admin).statusCode()).isEqualTo(404);
}
@Test void clientQueriesUseAuthenticatedAssignmentsAndAdminQueriesStaySeparate() throws Exception {
String user=token(2,"user"),admin=token(1,"admin");
var clients=data(request("GET","/cases/client/assing",null,user)).get("clients");
assertThat(clients.size()).isEqualTo(1); assertThat(clients.get(0).get("id").asInt()).isEqualTo(1);
var adminClients=data(request("GET","/cases/client/assing",null,admin)).get("clients");
assertThat(adminClients.size()).isEqualTo(1); assertThat(adminClients.get(0).get("id").asInt()).isEqualTo(2);
assertThat(data(request("GET","/cases/client/case/assing/1",null,user)).get("cases").size()).isEqualTo(1);
assertThat(data(request("GET","/cases/client/case/assing/2",null,user)).get("cases").size()).isZero();
assertThat(data(request("GET","/cases/client/1",null,admin)).get("cases").size()).isEqualTo(1);
}
@Test void assignedAndAvailableUsersListsContainOnlyActivePublicFields() throws Exception {
String admin=token(1,"admin");
var assigned=data(request("GET","/cases/case/assing/1",null,admin)).get("users");
assertThat(assigned.size()).isEqualTo(1); assertThat(assigned.get(0).get("id").asInt()).isEqualTo(2);
assertThat(assigned.get(0).size()).isEqualTo(4);
var available=data(request("GET","/cases/case/unassing/1",null,admin)).get("users");
assertThat(available.size()).isEqualTo(4);
for(var item:available) assertThat(item.get("id").asInt()).isNotIn(2,4);
}
@Test void concurrentAssignmentsCannotCreateDuplicatesWithoutUniqueConstraint() throws Exception {
String admin=token(1,"admin");
try(var executor=java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
var jobs=new ArrayList<java.util.concurrent.Callable<Integer>>();
for(int i=0;i<8;i++) jobs.add(() -> request("POST","/cases/assing",List.of(assignment(6,1)),admin).statusCode());
for(var result:executor.invokeAll(jobs)) assertThat(result.get()).isEqualTo(200);
}
assertThat(jdbc.sql("SELECT count(*) FROM user_case WHERE id_user=6 AND id_case=1").query(Integer.class).single()).isEqualTo(1);
}
@Test void concurrentDisableAndAssignLeaveNoAssignmentsOnDisabledCase() throws Exception {
String admin=token(1,"admin");
try(var executor=java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
var assign=executor.submit(() -> request("POST","/cases/assing",List.of(assignment(6,1)),admin).statusCode());
var disable=executor.submit(() -> request("PATCH","/cases/disable/1",null,admin).statusCode());
assertThat(assign.get()).isIn(200,400); assertThat(disable.get()).isEqualTo(200);
}
assertThat(jdbc.sql("SELECT count(*) FROM user_case WHERE id_case=1").query(Integer.class).single()).isZero();
assertThat(jdbc.sql("SELECT id_status FROM cases WHERE id=1").query(Integer.class).single()).isEqualTo(7);
}
@Test void invalidJwtSessionRoleAndDisabledUsersAreRejected() throws Exception {
String revoked=token(2,"user"); jdbc.sql("UPDATE auth_session SET revoked=TRUE").update();
assertThat(request("GET","/cases/all",null,revoked).statusCode()).isEqualTo(401);
assertThat(request("GET","/cases/all",null,token(4,"user")).statusCode()).isEqualTo(401);
assertThat(request("GET","/cases/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","/cases/all",null,jwt).statusCode()).isEqualTo(401);
}
}
@Test void corsBodyLimitAndRequestIdsAreApplied() throws Exception {
var allowed=http.send(HttpRequest.newBuilder(URI.create(base()+"/cases/assing")).header("Origin","http://localhost:3000").header("Access-Control-Request-Method","POST")
.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()+"/cases/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","/cases/create",Map.of("name","x".repeat(1024*1024+1),"id_client",1),token(1,"admin")).statusCode()).isEqualTo(413);
assertThat(request("GET","/health",null,null).headers().firstValue("X-Request-Id")).isPresent();
}
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 businessHistoryContainsOnlyEffectiveChangesAndActor() throws Exception {
String admin=token(1,"admin");
assertThat(request("PUT","/cases/update/1",Map.of("name","Nuevo"),admin).statusCode()).isEqualTo(200);
assertThat(request("PUT","/cases/update/1",Map.of("name","Nuevo"),admin).statusCode()).isEqualTo(200);
var event=jdbc.sql("SELECT actor_id,actor_name,entity_id,case_id,before_values::text,after_values::text,request_id FROM business_audit_events").query().singleRow();
assertThat(((Number)event.get("actor_id")).longValue()).isEqualTo(1);
assertThat(event.get("actor_name")).isEqualTo("Admin Prueba");
assertThat(json.readTree((String)event.get("before_values")).get("name").asString()).isEqualTo("Zeta");
var after=json.readTree((String)event.get("after_values"));
assertThat(after.size()).isEqualTo(1); assertThat(after.get("name").asString()).isEqualTo("Nuevo");
assertThat(event.get("request_id")).isNotNull();
}
@Test void businessHistoryTracksIndividualAssignmentsAndAutomaticRemoval() throws Exception {
String admin=token(1,"admin");
assertThat(request("POST","/cases/assing",List.of(assignment(2,1),assignment(3,1),assignment(3,1)),admin).statusCode()).isEqualTo(200);
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events WHERE action='case.assign'").query(Integer.class).single()).isEqualTo(1);
assertThat(request("PATCH","/cases/disable/1",null,admin).statusCode()).isEqualTo(200);
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events WHERE action='case.unassign'").query(Integer.class).single()).isEqualTo(2);
assertThat(jdbc.sql("SELECT count(DISTINCT operation_id) FROM business_audit_events WHERE action IN ('case.disable','case.unassign')").query(Integer.class).single()).isEqualTo(1);
}
@Test void businessHistoryFailureRollsBackCaseAndAssignmentRemoval() throws Exception {
jdbc.sql("ALTER TABLE business_audit_events ADD CONSTRAINT reject_history CHECK(action='never')").update();
try {
assertThat(request("PATCH","/cases/disable/1",null,token(1,"admin")).statusCode()).isGreaterThanOrEqualTo(400);
assertThat(jdbc.sql("SELECT id_status FROM cases WHERE id=1").query(Integer.class).single()).isEqualTo(4);
assertThat(jdbc.sql("SELECT count(*) FROM user_case WHERE id_case=1").query(Integer.class).single()).isEqualTo(1);
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events").query(Integer.class).single()).isZero();
} finally { jdbc.sql("ALTER TABLE business_audit_events DROP CONSTRAINT reject_history").update(); }
}
@Test void businessHistoryRequiresTransactionAndDoesNotPersistFailedOperations() throws Exception {
var writer=new com.aellis.cases.audit.BusinessAudit(jdbc,json);
assertThatThrownBy(()->writer.context(1)).isInstanceOf(IllegalStateException.class);
assertThat(request("PUT","/cases/update/1",Map.of("id_client",999),token(1,"admin")).statusCode()).isEqualTo(400);
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events").query(Integer.class).single()).isZero();
}
@Test void concurrentCaseEditsHaveAContinuousBeforeAfterHistory() throws Exception {
String admin=token(1,"admin");
try(var executor=java.util.concurrent.Executors.newFixedThreadPool(2)) {
var first=executor.submit(()->request("PUT","/cases/update/1",Map.of("name","Primero"),admin));
var second=executor.submit(()->request("PUT","/cases/update/1",Map.of("name","Segundo"),admin));
assertThat(first.get().statusCode()).isEqualTo(200); assertThat(second.get().statusCode()).isEqualTo(200);
}
var rows=jdbc.sql("SELECT before_values->>'name' AS old_name,after_values->>'name' AS new_name FROM business_audit_events ORDER BY id").query().listOfRows();
assertThat(rows).hasSize(2); assertThat(rows.getFirst().get("old_name")).isEqualTo("Zeta");
assertThat(rows.get(1).get("old_name")).isEqualTo(rows.getFirst().get("new_name"));
assertThat(jdbc.sql("SELECT name FROM cases WHERE id=1").query(String.class).single()).isEqualTo(rows.getLast().get("new_name"));
}
@Test void auditReasonIsOptionalValidatedAndStoredWithTrustedMetadata() throws Exception {
String admin=token(1,"admin");
var builder=HttpRequest.newBuilder(URI.create("http://localhost:"+environment.getProperty("local.server.port")+"/cases/update/1"))
.header("Authorization","Bearer "+admin).header("Content-Type","application/json").header("X-Audit-Reason","Correccion")
.PUT(HttpRequest.BodyPublishers.ofString("{\"name\":\"Cambio\"}"));
assertThat(http.send(builder.build(),HttpResponse.BodyHandlers.ofString()).statusCode()).isEqualTo(200);
assertThat(jdbc.sql("SELECT reason FROM business_audit_events").query(String.class).single()).isEqualTo("Correccion");
assertThat(http.send(builder.setHeader("X-Audit-Reason","x".repeat(501)).build(),HttpResponse.BodyHandlers.ofString()).statusCode()).isEqualTo(400);
assertThat(http.send(builder.setHeader("X-Audit-Reason","con\tcontrol").build(),HttpResponse.BodyHandlers.ofString()).statusCode()).isEqualTo(400);
assertThat(http.send(builder.setHeader("X-Audit-Reason","primero").header("X-Audit-Reason","segundo").build(),HttpResponse.BodyHandlers.ofString()).statusCode()).isEqualTo(400);
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events").query(Integer.class).single()).isEqualTo(1);
}
}
+39
View File
@@ -0,0 +1,39 @@
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),
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 client(id INTEGER PRIMARY KEY,identdocument INTEGER,businessname VARCHAR(255),id_documenttype INTEGER);
INSERT INTO client VALUES(1,111,'Cliente uno',1),(2,222,'Cliente dos',1);
CREATE TABLE status(id INTEGER PRIMARY KEY,name VARCHAR(255));
INSERT INTO status VALUES(4,'Activo'),(7,'Desactivado'),(8,'Otro');
CREATE TABLE cases(id SERIAL PRIMARY KEY,name VARCHAR(255) NOT NULL,description VARCHAR(255),created TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMPTZ,id_status INTEGER NOT NULL DEFAULT 4 REFERENCES status(id),id_created INTEGER REFERENCES users(id),id_client INTEGER REFERENCES client(id));
-- Sin restriccion UNIQUE para comprobar que los bloqueos evitan duplicados dentro del servicio.
CREATE TABLE user_case(id SERIAL PRIMARY KEY,id_case INTEGER NOT NULL REFERENCES cases(id),id_user INTEGER NOT NULL REFERENCES users(id));
CREATE TABLE assignment_reference(id SERIAL PRIMARY KEY,assignment_id INTEGER REFERENCES user_case(id));
CREATE TABLE activities(id SERIAL PRIMARY KEY,id_case INTEGER REFERENCES cases(id),id_status INTEGER DEFAULT 5,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);