@@ -0,0 +1,6 @@
|
|||||||
|
.git
|
||||||
|
.env
|
||||||
|
.secrets
|
||||||
|
target
|
||||||
|
.idea
|
||||||
|
.tools
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
root = true
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 4
|
||||||
|
[*.{yml,yaml,xml}]
|
||||||
|
indent_size = 2
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# La misma base que genesis_authv2. Este servicio NO crea ni modifica el esquema.
|
||||||
|
SERVER_PORT=8082
|
||||||
|
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-specialization:rate
|
||||||
|
REQUEST_LOG_ENABLED=true
|
||||||
|
|
||||||
|
# Solo al usar Docker. localhost dentro del contenedor no es tu ordenador.
|
||||||
|
DOCKER_DB_URL=jdbc:postgresql://host.docker.internal:5432/genesis_auth
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
* text=auto
|
||||||
|
mvnw text eol=lf
|
||||||
|
mvnw.cmd text eol=crlf
|
||||||
|
*.java text eol=lf
|
||||||
|
*.yml text eol=lf
|
||||||
|
*.sql text eol=lf
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
name: verify
|
||||||
|
on: [push, pull_request]
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
jobs:
|
||||||
|
verify:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: '25'
|
||||||
|
cache: maven
|
||||||
|
- run: bash ./mvnw -B -ntp verify
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/target/
|
||||||
|
/.tools/
|
||||||
|
/.secrets/
|
||||||
|
/.env
|
||||||
|
/.idea/
|
||||||
|
*.iml
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
wrapperVersion=3.3.4
|
||||||
|
distributionType=only-script
|
||||||
|
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip
|
||||||
|
distributionSha256Sum=0d7125e8c91097b36edb990ea5934e6c68b4440eef4ea96510a0f6815e7eeadb
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
FROM maven:3.9.11-eclipse-temurin-25 AS build
|
||||||
|
WORKDIR /build
|
||||||
|
COPY pom.xml .
|
||||||
|
COPY src src
|
||||||
|
RUN mvn -B -ntp -DskipTests package
|
||||||
|
|
||||||
|
FROM eclipse-temurin:25-jre
|
||||||
|
WORKDIR /app
|
||||||
|
RUN groupadd --system app && useradd --system --gid app app
|
||||||
|
COPY --from=build --chown=app:app /build/target/genesis-specialization-0.0.1-SNAPSHOT.jar app.jar
|
||||||
|
USER app
|
||||||
|
EXPOSE 8082
|
||||||
|
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
# Genesis Specialization Service — Java 25
|
||||||
|
|
||||||
|
Migración de `genesis_specializationService` a Java 25 y Spring Boot. Comparte PostgreSQL y la validación de tokens con `genesis_authv2` y `genesis_userv2`.
|
||||||
|
|
||||||
|
## Arrancar
|
||||||
|
|
||||||
|
Necesitas JDK 25 y la base PostgreSQL existente del auth. Desde `genesis_specializationv2` ejecuta:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
El script carga `.env` y utiliza el wrapper Maven incluido; la primera ejecución necesita internet para descargar dependencias. El puerto predeterminado es **8082**, por lo que puedes mantener el auth en 8080 y usuarios en 8081.
|
||||||
|
|
||||||
|
Abre **http://localhost:8082/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 la conexión, issuer, audiencia y CORS del auth. Revisa que apunte al entorno deseado. Para otra instalación, copia `.env.example` a `.env` y completa los valores. Si arrancas directamente desde el IDE o con `java -jar`, configura las variables de entorno allí: Spring no carga este `.env` por sí solo.
|
||||||
|
|
||||||
|
## Tabla necesaria
|
||||||
|
|
||||||
|
Se utiliza la tabla existente **`specialization`** con estas columnas:
|
||||||
|
|
||||||
|
| Columna | Tipo esperado |
|
||||||
|
| --- | --- |
|
||||||
|
| `id` | INTEGER, clave primaria autoincremental |
|
||||||
|
| `name` | VARCHAR, obligatorio |
|
||||||
|
|
||||||
|
Solo se requieren `id` y `name`. No necesitas añadir columnas de estado ni fechas y no hay que ejecutar un script de preparación para este servicio.
|
||||||
|
|
||||||
|
El servicio comprueba las columnas al arrancar y no modifica el esquema automáticamente. Tampoco crea otra base ni catálogos: necesita las tablas de usuarios, roles y sesiones existentes del auth. La comprobación de asociaciones usa `users.id_specialization`.
|
||||||
|
|
||||||
|
## Rutas conservadas
|
||||||
|
|
||||||
|
| Método | Ruta | Rol | Respuesta correcta |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| POST | `/specialization/create` | admin | 201, mensaje de creación |
|
||||||
|
| POST | `/specialization/update/{id}` | admin, user | 200, mensaje de edición |
|
||||||
|
| GET | `/specialization/disable/{id}` | admin | 200, eliminación física |
|
||||||
|
| GET | `/specialization/get/{id}` | admin, user | 200, `data.specialization` |
|
||||||
|
| GET | `/specialization/all` | admin | 200, `data.specializations` |
|
||||||
|
|
||||||
|
Se mantiene el formato `{ "data": ..., "status": "success" }` y, ante errores, `{ "data": { "message": "..." }, "status": "error" }`. Los registros inexistentes devuelven 404. Las consultas incluyen únicamente `id` y `name`.
|
||||||
|
|
||||||
|
Crear y actualizar solo aceptan `name`: se recortan los espacios exteriores y debe tener entre 1 y 120 caracteres. Los campos desconocidos y los valores NULL se rechazan.
|
||||||
|
|
||||||
|
La ruta `/disable/{id}` conserva el método GET para compatibilidad con el frontend, pero ahora **borra físicamente la fila**. Solo un administrador puede utilizarla. Si hay usuarios asociados a la especialización se devuelve **409** y se conservan tanto la especialización como las asociaciones. Otras referencias protegidas por claves foráneas también impiden el borrado. La comprobación y el borrado se realizan dentro de una transacción; no se ejecutan borrados en cascada desde el servicio.
|
||||||
|
|
||||||
|
Se conserva que **el rol user puede actualizar el nombre de cualquier especialización**. El listado incluye todas las especializaciones existentes, ordenadas por nombre.
|
||||||
|
|
||||||
|
## Autenticación y seguridad
|
||||||
|
|
||||||
|
Obtén un access token iniciando sesión en `genesis_authv2` y envíalo en cada petición:
|
||||||
|
|
||||||
|
```http
|
||||||
|
Authorization: Bearer <access-token-del-auth>
|
||||||
|
```
|
||||||
|
|
||||||
|
La configuración predeterminada utiliza **RS256** y solo la clave pública del auth en `.secrets/public.pem`; la actual se ha copiado. Nunca necesita la clave privada. Al rotar las claves del auth, actualiza esta copia.
|
||||||
|
|
||||||
|
`DB_URL`, `DB_USER`, `DB_PASSWORD`, `JWT_ISSUER` y `JWT_AUDIENCE` deben coincidir con el entorno del auth. `JWT_CHECK_SESSION=true` comprueba `sid`, vencimiento y revocación en `auth_session`. También se comprueba que el usuario exista, no esté en estado 2 y conserve el rol del token. El refresh token se utiliza solo con el auth.
|
||||||
|
|
||||||
|
Existe un modo de transición explícito para auth Node: `JWT_ALGORITHM=HS256`, el mismo `TOKEN_SECRET` de al menos 32 bytes y `JWT_CHECK_SESSION=false` si ese emisor no genera `sid`. Exige issuer, audiencia, `iat`, `exp`, `id` y `rol`. Desactivar la comprobación de sesiones pierde la revocación inmediata basada en ellas. Las pruebas de integración utilizan RS256.
|
||||||
|
|
||||||
|
Incluye consultas parametrizadas, transacciones, validación de entradas, CORS con orígenes explícitos, cabeceras de seguridad, identificador de petición y cuerpo máximo de 1 MiB. El límite predeterminado es 300 peticiones por IP cada 60 segundos. `REDIS_URL` permite compartir el límite entre instancias; sin Redis o si falla se usa memoria local. No se confía automáticamente en cabeceras de proxy: configura proxies confiables antes de habilitarlas en un despliegue que los necesite.
|
||||||
|
|
||||||
|
No se han trasladado los auxiliares sin uso de correo, Excel o Socket.IO. Este servicio no gestiona contraseñas ni envía correos.
|
||||||
|
|
||||||
|
## Organización
|
||||||
|
|
||||||
|
| Ubicación | Responsabilidad |
|
||||||
|
| --- | --- |
|
||||||
|
| `SpecializationsApplication.java` | Arranque y comprobación de conexión y columnas. |
|
||||||
|
| `api/SpecializationController.java` | Las cinco rutas HTTP. |
|
||||||
|
| `api/SpecializationDtos.java` | Entradas, validación y respuestas. |
|
||||||
|
| `api/ApiException*` | Respuestas JSON de error. |
|
||||||
|
| `api/HealthController.java` | Comprobación pública `/health`. |
|
||||||
|
| `service/SpecializationService.java` | Operaciones y transacciones. |
|
||||||
|
| `repository/SpecializationRepository.java` | Consultas SQL. |
|
||||||
|
| `config/` | JWT, permisos, CORS, límites y configuración. |
|
||||||
|
| `src/main/resources/application.yml` | Configuración de Spring mediante variables. |
|
||||||
|
| `src/test/` | Pruebas de integración con PostgreSQL aislado. |
|
||||||
|
|
||||||
|
## Verificación y Docker
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1 -Verify
|
||||||
|
```
|
||||||
|
|
||||||
|
Las pruebas utilizan PostgreSQL 18 con Testcontainers y necesitan Docker funcionando. También puedes definir `TEST_DB_URL`, `TEST_DB_USER` y `TEST_DB_PASSWORD` para una base de pruebas: se crea y elimina un esquema temporal exclusivo. No uses una base de producción.
|
||||||
|
|
||||||
|
Las diez pruebas de integración cubren las cinco rutas, permisos, contratos con solo `id` y `name`, validación, edición, borrado físico, bloqueo del borrado con usuarios asociados, JWT RS256, sesiones revocadas o vencidas, CORS y límite del cuerpo. Se han ejecutado con Java 25 y PostgreSQL aislado. No se ha modificado la base real ni probado un servidor Redis real.
|
||||||
|
|
||||||
|
Se incluyen `Dockerfile`, `compose.yml` y una configuración de CI. Para Docker configura `DOCKER_DB_URL` con una dirección accesible desde el contenedor y conserva la clave pública disponible:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker compose up --build -d
|
||||||
|
```
|
||||||
|
|
||||||
|
El contenedor usa un usuario sin privilegios y monta solo la clave pública. No levanta otra base ni aplica cambios al esquema. `.env`, `.secrets` y artefactos locales están excluidos del control de versiones y de la imagen.
|
||||||
|
|
||||||
|
|
||||||
|
## Historial de negocio
|
||||||
|
|
||||||
|
Las operaciones de escritura generan eventos transaccionales. La consulta de administradores se realiza en Reporting mediante `GET /reporting/audit`. Antes de desplegar, instala el esquema del historial desde Auth. Consulta [activacion, API y contrato](../genesis_authv2/docs/business-audit.md).
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
services:
|
||||||
|
specializations:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${SERVER_PORT:-8082}:8082"
|
||||||
|
environment:
|
||||||
|
SERVER_PORT: 8082
|
||||||
|
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-specialization:rate}
|
||||||
|
REQUEST_LOG_ENABLED: ${REQUEST_LOG_ENABLED:-true}
|
||||||
|
volumes:
|
||||||
|
- ./.secrets:/run/keys:ro
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp:size=64m
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: [no-new-privileges:true]
|
||||||
|
restart: unless-stopped
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
# Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
# or more contributor license agreements. See the NOTICE file
|
||||||
|
# distributed with this work for additional information
|
||||||
|
# regarding copyright ownership. The ASF licenses this file
|
||||||
|
# to you under the Apache License, Version 2.0 (the
|
||||||
|
# "License"); you may not use this file except in compliance
|
||||||
|
# with the License. You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing,
|
||||||
|
# software distributed under the License is distributed on an
|
||||||
|
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
# KIND, either express or implied. See the License for the
|
||||||
|
# specific language governing permissions and limitations
|
||||||
|
# under the License.
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
# Apache Maven Wrapper startup batch script, version 3.3.4
|
||||||
|
#
|
||||||
|
# Optional ENV vars
|
||||||
|
# -----------------
|
||||||
|
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||||
|
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||||
|
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||||
|
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
set -euf
|
||||||
|
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||||
|
|
||||||
|
# OS specific support.
|
||||||
|
native_path() { printf %s\\n "$1"; }
|
||||||
|
case "$(uname)" in
|
||||||
|
CYGWIN* | MINGW*)
|
||||||
|
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||||
|
native_path() { cygpath --path --windows "$1"; }
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# set JAVACMD and JAVACCMD
|
||||||
|
set_java_home() {
|
||||||
|
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||||
|
if [ -n "${JAVA_HOME-}" ]; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||||
|
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||||
|
else
|
||||||
|
JAVACMD="$JAVA_HOME/bin/java"
|
||||||
|
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||||
|
|
||||||
|
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||||
|
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||||
|
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD="$(
|
||||||
|
'set' +e
|
||||||
|
'unset' -f command 2>/dev/null
|
||||||
|
'command' -v java
|
||||||
|
)" || :
|
||||||
|
JAVACCMD="$(
|
||||||
|
'set' +e
|
||||||
|
'unset' -f command 2>/dev/null
|
||||||
|
'command' -v javac
|
||||||
|
)" || :
|
||||||
|
|
||||||
|
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||||
|
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# hash string like Java String::hashCode
|
||||||
|
hash_string() {
|
||||||
|
str="${1:-}" h=0
|
||||||
|
while [ -n "$str" ]; do
|
||||||
|
char="${str%"${str#?}"}"
|
||||||
|
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||||
|
str="${str#?}"
|
||||||
|
done
|
||||||
|
printf %x\\n $h
|
||||||
|
}
|
||||||
|
|
||||||
|
verbose() { :; }
|
||||||
|
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||||
|
|
||||||
|
die() {
|
||||||
|
printf %s\\n "$1" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
trim() {
|
||||||
|
# MWRAPPER-139:
|
||||||
|
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||||
|
# Needed for removing poorly interpreted newline sequences when running in more
|
||||||
|
# exotic environments such as mingw bash on Windows.
|
||||||
|
printf "%s" "${1}" | tr -d '[:space:]'
|
||||||
|
}
|
||||||
|
|
||||||
|
scriptDir="$(dirname "$0")"
|
||||||
|
scriptName="$(basename "$0")"
|
||||||
|
|
||||||
|
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||||
|
while IFS="=" read -r key value; do
|
||||||
|
case "${key-}" in
|
||||||
|
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||||
|
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||||
|
esac
|
||||||
|
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||||
|
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||||
|
|
||||||
|
case "${distributionUrl##*/}" in
|
||||||
|
maven-mvnd-*bin.*)
|
||||||
|
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||||
|
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||||
|
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||||
|
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||||
|
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||||
|
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||||
|
*)
|
||||||
|
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||||
|
distributionPlatform=linux-amd64
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||||
|
;;
|
||||||
|
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||||
|
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||||
|
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||||
|
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||||
|
distributionUrlName="${distributionUrl##*/}"
|
||||||
|
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||||
|
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||||
|
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||||
|
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||||
|
|
||||||
|
exec_maven() {
|
||||||
|
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||||
|
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ -d "$MAVEN_HOME" ]; then
|
||||||
|
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||||
|
exec_maven "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
|
case "${distributionUrl-}" in
|
||||||
|
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||||
|
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# prepare tmp dir
|
||||||
|
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||||
|
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||||
|
trap clean HUP INT TERM EXIT
|
||||||
|
else
|
||||||
|
die "cannot create temp dir"
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||||
|
|
||||||
|
# Download and Install Apache Maven
|
||||||
|
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||||
|
verbose "Downloading from: $distributionUrl"
|
||||||
|
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||||
|
|
||||||
|
# select .zip or .tar.gz
|
||||||
|
if ! command -v unzip >/dev/null; then
|
||||||
|
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||||
|
distributionUrlName="${distributionUrl##*/}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# verbose opt
|
||||||
|
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||||
|
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||||
|
|
||||||
|
# normalize http auth
|
||||||
|
case "${MVNW_PASSWORD:+has-password}" in
|
||||||
|
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||||
|
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||||
|
verbose "Found wget ... using wget"
|
||||||
|
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||||
|
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||||
|
verbose "Found curl ... using curl"
|
||||||
|
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||||
|
elif set_java_home; then
|
||||||
|
verbose "Falling back to use Java to download"
|
||||||
|
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||||
|
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||||
|
cat >"$javaSource" <<-END
|
||||||
|
public class Downloader extends java.net.Authenticator
|
||||||
|
{
|
||||||
|
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||||
|
{
|
||||||
|
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||||
|
}
|
||||||
|
public static void main( String[] args ) throws Exception
|
||||||
|
{
|
||||||
|
setDefault( new Downloader() );
|
||||||
|
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
END
|
||||||
|
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||||
|
verbose " - Compiling Downloader.java ..."
|
||||||
|
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||||
|
verbose " - Running Downloader.java ..."
|
||||||
|
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||||
|
if [ -n "${distributionSha256Sum-}" ]; then
|
||||||
|
distributionSha256Result=false
|
||||||
|
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||||
|
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||||
|
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||||
|
exit 1
|
||||||
|
elif command -v sha256sum >/dev/null; then
|
||||||
|
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
|
||||||
|
distributionSha256Result=true
|
||||||
|
fi
|
||||||
|
elif command -v shasum >/dev/null; then
|
||||||
|
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||||
|
distributionSha256Result=true
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||||
|
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ $distributionSha256Result = false ]; then
|
||||||
|
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||||
|
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# unzip and move
|
||||||
|
if command -v unzip >/dev/null; then
|
||||||
|
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||||
|
else
|
||||||
|
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||||
|
actualDistributionDir=""
|
||||||
|
|
||||||
|
# First try the expected directory name (for regular distributions)
|
||||||
|
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
|
||||||
|
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
|
||||||
|
actualDistributionDir="$distributionUrlNameMain"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||||
|
if [ -z "$actualDistributionDir" ]; then
|
||||||
|
# enable globbing to iterate over items
|
||||||
|
set +f
|
||||||
|
for dir in "$TMP_DOWNLOAD_DIR"/*; do
|
||||||
|
if [ -d "$dir" ]; then
|
||||||
|
if [ -f "$dir/bin/$MVN_CMD" ]; then
|
||||||
|
actualDistributionDir="$(basename "$dir")"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
set -f
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "$actualDistributionDir" ]; then
|
||||||
|
verbose "Contents of $TMP_DOWNLOAD_DIR:"
|
||||||
|
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
|
||||||
|
die "Could not find Maven distribution directory in extracted archive"
|
||||||
|
fi
|
||||||
|
|
||||||
|
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||||
|
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
|
||||||
|
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||||
|
|
||||||
|
clean || :
|
||||||
|
exec_maven "$@"
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
<# : batch portion
|
||||||
|
@REM ----------------------------------------------------------------------------
|
||||||
|
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
@REM or more contributor license agreements. See the NOTICE file
|
||||||
|
@REM distributed with this work for additional information
|
||||||
|
@REM regarding copyright ownership. The ASF licenses this file
|
||||||
|
@REM to you under the Apache License, Version 2.0 (the
|
||||||
|
@REM "License"); you may not use this file except in compliance
|
||||||
|
@REM with the License. You may obtain a copy of the License at
|
||||||
|
@REM
|
||||||
|
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@REM
|
||||||
|
@REM Unless required by applicable law or agreed to in writing,
|
||||||
|
@REM software distributed under the License is distributed on an
|
||||||
|
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
@REM KIND, either express or implied. See the License for the
|
||||||
|
@REM specific language governing permissions and limitations
|
||||||
|
@REM under the License.
|
||||||
|
@REM ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@REM ----------------------------------------------------------------------------
|
||||||
|
@REM Apache Maven Wrapper startup batch script, version 3.3.4
|
||||||
|
@REM
|
||||||
|
@REM Optional ENV vars
|
||||||
|
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||||
|
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||||
|
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||||
|
@REM ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||||
|
@SET __MVNW_CMD__=
|
||||||
|
@SET __MVNW_ERROR__=
|
||||||
|
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||||
|
@SET PSModulePath=
|
||||||
|
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||||
|
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||||
|
)
|
||||||
|
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||||
|
@SET __MVNW_PSMODULEP_SAVE=
|
||||||
|
@SET __MVNW_ARG0_NAME__=
|
||||||
|
@SET MVNW_USERNAME=
|
||||||
|
@SET MVNW_PASSWORD=
|
||||||
|
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
|
||||||
|
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||||
|
@GOTO :EOF
|
||||||
|
: end batch / begin powershell #>
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
if ($env:MVNW_VERBOSE -eq "true") {
|
||||||
|
$VerbosePreference = "Continue"
|
||||||
|
}
|
||||||
|
|
||||||
|
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||||
|
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||||
|
if (!$distributionUrl) {
|
||||||
|
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||||
|
}
|
||||||
|
|
||||||
|
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||||
|
"maven-mvnd-*" {
|
||||||
|
$USE_MVND = $true
|
||||||
|
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||||
|
$MVN_CMD = "mvnd.cmd"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
default {
|
||||||
|
$USE_MVND = $false
|
||||||
|
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||||
|
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||||
|
if ($env:MVNW_REPOURL) {
|
||||||
|
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||||
|
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
|
||||||
|
}
|
||||||
|
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||||
|
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||||
|
|
||||||
|
$MAVEN_M2_PATH = "$HOME/.m2"
|
||||||
|
if ($env:MAVEN_USER_HOME) {
|
||||||
|
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
|
||||||
|
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
$MAVEN_WRAPPER_DISTS = $null
|
||||||
|
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
|
||||||
|
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
|
||||||
|
} else {
|
||||||
|
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
|
||||||
|
}
|
||||||
|
|
||||||
|
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
|
||||||
|
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||||
|
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||||
|
|
||||||
|
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||||
|
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||||
|
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||||
|
exit $?
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||||
|
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||||
|
}
|
||||||
|
|
||||||
|
# prepare tmp dir
|
||||||
|
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||||
|
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||||
|
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||||
|
trap {
|
||||||
|
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||||
|
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||||
|
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||||
|
|
||||||
|
# Download and Install Apache Maven
|
||||||
|
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||||
|
Write-Verbose "Downloading from: $distributionUrl"
|
||||||
|
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||||
|
|
||||||
|
$webclient = New-Object System.Net.WebClient
|
||||||
|
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||||
|
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||||
|
}
|
||||||
|
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||||
|
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||||
|
|
||||||
|
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||||
|
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||||
|
if ($distributionSha256Sum) {
|
||||||
|
if ($USE_MVND) {
|
||||||
|
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||||
|
}
|
||||||
|
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||||
|
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||||
|
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# unzip and move
|
||||||
|
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||||
|
|
||||||
|
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||||
|
$actualDistributionDir = ""
|
||||||
|
|
||||||
|
# First try the expected directory name (for regular distributions)
|
||||||
|
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
|
||||||
|
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
|
||||||
|
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
|
||||||
|
$actualDistributionDir = $distributionUrlNameMain
|
||||||
|
}
|
||||||
|
|
||||||
|
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||||
|
if (!$actualDistributionDir) {
|
||||||
|
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
|
||||||
|
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
|
||||||
|
if (Test-Path -Path $testPath -PathType Leaf) {
|
||||||
|
$actualDistributionDir = $_.Name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$actualDistributionDir) {
|
||||||
|
Write-Error "Could not find Maven distribution directory in extracted archive"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||||
|
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||||
|
try {
|
||||||
|
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||||
|
} catch {
|
||||||
|
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||||
|
Write-Error "fail to move MAVEN_HOME"
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||||
|
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.0.8</version><relativePath/></parent>
|
||||||
|
<groupId>com.aellis</groupId><artifactId>genesis-specialization</artifactId><version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>Genesis Specialization Service</name>
|
||||||
|
<properties><java.version>25</java.version></properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webmvc</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-resource-server</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>runtime</scope></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
|
||||||
|
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency>
|
||||||
|
<dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers-postgresql</artifactId><scope>test</scope></dependency>
|
||||||
|
<dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers-junit-jupiter</artifactId><scope>test</scope></dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build><plugins>
|
||||||
|
<plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin>
|
||||||
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-failsafe-plugin</artifactId><executions><execution><goals><goal>integration-test</goal><goal>verify</goal></goals></execution></executions></plugin>
|
||||||
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-enforcer-plugin</artifactId><version>3.6.2</version><executions><execution><goals><goal>enforce</goal></goals><configuration><rules><requireJavaVersion><version>[25,26)</version></requireJavaVersion></rules></configuration></execution></executions></plugin>
|
||||||
|
</plugins></build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
param([switch]$Verify)
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$projectRoot = Split-Path -Parent $PSScriptRoot
|
||||||
|
Set-Location -LiteralPath $projectRoot
|
||||||
|
|
||||||
|
if (Test-Path -LiteralPath '.env') {
|
||||||
|
foreach ($line in [System.IO.File]::ReadAllLines((Join-Path $projectRoot '.env'), [System.Text.Encoding]::UTF8)) {
|
||||||
|
if ($line -match '^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$') {
|
||||||
|
$settingName = $Matches[1]
|
||||||
|
$settingValue = $Matches[2].Trim()
|
||||||
|
if ($settingValue.Length -ge 2) {
|
||||||
|
if (($settingValue.StartsWith('"') -and $settingValue.EndsWith('"')) -or
|
||||||
|
($settingValue.StartsWith("'") -and $settingValue.EndsWith("'"))) {
|
||||||
|
$settingValue = $settingValue.Substring(1, $settingValue.Length - 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[Environment]::SetEnvironmentVariable($settingName, $settingValue, 'Process')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Write-Host 'No existe .env. Se usarán las variables del proceso; consulta .env.example.'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(Get-Command java -ErrorAction SilentlyContinue)) {
|
||||||
|
if ($env:JAVA_HOME -and (Test-Path -LiteralPath (Join-Path $env:JAVA_HOME 'bin/java.exe'))) {
|
||||||
|
$env:PATH = "$env:JAVA_HOME\bin;$env:PATH"
|
||||||
|
} else {
|
||||||
|
throw 'No se encuentra Java. Instala JDK 25 o configura JAVA_HOME.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($Verify) { & (Join-Path $projectRoot 'mvnw.cmd') verify }
|
||||||
|
else { & (Join-Path $projectRoot 'mvnw.cmd') spring-boot:run }
|
||||||
|
exit $LASTEXITCODE
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.aellis.specializations;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@ConfigurationPropertiesScan
|
||||||
|
public class SpecializationsApplication {
|
||||||
|
public static void main(String[] args) { SpringApplication.run(SpecializationsApplication.class, args); }
|
||||||
|
@Bean ApplicationRunner verifyDatabase(JdbcClient jdbc) {
|
||||||
|
return args -> {
|
||||||
|
jdbc.sql("SELECT 1").query(Integer.class).single();
|
||||||
|
jdbc.sql("SELECT id,name FROM specialization WHERE FALSE").query().listOfRows();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.aellis.specializations.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.specializations.api;
|
||||||
|
|
||||||
|
import com.aellis.specializations.api.SpecializationDtos.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.specializations.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("specialization_service_error type={}", error.getClass().getSimpleName());
|
||||||
|
return ResponseEntity.internalServerError().body(ApiResponse.fail("Internal server error."));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.aellis.specializations.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,31 @@
|
|||||||
|
package com.aellis.specializations.api;
|
||||||
|
|
||||||
|
import com.aellis.specializations.api.SpecializationDtos.*;
|
||||||
|
import com.aellis.specializations.service.SpecializationService;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/specialization")
|
||||||
|
public class SpecializationController {
|
||||||
|
private final SpecializationService service;
|
||||||
|
public SpecializationController(SpecializationService service) { this.service = service; }
|
||||||
|
@PostMapping("/create") @ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public ApiResponse<Message> create(@RequestBody Map<String, Object> body) {
|
||||||
|
service.create(SpecializationDtos.parse(body));
|
||||||
|
return ApiResponse.ok(new Message("Especializacion registrada exitosamente."));
|
||||||
|
}
|
||||||
|
@PostMapping("/update/{id}") public ApiResponse<Message> update(@PathVariable String id, @RequestBody Map<String, Object> body) {
|
||||||
|
service.update(SpecializationDtos.positiveId(id), SpecializationDtos.parse(body));
|
||||||
|
return ApiResponse.ok(new Message("Especializacion editada exitosamente."));
|
||||||
|
}
|
||||||
|
@GetMapping("/disable/{id}") public ApiResponse<Message> disable(@PathVariable String id) {
|
||||||
|
service.delete(SpecializationDtos.positiveId(id));
|
||||||
|
return ApiResponse.ok(new Message("Especializacion eliminada exitosamente."));
|
||||||
|
}
|
||||||
|
@GetMapping("/get/{id}") public ApiResponse<?> find(@PathVariable String id) {
|
||||||
|
return ApiResponse.ok(Map.of("specialization", service.find(SpecializationDtos.positiveId(id))));
|
||||||
|
}
|
||||||
|
@GetMapping("/all") public ApiResponse<?> all() { return ApiResponse.ok(Map.of("specializations", service.all())); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.aellis.specializations.api;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
public final class SpecializationDtos {
|
||||||
|
private SpecializationDtos() {}
|
||||||
|
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 Specialization(long id, String name) {}
|
||||||
|
public record Input(String name) {}
|
||||||
|
|
||||||
|
public static Input parse(Map<String, Object> body) {
|
||||||
|
if (body == null || !body.keySet().equals(Set.of("name")) || !(body.get("name") instanceof String value)) throw invalid();
|
||||||
|
String name = value.strip();
|
||||||
|
if (name.isEmpty() || name.length() > 120) throw invalid();
|
||||||
|
return new Input(name);
|
||||||
|
}
|
||||||
|
public static int positiveId(Object value) {
|
||||||
|
try {
|
||||||
|
double number = value instanceof Number n ? n.doubleValue() : value instanceof String s ? Double.parseDouble(s.strip()) : Double.NaN;
|
||||||
|
if (!Double.isFinite(number) || number <= 0 || number > Integer.MAX_VALUE || number != Math.rint(number)) throw invalid();
|
||||||
|
return (int) number;
|
||||||
|
} catch (NumberFormatException exception) { throw invalid(); }
|
||||||
|
}
|
||||||
|
private static ApiException invalid() { return new ApiException(400, "Invalid request."); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.aellis.specializations.audit;
|
||||||
|
|
||||||
|
import com.aellis.specializations.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.specializations.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","specializations").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,120 @@
|
|||||||
|
package com.aellis.specializations.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 SpecializationProperties properties;
|
||||||
|
private final Clock clock;
|
||||||
|
private final StringRedisTemplate redis;
|
||||||
|
private volatile long redisDisabledUntil;
|
||||||
|
public RequestFilter(SpecializationProperties properties, Clock clock, StringRedisTemplate redis) {
|
||||||
|
this.properties = properties; this.clock = clock; this.redis = redis;
|
||||||
|
}
|
||||||
|
synchronized Limit memoryLimit(String key) {
|
||||||
|
long now = clock.millis();
|
||||||
|
var window = memory.get(key);
|
||||||
|
if (window == null || window.resetAt() <= now) {
|
||||||
|
if (memory.size() >= properties.rateLimitMemoryMaxKeys()) {
|
||||||
|
memory.entrySet().removeIf(entry -> entry.getValue().resetAt() <= now);
|
||||||
|
if (memory.size() >= properties.rateLimitMemoryMaxKeys() && !memory.containsKey(key)) {
|
||||||
|
return new Limit(properties.rateLimitMax(), now + properties.rateLimitWindowMs(), false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window = new Window(1, now + properties.rateLimitWindowMs());
|
||||||
|
} else window = new Window(Math.min(window.count() + 1, properties.rateLimitMax() + 1L), window.resetAt());
|
||||||
|
memory.put(key, window);
|
||||||
|
return new Limit(window.count(), window.resetAt(), window.count() <= properties.rateLimitMax());
|
||||||
|
}
|
||||||
|
private Limit limit(String key) {
|
||||||
|
long now = clock.millis();
|
||||||
|
if (properties.redisUrl() != null && !properties.redisUrl().isBlank() && now >= redisDisabledUntil) {
|
||||||
|
try {
|
||||||
|
List<?> result = redis.execute(REDIS_SCRIPT, List.of(properties.rateLimitPrefix() + ":" + key), Long.toString(properties.rateLimitWindowMs()));
|
||||||
|
if (result != null && result.size() == 2) {
|
||||||
|
long count = ((Number) result.get(0)).longValue(); long ttl = ((Number) result.get(1)).longValue();
|
||||||
|
return new Limit(count, now + Math.max(ttl, 0), count <= properties.rateLimitMax());
|
||||||
|
}
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
redisDisabledUntil = now + properties.rateLimitRedisBackoffMs();
|
||||||
|
LoggerFactory.getLogger(getClass()).warn("redis_rate_limit_unavailable; using local limiter");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return memoryLimit(key);
|
||||||
|
}
|
||||||
|
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||||
|
throws ServletException, IOException {
|
||||||
|
String supplied = request.getHeader("X-Request-Id");
|
||||||
|
String requestId = supplied != null && supplied.matches("[A-Za-z0-9._:-]{1,128}") ? supplied : UUID.randomUUID().toString();
|
||||||
|
response.setHeader("X-Request-Id", requestId); response.setHeader("Cache-Control", "no-store");
|
||||||
|
response.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
|
||||||
|
response.setHeader("X-DNS-Prefetch-Control", "off");
|
||||||
|
if (properties.rateLimitMax() > 0) {
|
||||||
|
var limit = limit(request.getRemoteAddr());
|
||||||
|
response.setHeader("X-RateLimit-Limit", Integer.toString(properties.rateLimitMax()));
|
||||||
|
response.setHeader("X-RateLimit-Remaining", Long.toString(Math.max(0, properties.rateLimitMax() - limit.count())));
|
||||||
|
response.setHeader("X-RateLimit-Reset", Long.toString((limit.resetAt() + 999) / 1000));
|
||||||
|
if (!limit.allowed()) {
|
||||||
|
response.setHeader("Retry-After", Long.toString(Math.max(1, (limit.resetAt() - clock.millis() + 999) / 1000)));
|
||||||
|
error(response, 429, "Too many requests."); return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (request.getContentLengthLong() > MAX_BODY) { error(response, 413, "Request body too large."); return; }
|
||||||
|
long start = clock.millis();
|
||||||
|
try { chain.doFilter(new LimitedRequest(request), response); }
|
||||||
|
finally {
|
||||||
|
if (properties.requestLogEnabled()) LoggerFactory.getLogger(getClass()).info("request method={} path={} status={} durationMs={} requestId={}",
|
||||||
|
request.getMethod(), request.getServletPath(), response.getStatus(), clock.millis() - start, requestId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static void error(HttpServletResponse response, int status, String message) throws IOException {
|
||||||
|
response.setStatus(status); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json");
|
||||||
|
if (status == 401) response.setHeader("WWW-Authenticate", "Bearer");
|
||||||
|
response.getWriter().write("{\"data\":{\"message\":\"" + message + "\"},\"status\":\"error\"}");
|
||||||
|
}
|
||||||
|
@Bean FilterRegistrationBean<RequestFilter> disableDoubleRegistration() {
|
||||||
|
var registration = new FilterRegistrationBean<>(this); registration.setEnabled(false); return registration;
|
||||||
|
}
|
||||||
|
public static class BodyTooLargeException extends IOException {}
|
||||||
|
private static class LimitedRequest extends HttpServletRequestWrapper {
|
||||||
|
private ServletInputStream input;
|
||||||
|
LimitedRequest(HttpServletRequest request) { super(request); }
|
||||||
|
@Override public ServletInputStream getInputStream() throws IOException {
|
||||||
|
if (input == null) {
|
||||||
|
var original = super.getInputStream();
|
||||||
|
input = new ServletInputStream() {
|
||||||
|
long count;
|
||||||
|
private void check(int read) throws IOException { if (read > 0 && (count += read) > MAX_BODY) throw new BodyTooLargeException(); }
|
||||||
|
@Override public int read() throws IOException { int value = original.read(); check(value < 0 ? 0 : 1); return value; }
|
||||||
|
@Override public int read(byte[] bytes, int offset, int length) throws IOException { int value = original.read(bytes, offset, length); check(value); return value; }
|
||||||
|
@Override public boolean isFinished() { return original.isFinished(); }
|
||||||
|
@Override public boolean isReady() { return original.isReady(); }
|
||||||
|
@Override public void setReadListener(ReadListener listener) { original.setReadListener(listener); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return input;
|
||||||
|
}
|
||||||
|
@Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream(), java.nio.charset.StandardCharsets.UTF_8)); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package com.aellis.specializations.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(SpecializationProperties 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, SpecializationProperties 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, "/specialization/create").hasRole("ADMIN")
|
||||||
|
.requestMatchers(org.springframework.http.HttpMethod.POST, "/specialization/update/*").hasAnyRole("ADMIN", "USER")
|
||||||
|
.requestMatchers(org.springframework.http.HttpMethod.GET, "/specialization/disable/*", "/specialization/all").hasRole("ADMIN")
|
||||||
|
.requestMatchers(org.springframework.http.HttpMethod.GET, "/specialization/get/*").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(SpecializationProperties 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,22 @@
|
|||||||
|
package com.aellis.specializations.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("specializations")
|
||||||
|
public record SpecializationProperties(@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 SpecializationProperties {
|
||||||
|
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,32 @@
|
|||||||
|
package com.aellis.specializations.repository;
|
||||||
|
|
||||||
|
import com.aellis.specializations.api.SpecializationDtos.*;
|
||||||
|
import java.sql.*;
|
||||||
|
import java.util.*;
|
||||||
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public class SpecializationRepository {
|
||||||
|
private final JdbcClient jdbc;
|
||||||
|
public SpecializationRepository(JdbcClient jdbc) { this.jdbc = jdbc; }
|
||||||
|
public long create(String name) { return jdbc.sql("INSERT INTO specialization(name) VALUES(:name) RETURNING id").param("name", name).query(Long.class).single(); }
|
||||||
|
public int update(long id, Input input) {
|
||||||
|
return jdbc.sql("UPDATE specialization SET name=:name WHERE id=:id")
|
||||||
|
.param("name", input.name()).param("id", id).update();
|
||||||
|
}
|
||||||
|
public boolean lock(long id) { return jdbc.sql("SELECT id FROM specialization WHERE id=:id FOR UPDATE").param("id",id).query(Long.class).optional().isPresent(); }
|
||||||
|
public boolean assignedToUsers(long id) {
|
||||||
|
return jdbc.sql("SELECT EXISTS(SELECT 1 FROM users WHERE id_specialization=:id)").param("id",id).query(Boolean.class).single();
|
||||||
|
}
|
||||||
|
public int delete(long id) { return jdbc.sql("DELETE FROM specialization WHERE id=:id").param("id",id).update(); }
|
||||||
|
public Optional<Specialization> find(long id) {
|
||||||
|
return jdbc.sql("SELECT id,name FROM specialization WHERE id=:id").param("id", id).query(this::map).optional();
|
||||||
|
}
|
||||||
|
public List<Specialization> all() {
|
||||||
|
return jdbc.sql("SELECT id,name FROM specialization ORDER BY name ASC,id ASC").query(this::map).list();
|
||||||
|
}
|
||||||
|
private Specialization map(ResultSet rs, int row) throws SQLException {
|
||||||
|
return new Specialization(rs.getLong("id"), rs.getString("name"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.aellis.specializations.service;
|
||||||
|
|
||||||
|
import com.aellis.specializations.api.ApiException;
|
||||||
|
import com.aellis.specializations.audit.BusinessAudit;
|
||||||
|
import com.aellis.specializations.api.SpecializationDtos.*;
|
||||||
|
import com.aellis.specializations.repository.SpecializationRepository;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class SpecializationService {
|
||||||
|
private final SpecializationRepository repository;
|
||||||
|
private final BusinessAudit history;
|
||||||
|
public SpecializationService(SpecializationRepository repository,BusinessAudit history) { this.repository = repository; this.history=history; }
|
||||||
|
@Transactional public void create(Input input) { var context=history.context(); long id=repository.create(input.name());
|
||||||
|
history.change(context,"specialization.create","specialization",id,null,Map.of(),history.snapshot("specialization",id)); }
|
||||||
|
@Transactional public void update(long id, Input input) {
|
||||||
|
if(!repository.lock(id)) throw missing(); var context=history.context(); var before=history.snapshot("specialization",id);
|
||||||
|
if (repository.update(id, input) == 0) throw missing();
|
||||||
|
history.change(context,"specialization.update","specialization",id,null,before,history.snapshot("specialization",id)); }
|
||||||
|
@Transactional public void delete(long id) {
|
||||||
|
if (!repository.lock(id)) throw missing();
|
||||||
|
if (repository.assignedToUsers(id)) throw new ApiException(409,"No se puede eliminar la especializacion porque tiene usuarios asociados.");
|
||||||
|
var context=history.context(); var before=history.snapshot("specialization",id);
|
||||||
|
if (repository.delete(id)==0) throw missing();
|
||||||
|
history.change(context,"specialization.delete","specialization",id,null,before,Map.of());
|
||||||
|
}
|
||||||
|
public Specialization find(long id) { return repository.find(id).orElseThrow(SpecializationService::missing); }
|
||||||
|
public List<Specialization> all() { return repository.all(); }
|
||||||
|
private static ApiException missing() { return new ApiException(404, "No se encontro la especializacion."); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
spring:
|
||||||
|
application:
|
||||||
|
name: genesis-specialization
|
||||||
|
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:8082}
|
||||||
|
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
|
||||||
|
specializations:
|
||||||
|
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-specialization:rate}
|
||||||
|
redis-url: ${REDIS_URL:}
|
||||||
|
request-log-enabled: ${REQUEST_LOG_ENABLED:true}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
package com.aellis.specializations;
|
||||||
|
|
||||||
|
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", "specializations.request-log-enabled=false", "specializations.rate-limit-max=10000", "spring.data.redis.port=1"})
|
||||||
|
class SpecializationServiceIT {
|
||||||
|
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 = "specializations_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-users-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("specializations.public-key", () -> keyDirectory.resolve("public.pem").toUri().toString());
|
||||||
|
registry.add("specializations.jwt-algorithm", () -> "RS256");
|
||||||
|
registry.add("specializations.issuer", () -> "http://localhost:8080"); registry.add("specializations.audience", () -> "genesis-api");
|
||||||
|
registry.add("specializations.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 specialization,users RESTART IDENTITY CASCADE").update();
|
||||||
|
jdbc.sql("INSERT INTO users(id,id_rol,id_status) VALUES(1,1,1),(2,2,1),(3,2,2),(4,3,1)").update();
|
||||||
|
jdbc.sql("INSERT INTO specialization(name) VALUES('Zeta'),('Alfa')").update();
|
||||||
|
}
|
||||||
|
@Test void assignedSpecializationCannotBeDeleted() throws Exception {
|
||||||
|
jdbc.sql("UPDATE users SET id_specialization=1 WHERE id=2").update();
|
||||||
|
var result=request("GET","/specialization/disable/1",null,token(1,"admin"));
|
||||||
|
assertThat(result.statusCode()).isEqualTo(409);
|
||||||
|
assertThat(result.body()).contains("usuarios asociados");
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM specialization WHERE id=1").query(Integer.class).single()).isEqualTo(1);
|
||||||
|
assertThat(jdbc.sql("SELECT id_specialization FROM users WHERE id=2").query(Integer.class).single()).isEqualTo(1);
|
||||||
|
}
|
||||||
|
@Test void healthIsPublicAndEveryBusinessRouteRequiresAuthentication() throws Exception {
|
||||||
|
assertThat(request("GET", "/health", null, null).body()).contains("\"ok\":true");
|
||||||
|
assertThat(request("GET", "/actuator/health", null, null).statusCode()).isEqualTo(200);
|
||||||
|
for (String route : List.of("/all", "/get/1", "/disable/1"))
|
||||||
|
assertThat(request("GET", "/specialization" + route, null, null).statusCode()).isEqualTo(401);
|
||||||
|
for (String route : List.of("/create", "/update/1"))
|
||||||
|
assertThat(request("POST", "/specialization" + route, Map.of("name", "Test"), null).statusCode()).isEqualTo(401);
|
||||||
|
}
|
||||||
|
@Test void adminCreatesWith201AndRetainsDatabaseDefaults() throws Exception {
|
||||||
|
var response = request("POST", "/specialization/create", Map.of("name", " Nueva "), token(1,"admin"));
|
||||||
|
assertThat(response.statusCode()).isEqualTo(201);
|
||||||
|
assertThat(response.body()).contains("Especializacion registrada exitosamente.", "\"status\":\"success\"");
|
||||||
|
assertThat(jdbc.sql("SELECT name FROM specialization WHERE id=3").query(String.class).single()).isEqualTo("Nueva");
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='specialization'").query(Integer.class).single()).isEqualTo(2);
|
||||||
|
}
|
||||||
|
@Test void rolePermissionsMatchNodeIncludingRegularUserUpdate() throws Exception {
|
||||||
|
String user = token(2,"user");
|
||||||
|
assertThat(request("GET", "/specialization/get/1", null, user).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(request("POST", "/specialization/update/1", Map.of("name", " Renombrada "), user).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(jdbc.sql("SELECT name FROM specialization WHERE id=1").query(String.class).single()).isEqualTo("Renombrada");
|
||||||
|
assertThat(request("POST", "/specialization/create", Map.of("name","Denegada"), user).statusCode()).isEqualTo(403);
|
||||||
|
assertThat(request("GET", "/specialization/disable/1", null, user).statusCode()).isEqualTo(403);
|
||||||
|
assertThat(request("GET", "/specialization/all", null, user).statusCode()).isEqualTo(403);
|
||||||
|
assertThat(request("GET", "/specialization/get/1", null, token(4,"supervisor")).statusCode()).isEqualTo(403);
|
||||||
|
}
|
||||||
|
@Test void updateAndReadRequireOnlyIdAndName() throws Exception {
|
||||||
|
String admin = token(1,"admin");
|
||||||
|
assertThat(request("POST", "/specialization/update/1", Map.of("name","Beta"), admin).statusCode()).isEqualTo(200);
|
||||||
|
var response = request("GET", "/specialization/get/1", null, admin);
|
||||||
|
var item = json.readTree(response.body()).get("data").get("specialization");
|
||||||
|
assertThat(item.size()).isEqualTo(2);
|
||||||
|
assertThat(item.get("id").asInt()).isEqualTo(1);
|
||||||
|
assertThat(item.get("name").asString()).isEqualTo("Beta");
|
||||||
|
}
|
||||||
|
@Test void disablePhysicallyDeletesAndListsRemainSorted() throws Exception {
|
||||||
|
String admin = token(1,"admin");
|
||||||
|
var response = request("GET", "/specialization/disable/1", null, admin);
|
||||||
|
assertThat(response.statusCode()).isEqualTo(200);
|
||||||
|
assertThat(response.body()).contains("Especializacion eliminada exitosamente.");
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM specialization WHERE id=1").query(Integer.class).single()).isZero();
|
||||||
|
assertThat(request("GET","/specialization/get/1",null,admin).statusCode()).isEqualTo(404);
|
||||||
|
assertThat(request("GET","/specialization/disable/1",null,admin).statusCode()).isEqualTo(404);
|
||||||
|
var list = json.readTree(request("GET", "/specialization/all", null, admin).body()).get("data").get("specializations");
|
||||||
|
assertThat(list.size()).isEqualTo(1);
|
||||||
|
assertThat(list.get(0).get("name").asString()).isEqualTo("Alfa");
|
||||||
|
}
|
||||||
|
@Test void missingRecordsReturn404AcrossReadAndMutations() throws Exception {
|
||||||
|
String admin = token(1,"admin");
|
||||||
|
for (String route : List.of("/get/999", "/disable/999")) {
|
||||||
|
var response = request("GET", "/specialization"+route, null, admin);
|
||||||
|
assertThat(response.statusCode()).isEqualTo(404);
|
||||||
|
assertThat(response.body()).contains("No se encontro la especializacion.");
|
||||||
|
}
|
||||||
|
assertThat(request("POST", "/specialization/update/999", Map.of("name","Missing"), admin).statusCode()).isEqualTo(404);
|
||||||
|
}
|
||||||
|
@Test void strictValidationRejectsEmptyUnknownNullAndInvalidIds() throws Exception {
|
||||||
|
String admin = token(1,"admin");
|
||||||
|
for (var body : List.of(Map.of(), Map.of("name"," "), Map.of("name","a".repeat(121)), Map.of("name",25), Map.of("name","x","extra",1), Map.of("name","x","id_status",10)))
|
||||||
|
assertThat(request("POST", "/specialization/create", body, admin).statusCode()).isEqualTo(400);
|
||||||
|
for (var body : List.of(Map.of(), Map.of("id_status",10), Map.of("name","Beta","id_status",10), Map.of("name","Beta","updated","2026-01-01"), Map.of("extra",1)))
|
||||||
|
assertThat(request("POST", "/specialization/update/1", body, admin).statusCode()).isEqualTo(400);
|
||||||
|
var nullBody = new HashMap<String,Object>(); nullBody.put("name", null);
|
||||||
|
assertThat(request("POST", "/specialization/update/1", nullBody, admin).statusCode()).isEqualTo(400);
|
||||||
|
for (String id : List.of("abc","0","-1","1.5","2147483648"))
|
||||||
|
assertThat(request("GET", "/specialization/get/"+id, null, admin).statusCode()).isEqualTo(400);
|
||||||
|
}
|
||||||
|
@Test void invalidTokensDisabledUsersRevokedAndExpiredSessionsAreRejected() throws Exception {
|
||||||
|
String revoked = token(2,"user"); jdbc.sql("UPDATE auth_session SET revoked=TRUE").update();
|
||||||
|
assertThat(request("GET", "/specialization/get/1", null, revoked).statusCode()).isEqualTo(401);
|
||||||
|
assertThat(request("GET", "/specialization/get/1", null, token(3,"user")).statusCode()).isEqualTo(401);
|
||||||
|
assertThat(request("GET", "/specialization/all", null, token(2,"admin")).statusCode()).isEqualTo(401);
|
||||||
|
String expiredSession = token(2,"user"); jdbc.sql("UPDATE auth_session SET expires_at=CURRENT_TIMESTAMP-INTERVAL '1 day'").update();
|
||||||
|
assertThat(request("GET", "/specialization/get/1", null, expiredSession).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", "/specialization/get/1", null, jwt).statusCode()).isEqualTo(401);
|
||||||
|
}
|
||||||
|
String[] parts = token(1,"admin").split("\\.");
|
||||||
|
String tampered = parts[0]+"."+Base64.getUrlEncoder().withoutPadding().encodeToString("{\"id\":2}".getBytes())+"."+parts[2];
|
||||||
|
assertThat(request("GET", "/specialization/all", null, tampered).statusCode()).isEqualTo(401);
|
||||||
|
}
|
||||||
|
@Test void corsSecurityHeadersAndBodyLimitAreApplied() throws Exception {
|
||||||
|
var allowed = http.send(HttpRequest.newBuilder(URI.create(base()+"/specialization/all")).header("Origin","http://localhost:3000")
|
||||||
|
.header("Access-Control-Request-Method","GET").method("OPTIONS",HttpRequest.BodyPublishers.noBody()).build(),HttpResponse.BodyHandlers.ofString());
|
||||||
|
assertThat(allowed.statusCode()).isEqualTo(200);
|
||||||
|
assertThat(allowed.headers().firstValue("Access-Control-Allow-Origin")).hasValue("http://localhost:3000");
|
||||||
|
var blocked = http.send(HttpRequest.newBuilder(URI.create(base()+"/specialization/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);
|
||||||
|
var health = request("GET","/health",null,null);
|
||||||
|
assertThat(health.headers().firstValue("Cache-Control")).hasValue("no-store");
|
||||||
|
assertThat(health.headers().firstValue("X-Request-Id")).isPresent();
|
||||||
|
assertThat(request("POST","/specialization/create",Map.of("name","x".repeat(1024*1024+1)),token(1,"admin")).statusCode()).isEqualTo(413);
|
||||||
|
}
|
||||||
|
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");
|
||||||
|
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 auditRetainsDeletedSpecializationAndSkipsUnchangedUpdates() throws Exception {
|
||||||
|
String admin=token(1,"admin");
|
||||||
|
assertThat(request("POST","/specialization/update/1",Map.of("name","Nueva"),admin).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(request("POST","/specialization/update/1",Map.of("name","Nueva"),admin).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(request("GET","/specialization/disable/1",null,admin).statusCode()).isEqualTo(200);
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events WHERE entity_id=1").query(Integer.class).single()).isEqualTo(2);
|
||||||
|
assertThat(jdbc.sql("SELECT before_values->>'name' FROM business_audit_events WHERE action='specialization.delete'").query(String.class).single()).isEqualTo("Nueva");
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM specialization WHERE id=1").query(Integer.class).single()).isZero();
|
||||||
|
}
|
||||||
|
@Test void specializationAuditFailureRollsBackDeletion() throws Exception {
|
||||||
|
jdbc.sql("ALTER TABLE business_audit_events ADD CONSTRAINT reject_audit CHECK(action='never')").update();
|
||||||
|
try {
|
||||||
|
assertThat(request("GET","/specialization/disable/1",null,token(1,"admin")).statusCode()).isGreaterThanOrEqualTo(400);
|
||||||
|
assertThat(jdbc.sql("SELECT count(*) FROM specialization WHERE id=1").query(Integer.class).single()).isEqualTo(1);
|
||||||
|
} finally { jdbc.sql("ALTER TABLE business_audit_events DROP CONSTRAINT reject_audit").update(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
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, 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 specialization(id SERIAL PRIMARY KEY,name VARCHAR(255) NOT NULL);
|
||||||
|
ALTER TABLE users ADD COLUMN id_specialization INTEGER REFERENCES specialization(id);
|
||||||
|
|
||||||
|
CREATE TABLE business_audit_events (
|
||||||
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
occurred_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
service VARCHAR(40) NOT NULL,
|
||||||
|
action VARCHAR(80) NOT NULL,
|
||||||
|
entity_type VARCHAR(40) NOT NULL,
|
||||||
|
entity_id BIGINT NOT NULL,
|
||||||
|
actor_id BIGINT NOT NULL,
|
||||||
|
actor_name VARCHAR(600) NOT NULL,
|
||||||
|
case_id BIGINT,
|
||||||
|
before_values JSONB NOT NULL,
|
||||||
|
after_values JSONB NOT NULL,
|
||||||
|
reason VARCHAR(500),
|
||||||
|
operation_id UUID NOT NULL,
|
||||||
|
request_id VARCHAR(128),
|
||||||
|
format_version INTEGER NOT NULL DEFAULT 1 CHECK (format_version=1)
|
||||||
|
);
|
||||||
|
CREATE INDEX business_audit_entity_idx ON business_audit_events(entity_type,entity_id,id DESC);
|
||||||
|
CREATE INDEX business_audit_case_idx ON business_audit_events(case_id,id DESC);
|
||||||
|
CREATE INDEX business_audit_actor_idx ON business_audit_events(actor_id,id DESC);
|
||||||
|
CREATE INDEX business_audit_date_idx ON business_audit_events(occurred_at,id DESC);
|
||||||
|
CREATE INDEX business_audit_operation_idx ON business_audit_events(operation_id,id);
|
||||||
Reference in New Issue
Block a user