commit e5655656e6e831e156b717f408051f9537d3f045 Author: Aellis Tech Date: Fri Oct 23 15:35:39 2026 +0200 first commit diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..47c2760 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +.git +.env +.secrets +target +.idea +.tools diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..ef1277f --- /dev/null +++ b/.editorconfig @@ -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 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..1047d87 --- /dev/null +++ b/.env.example @@ -0,0 +1,34 @@ +# La misma base que genesis_authv2. Este servicio NO crea ni modifica el esquema. +SERVER_PORT=8081 +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 +AUTH_ALLOW_LEGACY_PASSWORDS=false +PASSWORD_MIN_LENGTH=10 +PASSWORD_MAX_LENGTH=128 +PASSWORD_MIN_CLASSES=3 +PASSWORD_REQUIRE_COMPLEXITY=true + +# 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-user: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 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d66d0d2 --- /dev/null +++ b/.gitattributes @@ -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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..06db7a5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..21e929a --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/target/ +/.tools/ +/.secrets/ +/.env +/.idea/ +*.iml +*.log +.DS_Store diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..222cba3 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -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 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..37aff05 --- /dev/null +++ b/Dockerfile @@ -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-user-0.0.1-SNAPSHOT.jar app.jar +USER app +EXPOSE 8081 +ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..0850f0b --- /dev/null +++ b/README.md @@ -0,0 +1,116 @@ +# Genesis User Service — Java 25 + +Migración de `genesis_userService` a Java 25 y Spring Boot, compatible con la base PostgreSQL y los tokens del proyecto `genesis_authv2`. + +## Arrancar en Windows + +Necesitas JDK 25, PostgreSQL disponible y la base existente preparada por el auth. Maven se descarga automáticamente con el wrapper; la primera ejecución necesita internet. + +Desde la carpeta `genesis_userv2`: + +```powershell +powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1 +``` + +El script carga `.env` y arranca el servicio en **http://localhost:8081**. Puedes tener el auth en el puerto 8080 al mismo tiempo. + +Comprueba que responde abriendo **http://localhost:8081/health**; devuelve `{"ok":true}`. También existe `/actuator/health`, que comprueba la conexión con PostgreSQL. Para detenerlo, pulsa `Ctrl+C`. + +El `.env` local se ha preparado con la conexión y los valores compartidos del auth. Revisa que correspondan al entorno que quieres utilizar. Para una instalación nueva, copia `.env.example` como `.env` y completa la conexión. El arranque directo desde el IDE o mediante `java -jar` necesita que configures las variables de entorno; Spring no carga este `.env` por sí solo. + +## Conexión con el auth + +- Ambos servicios deben apuntar a la misma base: `DB_URL`, `DB_USER` y `DB_PASSWORD`. +- El modo predeterminado es `JWT_ALGORITHM=RS256`. Este servicio solo necesita la **clave pública** del auth en `.secrets/public.pem`; se ha copiado la actual. Nunca necesita la clave privada. Si cambias las claves del auth, actualiza esta copia. +- `JWT_ISSUER` y `JWT_AUDIENCE` deben coincidir con los del auth. `JWT_MAX_AGE=15m` limita la antigüedad del token. +- `JWT_CHECK_SESSION=true` comprueba además la sesión `sid` en `auth_session`. Cerrar sesión, revocar una sesión o desactivar al usuario invalida su acceso. +- En cada petición autenticada se consulta que el usuario exista, no tenga estado 2 y conserve el rol del token. + +Inicia sesión en el auth y envía su **access token** en las peticiones a usuarios: + +```http +Authorization: Bearer +``` + +El refresh token se utiliza únicamente con el auth. + +Para una transición con el auth Node antiguo hay un modo explícito `JWT_ALGORITHM=HS256`: configura el mismo `TOKEN_SECRET` de al menos 32 bytes y `JWT_CHECK_SESSION=false` si ese auth no genera `sid`. El token debe tener `id`, `rol`, `iat`, `exp`, el issuer y la audiencia configurados. Esta opción pierde la comprobación de sesiones compartidas y no es la configuración predeterminada. Las pruebas de integración incluidas utilizan RS256. + +## Rutas conservadas + +Se mantienen las rutas del servicio Node y el formato de respuesta `{ "data": ..., "status": "success" }` o `"error"`. + +| Método | Ruta | Permiso | +| --- | --- | --- | +| POST | `/users/create` | admin | +| PUT | `/users/update/{id}` | admin o el propio usuario | +| DELETE | `/users/delete/{id}` | admin | +| PATCH | `/users/disable/{id}` | admin | +| GET | `/users/get/{id}` | admin o el propio usuario | +| GET | `/users/all` | admin; devuelve usuarios con estado 1 | +| GET | `/users/rol/all` | admin | + +Crear un usuario requiere `name`, `lastname`, `email`, `rate`, `acronym` y `password`. Acepta también `id_specialization`, `id_rol` e `id_status`; rol y estado predeterminados son 2 y 1. Los catálogos deben existir previamente. + +Actualizar acepta los mismos campos de forma parcial. Un usuario normal no puede cambiar `rate`, `id_specialization`, `id_rol` ni `id_status`. Para cambiar su contraseña debe enviar `current_password` y `password`. Un administrador puede restablecerla sin la anterior. Desactivar no necesita cuerpo, o acepta `{}`. + +Los resultados de consulta mantienen los nombres de campos y los nombres de los catálogos aplanados del Node. No se devuelven contraseñas ni tokens de recuperación. Crear, actualizar, borrar y desactivar conservan las respuestas de confirmación HTTP 200. + +## Cambios de seguridad + +Las contraseñas nuevas se guardan con Argon2, como en el auth Java. Se siguen verificando contraseñas bcrypt existentes. MD5 y texto plano solo se aceptan si habilitas expresamente `AUTH_ALLOW_LEGACY_PASSWORDS=true`, igual que en el auth. + +La política nueva coincide con el auth: mínimo 10 caracteres, máximo 128 y al menos tres clases entre minúsculas, mayúsculas, números y símbolos. El Node permitía un mínimo de 8. La política se configura mediante `PASSWORD_*`; usa los mismos valores en ambos servicios. + +Cambiar contraseña, email, rol o estado revoca las sesiones y los refresh tokens existentes y cancela recuperaciones pendientes. Desactivar también revoca el acceso. El borrado es físico, como en Node; si otros módulos tienen referencias que impiden borrarlo se devuelve 409 y se revierte la operación. + +Se validan los campos y sus límites, se rechazan campos desconocidos, se parametrizan las consultas SQL y se limita el cuerpo a 1 MiB. Hay CORS para orígenes explícitos, cabeceras de seguridad, identificador de petición y límite por IP. Los logs de aplicación no incluyen cuerpos, contraseñas o tokens; evita activar logs de depuración en producción. + +El límite predeterminado es 300 peticiones por IP cada 60 segundos. `REDIS_URL` permite compartirlo entre instancias; sin Redis o si falla se usa memoria local. No se confía automáticamente en `X-Forwarded-For`: si publicas detrás de un proxy, configura una política de proxies confiables antes de habilitar sus cabeceras. + +## Organización + +| Ubicación | Para qué sirve | +| --- | --- | +| `UsersApplication.java` | Arranca Spring Boot y comprueba la conexión inicial. | +| `api/UserController.java` | Recibe las siete rutas HTTP. | +| `api/UserDtos.java` | Valida las entradas y define las respuestas. | +| `api/ApiException*` | Convierte los errores en respuestas JSON. | +| `api/HealthController.java` | Expone `/health`. | +| `service/UserService.java` | Reglas de usuarios, permisos y transacciones. | +| `service/MigrationPasswordEncoder.java` | Verifica contraseñas existentes y genera los hashes nuevos. | +| `repository/UserRepository.java` | Consultas SQL a PostgreSQL. | +| `config/` | JWT, permisos, CORS, límites y configuración. | +| `src/main/resources/application.yml` | Conecta las variables de entorno con Spring. | +| `src/test/` | Pruebas de integración y esquema exclusivo para las pruebas. | + +No se han trasladado los auxiliares de correo, Excel y Socket.IO que no utilizaban estas rutas. Los correos de recuperación siguen siendo responsabilidad del auth. + +## Base de datos y pruebas + +Este servicio no crea ni migra tablas al arrancar. Utiliza `users`, `rol`, `specialization`, `status` y las tablas de sesiones del auth. No ejecutes contra una base vacía. Las columnas opcionales de recuperación se limpian cuando existen. + +Para verificar el proyecto: + +```powershell +powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1 -Verify +``` + +Por defecto, las pruebas levantan PostgreSQL 18 con Testcontainers y necesitan Docker funcionando. Como alternativa puedes definir `TEST_DB_URL`, `TEST_DB_USER` y `TEST_DB_PASSWORD` para una base de pruebas existente: se crea y elimina un esquema temporal exclusivo. No uses una base de producción para pruebas. + +Las 12 pruebas de integración cubren las siete rutas, permisos, contraseñas, revocación, validación de JWT RS256, CORS y límites del cuerpo. Se han ejecutado con PostgreSQL aislado y Java 25. No se ha modificado la base real ni se ha probado una conexión real a Redis. + +## Docker + +Se incluyen `Dockerfile` y `compose.yml`. Configura `DOCKER_DB_URL` para acceder a la base existente desde el contenedor y conserva `.secrets/public.pem` disponible: + +```powershell +docker compose up --build -d +``` + +No se levanta otra base ni se ejecutan migraciones. El contenedor utiliza un usuario sin privilegios. El `.env`, las claves y los artefactos locales están excluidos del control de versiones y del contexto de construcción. + + +## Historial de negocio + +Las operaciones de escritura generan eventos transaccionales. La consulta de administradores se realiza en Reporting mediante `GET /reporting/audit`. Antes de desplegar, instala el esquema del historial desde Auth. Consulta [activacion, API y contrato](../genesis_authv2/docs/business-audit.md). diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..529163c --- /dev/null +++ b/compose.yml @@ -0,0 +1,38 @@ +services: + users: + build: . + ports: + - "127.0.0.1:${SERVER_PORT:-8081}:8081" + environment: + SERVER_PORT: 8081 + 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} + AUTH_ALLOW_LEGACY_PASSWORDS: ${AUTH_ALLOW_LEGACY_PASSWORDS:-false} + PASSWORD_MIN_LENGTH: ${PASSWORD_MIN_LENGTH:-10} + PASSWORD_MAX_LENGTH: ${PASSWORD_MAX_LENGTH:-128} + PASSWORD_MIN_CLASSES: ${PASSWORD_MIN_CLASSES:-3} + PASSWORD_REQUIRE_COMPLEXITY: ${PASSWORD_REQUIRE_COMPLEXITY:-true} + 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-user: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 diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -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-,maven-mvnd--}/ +[ -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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -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-,maven-mvnd--}/ +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" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..724f177 --- /dev/null +++ b/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + org.springframework.bootspring-boot-starter-parent4.0.8 + com.aellisgenesis-user0.0.1-SNAPSHOT + Genesis User Service + 25 + + org.springframework.bootspring-boot-starter-webmvc + org.springframework.bootspring-boot-starter-security + org.springframework.bootspring-boot-starter-oauth2-resource-server + org.springframework.bootspring-boot-starter-jdbc + org.springframework.bootspring-boot-starter-validation + org.springframework.bootspring-boot-starter-data-redis + org.springframework.bootspring-boot-starter-actuator + org.postgresqlpostgresqlruntime + org.bouncycastlebcprov-jdk18on1.83 + org.springframework.bootspring-boot-starter-testtest + org.springframework.securityspring-security-testtest + org.testcontainerstestcontainers-postgresqltest + org.testcontainerstestcontainers-junit-jupitertest + + + org.springframework.bootspring-boot-maven-plugin + org.apache.maven.pluginsmaven-failsafe-pluginintegration-testverify + org.apache.maven.pluginsmaven-enforcer-plugin3.6.2enforce[25,26) + + diff --git a/scripts/run.ps1 b/scripts/run.ps1 new file mode 100644 index 0000000..cda3342 --- /dev/null +++ b/scripts/run.ps1 @@ -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 diff --git a/src/main/java/com/aellis/users/UsersApplication.java b/src/main/java/com/aellis/users/UsersApplication.java new file mode 100644 index 0000000..3f40f9a --- /dev/null +++ b/src/main/java/com/aellis/users/UsersApplication.java @@ -0,0 +1,17 @@ +package com.aellis.users; + +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 UsersApplication { + public static void main(String[] args) { SpringApplication.run(UsersApplication.class, args); } + @Bean ApplicationRunner verifyDatabase(JdbcClient jdbc) { + return args -> jdbc.sql("SELECT 1").query(Integer.class).single(); + } +} diff --git a/src/main/java/com/aellis/users/api/ApiException.java b/src/main/java/com/aellis/users/api/ApiException.java new file mode 100644 index 0000000..fe8524e --- /dev/null +++ b/src/main/java/com/aellis/users/api/ApiException.java @@ -0,0 +1,7 @@ +package com.aellis.users.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; } +} diff --git a/src/main/java/com/aellis/users/api/ApiExceptionHandler.java b/src/main/java/com/aellis/users/api/ApiExceptionHandler.java new file mode 100644 index 0000000..d8428d0 --- /dev/null +++ b/src/main/java/com/aellis/users/api/ApiExceptionHandler.java @@ -0,0 +1,31 @@ +package com.aellis.users.api; + +import com.aellis.users.api.UserDtos.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("Email already exists.")); } + @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.users.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("user_service_error type={}", error.getClass().getSimpleName()); + return ResponseEntity.internalServerError().body(ApiResponse.fail("Internal server error.")); + } +} diff --git a/src/main/java/com/aellis/users/api/HealthController.java b/src/main/java/com/aellis/users/api/HealthController.java new file mode 100644 index 0000000..7164a04 --- /dev/null +++ b/src/main/java/com/aellis/users/api/HealthController.java @@ -0,0 +1,9 @@ +package com.aellis.users.api; + +import java.util.Map; +import org.springframework.web.bind.annotation.*; + +@RestController +public class HealthController { + @GetMapping("/health") public Map health() { return Map.of("ok", true); } +} diff --git a/src/main/java/com/aellis/users/api/UserController.java b/src/main/java/com/aellis/users/api/UserController.java new file mode 100644 index 0000000..bc4ddd1 --- /dev/null +++ b/src/main/java/com/aellis/users/api/UserController.java @@ -0,0 +1,39 @@ +package com.aellis.users.api; + +import com.aellis.users.api.UserDtos.*; +import com.aellis.users.service.UserService; +import java.util.Map; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/users") +public class UserController { + private final UserService users; + public UserController(UserService users) { this.users = users; } + @PostMapping("/create") public ApiResponse create(@AuthenticationPrincipal Jwt jwt, @RequestBody Payload body) { + users.create(requester(jwt), UserDtos.parse(body, true)); + return ApiResponse.ok(new Message("Usuario registrado exitosamente.")); + } + @PutMapping("/update/{id}") public ApiResponse update(@AuthenticationPrincipal Jwt jwt, @PathVariable String id, @RequestBody Payload body) { + users.update(requester(jwt), UserDtos.positiveId(id), UserDtos.parse(body, false)); + return ApiResponse.ok(new Message("Usuario editado exitosamente.")); + } + @DeleteMapping("/delete/{id}") public ApiResponse delete(@AuthenticationPrincipal Jwt jwt, @PathVariable String id) { + users.delete(requester(jwt), UserDtos.positiveId(id)); return ApiResponse.ok(new Message("Usuario eliminado exitosamente.")); + } + @PatchMapping("/disable/{id}") public ApiResponse disable(@AuthenticationPrincipal Jwt jwt, @PathVariable String id, + @RequestBody(required = false) Payload body) { + if (body != null && !body.isEmpty()) throw new ApiException(400, "Invalid request."); + users.disable(requester(jwt), UserDtos.positiveId(id)); return ApiResponse.ok(new Message("Usuario deshabilitado exitosamente.")); + } + @GetMapping("/get/{id}") public ApiResponse find(@AuthenticationPrincipal Jwt jwt, @PathVariable String id) { + return ApiResponse.ok(Map.of("user", users.find(requester(jwt), UserDtos.positiveId(id)))); + } + @GetMapping("/all") public ApiResponse all(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("users", users.all(requester(jwt)))); } + @GetMapping("/rol/all") public ApiResponse roles(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("roles", users.roles(requester(jwt)))); } + private static Requester requester(Jwt jwt) { + return new Requester(Long.parseLong(jwt.getClaimAsString("id")), jwt.getClaimAsString("rol")); + } +} diff --git a/src/main/java/com/aellis/users/api/UserDtos.java b/src/main/java/com/aellis/users/api/UserDtos.java new file mode 100644 index 0000000..73e58cb --- /dev/null +++ b/src/main/java/com/aellis/users/api/UserDtos.java @@ -0,0 +1,78 @@ +package com.aellis.users.api; + +import java.util.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +public final class UserDtos { + private UserDtos() {} + public record ApiResponse(T data, String status) { + public static ApiResponse ok(T data) { return new ApiResponse<>(data, "success"); } + public static ApiResponse fail(String message) { return new ApiResponse<>(new Message(message), "error"); } + } + public record Message(String message) {} + public record Role(long id, String name) {} + public record UserView(long id, String name, String lastname, String email, double rate, String acronym, + @JsonProperty("id_specialization") Integer specializationId, @JsonProperty("id_rol") int roleId, + String rol, String specialization, String status) {} + public record UserState(long id, String email, String password, int roleId, int statusId) {} + public record Requester(long id, String role) { public boolean admin() { return "admin".equals(role); } } + public record Input(Map fields, String currentPassword) {} + /** Evita que el logging DEBUG de Spring imprima contraseñas al leer el cuerpo JSON. */ + public static class Payload extends LinkedHashMap { + @Override public String toString() { return "[user request body redacted]"; } + } + + private static final Set FIELDS = Set.of("name", "lastname", "email", "rate", "acronym", "password", "id_specialization", "id_rol", "id_status"); + public static Input parse(Map body, boolean creating) { + if (body == null) throw invalid(); + var normalized = new LinkedHashMap(); + String currentPassword = null; + for (var entry : body.entrySet()) { + String key = entry.getKey(); Object raw = entry.getValue(); + if (!creating && key.equals("current_password")) { + currentPassword = password(raw); continue; + } + if (!FIELDS.contains(key) || raw == null) throw invalid(); + if (key.equals("rate")) { + double number = number(raw); + if (number < 0 || number > 1_000_000) throw invalid(); + normalized.put(key, number); + } else if (key.startsWith("id_")) { + double number = number(raw); + if (number <= 0 || number > Integer.MAX_VALUE || number != Math.rint(number)) throw invalid(); + normalized.put(key, (int) number); + } else if (key.equals("password")) { + normalized.put(key, password(raw)); + } else { + if (!(raw instanceof String)) throw invalid(); + String value = ((String) raw).strip(); + int max = key.equals("email") ? 254 : key.equals("acronym") ? 20 : 100; + if (value.isEmpty() || value.length() > max) throw invalid(); + if (key.equals("email")) { + if (!value.matches("[^@\\s]+@[^@\\s]+\\.[^@\\s]+")) throw invalid(); + value = value.toLowerCase(Locale.ROOT); + } + normalized.put(key, value); + } + } + if (creating && !normalized.keySet().containsAll(Set.of("name", "lastname", "email", "rate", "acronym", "password"))) throw invalid(); + if (normalized.isEmpty()) throw new ApiException(400, "No fields to update."); + return new Input(Collections.unmodifiableMap(normalized), currentPassword); + } + public static int positiveId(String value) { + try { double n = Double.parseDouble(value); if (!Double.isFinite(n) || n <= 0 || n > Integer.MAX_VALUE || n != Math.rint(n)) throw invalid(); return (int) n; } + catch (NumberFormatException exception) { throw new ApiException(400, "ID invalido."); } + } + private static String password(Object raw) { + if (!(raw instanceof String value) || value.isBlank() || value.length() > 128) throw invalid(); + return value; + } + private static double number(Object raw) { + try { + double number = raw instanceof Number n ? n.doubleValue() : raw instanceof String s ? (s.isBlank() ? 0 : Double.parseDouble(s.strip())) : Double.NaN; + if (!Double.isFinite(number)) throw invalid(); + return number; + } catch (NumberFormatException exception) { throw invalid(); } + } + private static ApiException invalid() { return new ApiException(400, "Invalid request."); } +} diff --git a/src/main/java/com/aellis/users/audit/AuditReasonValidation.java b/src/main/java/com/aellis/users/audit/AuditReasonValidation.java new file mode 100644 index 0000000..8b87b65 --- /dev/null +++ b/src/main/java/com/aellis/users/audit/AuditReasonValidation.java @@ -0,0 +1,23 @@ +package com.aellis.users.audit; + +import com.aellis.users.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; + } + }); + } +} diff --git a/src/main/java/com/aellis/users/audit/BusinessAudit.java b/src/main/java/com/aellis/users/audit/BusinessAudit.java new file mode 100644 index 0000000..56a24a3 --- /dev/null +++ b/src/main/java/com/aellis/users/audit/BusinessAudit.java @@ -0,0 +1,112 @@ +package com.aellis.users.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> 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 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)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 before,Map after) { + requireTransaction(); + List 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(); + var newValues=new LinkedHashMap(); + 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 before,Map 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","users").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"); + } +} diff --git a/src/main/java/com/aellis/users/config/RequestFilter.java b/src/main/java/com/aellis/users/config/RequestFilter.java new file mode 100644 index 0000000..877cc78 --- /dev/null +++ b/src/main/java/com/aellis/users/config/RequestFilter.java @@ -0,0 +1,120 @@ +package com.aellis.users.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 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 memory = new LinkedHashMap<>(); + private final UserProperties properties; + private final Clock clock; + private final StringRedisTemplate redis; + private volatile long redisDisabledUntil; + public RequestFilter(UserProperties 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 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)); } + } +} diff --git a/src/main/java/com/aellis/users/config/SecurityConfig.java b/src/main/java/com/aellis/users/config/SecurityConfig.java new file mode 100644 index 0000000..7094964 --- /dev/null +++ b/src/main/java/com/aellis/users/config/SecurityConfig.java @@ -0,0 +1,112 @@ +package com.aellis.users.config; + +import com.aellis.users.service.MigrationPasswordEncoder; +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.crypto.password.PasswordEncoder; +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 PasswordEncoder passwordEncoder(UserProperties properties) { return new MigrationPasswordEncoder(properties.allowLegacyPasswords()); } + + @Bean JwtDecoder jwtDecoder(UserProperties 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 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, UserProperties 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, "/users/create").hasRole("ADMIN") + .requestMatchers(org.springframework.http.HttpMethod.DELETE, "/users/delete/*").hasRole("ADMIN") + .requestMatchers(org.springframework.http.HttpMethod.PATCH, "/users/disable/*").hasRole("ADMIN") + .requestMatchers(org.springframework.http.HttpMethod.GET, "/users/all", "/users/rol/all").hasRole("ADMIN") + .requestMatchers(org.springframework.http.HttpMethod.GET, "/users/get/*").hasAnyRole("ADMIN", "USER") + .requestMatchers(org.springframework.http.HttpMethod.PUT, "/users/update/*").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(UserProperties 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; + } +} diff --git a/src/main/java/com/aellis/users/config/UserProperties.java b/src/main/java/com/aellis/users/config/UserProperties.java new file mode 100644 index 0000000..476fba4 --- /dev/null +++ b/src/main/java/com/aellis/users/config/UserProperties.java @@ -0,0 +1,40 @@ +package com.aellis.users.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("users") +public record UserProperties(@NotBlank String jwtAlgorithm, Resource publicKey, String tokenSecret, + @NotBlank String issuer, @NotBlank String audience, boolean checkSession, @NotNull Duration jwtMaxAge, + @NotEmpty List allowedOrigins, boolean allowLegacyPasswords, + @Min(1) @Max(128) int passwordMinLength, @Min(1) @Max(128) int passwordMaxLength, + @Min(1) @Max(4) int passwordMinClasses, boolean passwordRequireComplexity, + @Min(0) int rateLimitMax, @Min(1) long rateLimitWindowMs, + @Min(1) int rateLimitMemoryMaxKeys, @Min(1000) long rateLimitRedisBackoffMs, + @NotBlank String rateLimitPrefix, String redisUrl, boolean requestLogEnabled) { + public UserProperties { + if (!List.of("RS256", "HS256").contains(jwtAlgorithm)) throw new IllegalArgumentException("JWT_ALGORITHM debe ser RS256 o HS256"); + if (passwordMinLength > passwordMaxLength) throw new IllegalArgumentException("PASSWORD_MIN_LENGTH supera PASSWORD_MAX_LENGTH"); + 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 orígenes CORS explícitos"); + } + public String passwordPolicyError(String password) { + if (password == null || password.length() < passwordMinLength) return "Password must be at least " + passwordMinLength + " characters long."; + if (password.length() > passwordMaxLength) return "Password must be at most " + passwordMaxLength + " characters long."; + if (!passwordRequireComplexity) return null; + boolean lower = false, upper = false, number = false, symbol = false; + for (char c : password.toCharArray()) { + if (c >= 'a' && c <= 'z') lower = true; + else if (c >= 'A' && c <= 'Z') upper = true; + else if (c >= '0' && c <= '9') number = true; + else symbol = true; + } + int count = (lower ? 1 : 0) + (upper ? 1 : 0) + (number ? 1 : 0) + (symbol ? 1 : 0); + return count < passwordMinClasses ? "Password must include at least " + passwordMinClasses + " of: lowercase, uppercase, number, symbol." : null; + } +} diff --git a/src/main/java/com/aellis/users/repository/UserRepository.java b/src/main/java/com/aellis/users/repository/UserRepository.java new file mode 100644 index 0000000..a9a6ad8 --- /dev/null +++ b/src/main/java/com/aellis/users/repository/UserRepository.java @@ -0,0 +1,75 @@ +package com.aellis.users.repository; + +import com.aellis.users.api.UserDtos.*; +import java.util.*; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Repository; + +@Repository +public class UserRepository { + private static final String VIEW = """ + SELECT u.id,u.name,u.lastname,u.email,u.rate,u.acronym,u.id_specialization,u.id_rol, + r.name AS role_name,sp.name AS specialization_name,st.name AS status_name + FROM users u LEFT JOIN rol r ON r.id=u.id_rol + LEFT JOIN specialization sp ON sp.id=u.id_specialization LEFT JOIN status st ON st.id=u.id_status + """; + private static final Set WRITABLE = Set.of("name", "lastname", "email", "rate", "acronym", "password", "id_specialization", "id_rol", "id_status"); + private final JdbcClient jdbc; + public UserRepository(JdbcClient jdbc) { this.jdbc = jdbc; } + public Optional find(long id) { return jdbc.sql(VIEW + " WHERE u.id=:id").param("id", id).query(this::mapView).optional(); } + public List activeUsers() { return jdbc.sql(VIEW + " WHERE u.id_status=1 ORDER BY u.name ASC,u.id ASC").query(this::mapView).list(); } + public List roles() { return jdbc.sql("SELECT id,name FROM rol ORDER BY name ASC,id ASC").query(Role.class).list(); } + public Optional lock(long id) { + return jdbc.sql("SELECT id,email,password,id_rol,id_status FROM users WHERE id=:id FOR UPDATE") + .param("id", id).query((rs, row) -> new UserState(rs.getLong("id"), rs.getString("email"), rs.getString("password"), + rs.getInt("id_rol"), rs.getInt("id_status"))).optional(); + } + public boolean catalogExists(String field, int id) { + String table = switch (field) { case "id_rol" -> "rol"; case "id_status" -> "status"; case "id_specialization" -> "specialization"; default -> throw new IllegalArgumentException("Unknown catalog"); }; + return jdbc.sql("SELECT EXISTS(SELECT 1 FROM " + table + " WHERE id=:id)").param("id", id).query(Boolean.class).single(); + } + public boolean emailExists(String email, long exceptId) { + return jdbc.sql("SELECT EXISTS(SELECT 1 FROM users WHERE lower(btrim(email))=:email AND id<>:id)") + .param("email", email).param("id", exceptId).query(Boolean.class).single(); + } + public long create(Map values) { + return jdbc.sql(""" + INSERT INTO users(name,lastname,email,rate,acronym,password,id_specialization,id_rol,id_status,created) + VALUES (:name,:lastname,:email,:rate,:acronym,:password,:specialization,:role,:status,CURRENT_TIMESTAMP) RETURNING id + """).param("name", values.get("name")).param("lastname", values.get("lastname")) + .param("email", values.get("email")).param("rate", values.get("rate")).param("acronym", values.get("acronym")) + .param("password", values.get("password")).param("specialization", values.get("id_specialization")) + .param("role", values.getOrDefault("id_rol", 2)).param("status", values.getOrDefault("id_status", 1)).query(Long.class).single(); + } + public void update(long id, Map values) { + if (values.isEmpty() || !WRITABLE.containsAll(values.keySet())) throw new IllegalArgumentException("Invalid update fields"); + String assignments = String.join(",", values.keySet().stream().map(key -> key + "=:" + key).toList()); + jdbc.sql("UPDATE users SET " + assignments + ",updated=CURRENT_TIMESTAMP WHERE id=:targetId") + .params(values).param("targetId", id).update(); + } + public void delete(long id) { jdbc.sql("DELETE FROM users WHERE id=:id").param("id", id).update(); } + public boolean tableExists(String name) { + return jdbc.sql("SELECT to_regclass(:name) IS NOT NULL").param("name", name).query(Boolean.class).single(); + } + public void revokeSessions(long id) { + if (tableExists("auth_session")) jdbc.sql("UPDATE auth_session SET revoked=TRUE WHERE user_id=:id").param("id", id).update(); + if (tableExists("refresh_tokens")) jdbc.sql("UPDATE refresh_tokens SET revoked_at=COALESCE(revoked_at,CURRENT_TIMESTAMP) WHERE user_id=:id").param("id", id).update(); + if (tableExists("password_reset_request")) jdbc.sql("DELETE FROM password_reset_request WHERE user_id=:id").param("id", id).update(); + } + public void deleteRefreshTokens(long id) { + if (tableExists("refresh_tokens")) jdbc.sql("DELETE FROM refresh_tokens WHERE user_id=:id").param("id", id).update(); + } + public void clearResetToken(long id) { + // Las bases antiguas pueden no tener todavía las columnas de recuperación. + boolean present = jdbc.sql(""" + SELECT count(*)=2 FROM information_schema.columns WHERE table_schema=current_schema() + AND table_name='users' AND column_name IN ('reset_token_hash','reset_token_expires_at') + """).query(Boolean.class).single(); + if (present) jdbc.sql("UPDATE users SET reset_token_hash=NULL,reset_token_expires_at=NULL WHERE id=:id").param("id", id).update(); + } + private UserView mapView(java.sql.ResultSet rs, int row) throws java.sql.SQLException { + return new UserView(rs.getLong("id"), rs.getString("name"), rs.getString("lastname"), rs.getString("email"), + rs.getDouble("rate"), rs.getString("acronym"), rs.getObject("id_specialization", Integer.class), rs.getInt("id_rol"), + rs.getString("role_name"), rs.getString("specialization_name"), rs.getString("status_name")); + } +} diff --git a/src/main/java/com/aellis/users/service/MigrationPasswordEncoder.java b/src/main/java/com/aellis/users/service/MigrationPasswordEncoder.java new file mode 100644 index 0000000..0540153 --- /dev/null +++ b/src/main/java/com/aellis/users/service/MigrationPasswordEncoder.java @@ -0,0 +1,47 @@ +package com.aellis.users.service; + +import java.nio.charset.StandardCharsets; +import java.security.*; +import java.util.HexFormat; +import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +/** Compatibilidad con password.js de Node; MD5/plain requieren habilitación temporal explícita. */ +public class MigrationPasswordEncoder implements PasswordEncoder { + private final PasswordEncoder modern = new Argon2PasswordEncoder(16, 32, 1, 19456, 2); + private final PasswordEncoder bcrypt = new BCryptPasswordEncoder(); + private final boolean allowLegacy; + public MigrationPasswordEncoder(boolean allowLegacy) { this.allowLegacy = allowLegacy; } + @Override public String encode(CharSequence raw) { return "{argon2}" + modern.encode(raw); } + @Override public boolean matches(CharSequence raw, String stored) { + if (raw == null || stored == null) return false; + try { + if (stored.startsWith("{argon2}")) return modern.matches(raw, stored.substring(8)); + String hash = stored.startsWith("{bcrypt}") ? stored.substring(8) : stored; + if (hash.matches("\\$2[aby]\\$\\d{2}\\$[./A-Za-z0-9]{53}")) { + return raw.toString().getBytes(StandardCharsets.UTF_8).length <= 72 && bcrypt.matches(raw, hash); + } + if (!allowLegacy) return false; + if (stored.startsWith("{legacy-md5}")) { + return MessageDigest.isEqual(digest("MD5", raw.toString()), HexFormat.of().parseHex(stored.substring(12))); + } + if (stored.startsWith("{legacy-plain}")) { + return MessageDigest.isEqual(digest("SHA-256", raw.toString()), digest("SHA-256", stored.substring(14))); + } + if (stored.matches("[a-fA-F0-9]{32}")) { + return MessageDigest.isEqual(digest("MD5", raw.toString()), HexFormat.of().parseHex(stored)); + } + // Un hash bcrypt malformado o un identificador de hash desconocido no se interpreta como texto plano. + if (stored.startsWith("$2") || stored.startsWith("{")) return false; + return MessageDigest.isEqual(digest("SHA-256", raw.toString()), digest("SHA-256", stored)); + } catch (IllegalArgumentException exception) { return false; } + } + @Override public boolean upgradeEncoding(String stored) { + return stored != null && (!stored.startsWith("{argon2}") || modern.upgradeEncoding(stored.substring(8))); + } + private static byte[] digest(String algorithm, String value) { + try { return MessageDigest.getInstance(algorithm).digest(value.getBytes(StandardCharsets.UTF_8)); } + catch (NoSuchAlgorithmException exception) { throw new IllegalStateException(exception); } + } +} diff --git a/src/main/java/com/aellis/users/service/UserService.java b/src/main/java/com/aellis/users/service/UserService.java new file mode 100644 index 0000000..4f79363 --- /dev/null +++ b/src/main/java/com/aellis/users/service/UserService.java @@ -0,0 +1,95 @@ +package com.aellis.users.service; + +import com.aellis.users.api.ApiException; +import com.aellis.users.audit.BusinessAudit; +import com.aellis.users.api.UserDtos.*; +import com.aellis.users.config.UserProperties; +import com.aellis.users.repository.UserRepository; +import java.util.*; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class UserService { + private final UserRepository users; + private final PasswordEncoder passwords; + private final UserProperties properties; + private final BusinessAudit history; + public UserService(UserRepository users, PasswordEncoder passwords, UserProperties properties, BusinessAudit history) { + this.users = users; this.passwords = passwords; this.properties = properties; this.history=history; + } + @Transactional public void create(Requester requester, Input input) { + requireAdmin(requester); + var values = new LinkedHashMap<>(input.fields()); + values.putIfAbsent("id_rol", 2); values.putIfAbsent("id_status", 1); + validateCatalogs(values); + if (users.emailExists((String) values.get("email"), 0)) throw new ApiException(409, "Email already exists."); + validateNewPassword((String) values.get("password")); + values.put("password", passwords.encode((String) values.get("password"))); + var context=history.context(requester.id()); + long id=users.create(values); + history.change(context,"user.create","user",id,null,Map.of(),history.snapshot("users",id)); + } + @Transactional public void update(Requester requester, long id, Input input) { + requireSelfOrAdmin(requester, id); + var values = new LinkedHashMap<>(input.fields()); + if (!requester.admin() && values.keySet().stream().anyMatch(Set.of("rate", "id_specialization", "id_rol", "id_status")::contains)) { + throw new ApiException(403, "Forbidden."); + } + var current = users.lock(id).orElseThrow(UserService::notFound); + var context=history.context(requester.id()); var before=history.snapshot("users",id); + if (values.containsKey("email") && users.emailExists((String) values.get("email"), id)) throw new ApiException(409, "Email already exists."); + validateCatalogs(values); + if (values.containsKey("password")) { + if (!requester.admin()) { + if (input.currentPassword() == null) throw new ApiException(400, "Current password required."); + if (!passwords.matches(input.currentPassword(), current.password())) throw new ApiException(403, "Current password is incorrect."); + } + validateNewPassword((String) values.get("password")); + values.put("password", passwords.encode((String) values.get("password"))); + } + boolean credentialsChanged = values.containsKey("password") + || (values.containsKey("email") && !values.get("email").equals(current.email().strip().toLowerCase(Locale.ROOT))) + || (values.containsKey("id_rol") && !values.get("id_rol").equals(current.roleId())) + || (values.containsKey("id_status") && !values.get("id_status").equals(current.statusId())); + users.update(id, values); + if (credentialsChanged) { users.clearResetToken(id); users.revokeSessions(id); } + history.change(context,"user.update","user",id,null,before,history.snapshot("users",id)); + if(values.containsKey("password")) history.passwordChanged(context,id,"user.password_changed"); + } + @Transactional public void delete(Requester requester, long id) { + requireAdmin(requester); + users.lock(id).orElseThrow(UserService::notFound); + var context=history.context(requester.id()); var before=history.snapshot("users",id); + users.revokeSessions(id); users.deleteRefreshTokens(id); users.delete(id); + history.change(context,"user.delete","user",id,null,before,Map.of()); + } + @Transactional public void disable(Requester requester, long id) { + requireAdmin(requester); + users.lock(id).orElseThrow(UserService::notFound); + var context=history.context(requester.id()); var before=history.snapshot("users",id); + if (!users.catalogExists("id_status", 2)) throw new ApiException(400, "Invalid status."); + users.update(id, Map.of("id_status", 2)); users.clearResetToken(id); users.revokeSessions(id); + history.change(context,"user.disable","user",id,null,before,history.snapshot("users",id)); + } + public UserView find(Requester requester, long id) { + requireSelfOrAdmin(requester, id); return users.find(id).orElseThrow(UserService::notFound); + } + public List all(Requester requester) { requireAdmin(requester); return users.activeUsers(); } + public List roles(Requester requester) { requireAdmin(requester); return users.roles(); } + private void validateNewPassword(String password) { + String error = properties.passwordPolicyError(password); + if (error != null) throw new ApiException(400, error); + } + private void validateCatalogs(Map fields) { + for (String field : List.of("id_specialization", "id_rol", "id_status")) { + if (fields.containsKey(field) && !users.catalogExists(field, (Integer) fields.get(field))) { + throw new ApiException(400, switch (field) { case "id_rol" -> "Invalid role."; case "id_status" -> "Invalid status."; default -> "Invalid specialization."; }); + } + } + } + private static void requireAdmin(Requester requester) { if (!requester.admin()) throw new ApiException(403, "Forbidden."); } + private static void requireSelfOrAdmin(Requester requester, long id) { if (!requester.admin() && requester.id() != id) throw new ApiException(403, "Forbidden."); } + private static ApiException notFound() { return new ApiException(404, "Usuario no encontrado."); } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..e1d56a9 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,58 @@ +spring: + application: + name: genesis-user + 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:8081} + 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 +users: + 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}} + allow-legacy-passwords: ${AUTH_ALLOW_LEGACY_PASSWORDS:false} + password-min-length: ${PASSWORD_MIN_LENGTH:10} + password-max-length: ${PASSWORD_MAX_LENGTH:128} + password-min-classes: ${PASSWORD_MIN_CLASSES:3} + password-require-complexity: ${PASSWORD_REQUIRE_COMPLEXITY:true} + 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-user:rate} + redis-url: ${REDIS_URL:} + request-log-enabled: ${REQUEST_LOG_ENABLED:true} diff --git a/src/test/java/com/aellis/users/UserServiceIT.java b/src/test/java/com/aellis/users/UserServiceIT.java new file mode 100644 index 0000000..14fe44d --- /dev/null +++ b/src/test/java/com/aellis/users/UserServiceIT.java @@ -0,0 +1,268 @@ +package com.aellis.users; + +import com.aellis.users.service.MigrationPasswordEncoder; +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.crypto.bcrypt.BCryptPasswordEncoder; +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", "users.request-log-enabled=false", "users.rate-limit-max=10000", "spring.data.redis.port=1"}) +class UserServiceIT { + static final PostgreSQLContainer DB = new PostgreSQLContainer("postgres:18"); + static String url, username, password, schema; + static Path keyDirectory; + static JwtEncoder signer; + static final String PASSWORD = "OriginalPass12!"; + static final String NEXT_PASSWORD = "AnotherPass34!"; + @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 = "users_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("users.public-key", () -> keyDirectory.resolve("public.pem").toUri().toString()); + registry.add("users.jwt-algorithm", () -> "RS256"); + registry.add("users.issuer", () -> "http://localhost:8080"); registry.add("users.audience", () -> "genesis-api"); + registry.add("users.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 Environment environment; + final HttpClient http = HttpClient.newHttpClient(); + final JsonMapper json = JsonMapper.builder().build(); + @BeforeEach void seed() { + jdbc.sql("TRUNCATE business_audit_events RESTART IDENTITY").update(); + jdbc.sql("TRUNCATE users,refresh_tokens RESTART IDENTITY CASCADE").update(); + String hash = new MigrationPasswordEncoder(false).encode(PASSWORD); + for (int id = 1; id <= 5; id++) { + jdbc.sql(""" + INSERT INTO users(id,name,lastname,email,rate,acronym,password,id_specialization,id_rol,id_status) + VALUES (:id,:name,'Apellido',:email,12.5,'AA',:hash,3,:role,:status) + """).param("id", id).param("name", id == 1 ? "Ana" : "Usuario " + id) + .param("email", "user" + id + "@example.com").param("hash", hash).param("role", id == 1 ? 1 : 2) + .param("status", id == 4 ? 2 : id == 5 ? 7 : 1).update(); + } + jdbc.sql("SELECT setval(pg_get_serial_sequence('users','id'),5,TRUE)").query(Long.class).single(); + } + 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(); + } + Map createBody() { + return new LinkedHashMap<>(Map.of("name", " Nueva ", "lastname", " Persona ", "email", " NEW@Example.COM ", + "rate", "15.5", "acronym", " NP ", "password", NEXT_PASSWORD)); + } + @Test void healthIsPublicAndAllUserEndpointsRequireAuthentication() throws Exception { + assertThat(request("GET", "/health", null, null).body()).contains("\"ok\":true"); + assertThat(request("GET", "/actuator/health", null, null).statusCode()).isEqualTo(200); + assertThat(request("GET", "/users/all", null, null).statusCode()).isEqualTo(401); + assertThat(request("POST", "/users/create", createBody(), null).statusCode()).isEqualTo(401); + } + @Test void adminCreatesUserWithDefaultsAndArgon2HashCompatibleWithAuth() throws Exception { + var result = request("POST", "/users/create", createBody(), token(1, "admin")); + assertThat(result.statusCode()).isEqualTo(200); assertThat(result.body()).contains("success", "Usuario registrado exitosamente."); + var view = jdbc.sql("SELECT name||'|'||email||'|'||acronym FROM users WHERE id=6").query(String.class).single(); + assertThat(view).isEqualTo("Nueva|new@example.com|NP"); + String hash = jdbc.sql("SELECT password FROM users WHERE id=6").query(String.class).single(); + assertThat(hash).startsWith("{argon2}"); assertThat(new MigrationPasswordEncoder(false).matches(NEXT_PASSWORD, hash)).isTrue(); + assertThat(jdbc.sql("SELECT id_rol FROM users WHERE id=6").query(Integer.class).single()).isEqualTo(2); + assertThat(jdbc.sql("SELECT id_specialization IS NULL FROM users WHERE id=6").query(Boolean.class).single()).isTrue(); + } + @Test void duplicateEmailIs409AndInvalidForeignKeysAre400() throws Exception { + String admin = token(1, "admin"); + var body = createBody(); body.put("email", "USER2@example.com"); + assertThat(request("POST", "/users/create", body, admin).statusCode()).isEqualTo(409); + body.put("email", "valid@example.com"); body.put("id_specialization", 9876); + assertThat(request("POST", "/users/create", body, admin).statusCode()).isEqualTo(400); + body.remove("id_specialization"); body.put("id_rol", 9876); + assertThat(request("POST", "/users/create", body, admin).statusCode()).isEqualTo(400); + assertThat(jdbc.sql("SELECT count(*) FROM users").query(Integer.class).single()).isEqualTo(5); + } + @Test void regularUserCanReadAndEditOnlySelfAndCannotElevatePrivileges() throws Exception { + String user = token(2, "user"); + assertThat(request("GET", "/users/get/2", null, user).statusCode()).isEqualTo(200); + assertThat(request("GET", "/users/get/3", null, user).statusCode()).isEqualTo(403); + assertThat(request("PUT", "/users/update/3", Map.of("name", "Attack"), user).statusCode()).isEqualTo(403); + for (String field : List.of("rate", "id_rol", "id_status", "id_specialization")) { + assertThat(request("PUT", "/users/update/2", Map.of(field, 1), user).statusCode()).isEqualTo(403); + } + assertThat(request("PUT", "/users/update/2", Map.of("name", " Mi Nombre "), user).statusCode()).isEqualTo(200); + assertThat(jdbc.sql("SELECT name FROM users WHERE id=2").query(String.class).single()).isEqualTo("Mi Nombre"); + assertThat(request("POST", "/users/create", createBody(), user).statusCode()).isEqualTo(403); + assertThat(request("DELETE", "/users/delete/3", null, user).statusCode()).isEqualTo(403); + assertThat(request("PATCH", "/users/disable/3", Map.of(), user).statusCode()).isEqualTo(403); + assertThat(request("GET", "/users/all", null, user).statusCode()).isEqualTo(403); + assertThat(request("GET", "/users/rol/all", null, user).statusCode()).isEqualTo(403); + } + @Test void selfPasswordChangeRequiresCurrentPasswordAndRevokesSessionsAndResetTokens() throws Exception { + String user = token(2, "user"); + assertThat(request("PUT", "/users/update/2", Map.of("password", NEXT_PASSWORD), user).statusCode()).isEqualTo(400); + assertThat(request("PUT", "/users/update/2", Map.of("password", NEXT_PASSWORD, "current_password", "wrong"), user).statusCode()).isEqualTo(403); + jdbc.sql("UPDATE users SET reset_token_hash='old-token-hash',reset_token_expires_at=CURRENT_TIMESTAMP+INTERVAL '1 hour' WHERE id=2").update(); + jdbc.sql("INSERT INTO password_reset_request(user_id) VALUES(2)").update(); + var result = request("PUT", "/users/update/2", Map.of("password", NEXT_PASSWORD, "current_password", PASSWORD), user); + assertThat(result.statusCode()).isEqualTo(200); + assertThat(request("GET", "/users/get/2", null, user).statusCode()).isEqualTo(401); + assertThat(jdbc.sql("SELECT reset_token_hash IS NULL FROM users WHERE id=2").query(Boolean.class).single()).isTrue(); + assertThat(jdbc.sql("SELECT count(*) FROM password_reset_request WHERE user_id=2").query(Integer.class).single()).isZero(); + assertThat(new MigrationPasswordEncoder(false).matches(NEXT_PASSWORD, jdbc.sql("SELECT password FROM users WHERE id=2").query(String.class).single())).isTrue(); + } + @Test void existingBcryptCanBeVerifiedDuringSelfPasswordChange() throws Exception { + jdbc.sql("UPDATE users SET password=:hash WHERE id=2").param("hash", new BCryptPasswordEncoder(12).encode(PASSWORD)).update(); + assertThat(request("PUT", "/users/update/2", Map.of("password", NEXT_PASSWORD, "current_password", PASSWORD), token(2, "user")).statusCode()).isEqualTo(200); + } + @Test void adminResetRoleAndStatusChangesRevokeTheTargetsAccess() throws Exception { + String admin = token(1, "admin"), user = token(2, "user"); + assertThat(request("PUT", "/users/update/2", Map.of("password", NEXT_PASSWORD, "id_rol", 1), admin).statusCode()).isEqualTo(200); + assertThat(request("GET", "/users/get/2", null, user).statusCode()).isEqualTo(401); + assertThat(jdbc.sql("SELECT id_rol FROM users WHERE id=2").query(Integer.class).single()).isEqualTo(1); + } + @Test void disableAndDeleteRespectNodeStatusMessagesAndRevokeTokens() throws Exception { + String admin = token(1, "admin"), user = token(2, "user"); + assertThat(request("PATCH", "/users/disable/2", Map.of(), admin).statusCode()).isEqualTo(200); + assertThat(jdbc.sql("SELECT id_status FROM users WHERE id=2").query(Integer.class).single()).isEqualTo(2); + assertThat(request("GET", "/users/get/2", null, user).statusCode()).isEqualTo(401); + assertThat(request("DELETE", "/users/delete/2", null, admin).statusCode()).isEqualTo(200); + assertThat(request("GET", "/users/get/2", null, admin).statusCode()).isEqualTo(404); + assertThat(request("DELETE", "/users/delete/9876", null, admin).statusCode()).isEqualTo(404); + } + @Test void viewsFlattenCatalogNamesAndNeverExposePasswordsOrResetFields() throws Exception { + String admin = token(1, "admin"); + var list = request("GET", "/users/all", null, admin); + assertThat(list.statusCode()).isEqualTo(200); + var users = json.readTree(list.body()).get("data").get("users"); + assertThat(users.size()).isEqualTo(3); + assertThat(users.get(0).get("id").asLong()).isEqualTo(1); + assertThat(users.get(0).get("rol").asText()).isEqualTo("admin"); + assertThat(users.get(0).get("specialization").asText()).isEqualTo("Soporte"); + assertThat(users.get(0).get("status").asText()).isEqualTo("Activo"); + assertThat(users.get(0).get("id_specialization").asInt()).isEqualTo(3); + assertThat(list.body()).doesNotContain("password", "reset_token", "created", "updated", "id_status"); + assertThat(request("GET", "/users/get/4", null, admin).body()).contains("Deshabilitado"); + assertThat(request("GET", "/users/rol/all", null, admin).body()).contains("\"roles\"", "admin", "user"); + } + @Test void strictValidationRejectsUnknownNullEmptyAndOutOfRangeValues() throws Exception { + String admin = token(1, "admin"); + for (var patch : List.of(Map.of(), Map.of("unknown", "value"), Map.of("current_password", PASSWORD), Map.of("rate", -1), + Map.of("rate", 1_000_001), Map.of("id_rol", 1.5), Map.of("name", " "), Map.of("password", "short"))) { + assertThat(request("PUT", "/users/update/2", patch, admin).statusCode()).isEqualTo(400); + } + var nullField = new HashMap(); nullField.put("name", null); + assertThat(request("PUT", "/users/update/2", nullField, admin).statusCode()).isEqualTo(400); + assertThat(request("PATCH", "/users/disable/2", Map.of("id_status", 1), admin).statusCode()).isEqualTo(400); + assertThat(request("GET", "/users/get/abc", null, admin).statusCode()).isEqualTo(400); + assertThat(request("GET", "/users/get/-1", null, admin).statusCode()).isEqualTo(400); + } + @Test void revokedExpiredDisabledWrongIssuerAudienceRoleAndSignatureAreRejected() throws Exception { + String revoked = token(2, "user"); jdbc.sql("UPDATE auth_session SET revoked=TRUE").update(); + assertThat(request("GET", "/users/get/2", null, revoked).statusCode()).isEqualTo(401); + assertThat(request("GET", "/users/get/4", null, token(4, "user")).statusCode()).isEqualTo(401); + assertThat(request("GET", "/users/all", null, token(2, "admin")).statusCode()).isEqualTo(401); + for (String invalid : List.of("issuer", "audience", "expiry", "type", "age")) { + UUID sid = UUID.randomUUID(); + 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", "/users/get/2", null, jwt).statusCode()).isEqualTo(401); + } + String[] parts = token(2, "user").split("\\."); + String tampered = parts[0] + "." + Base64.getUrlEncoder().withoutPadding().encodeToString("{\"id\":1}".getBytes(java.nio.charset.StandardCharsets.UTF_8)) + "." + parts[2]; + assertThat(request("GET", "/users/all", null, tampered).statusCode()).isEqualTo(401); + } + @Test void corsRequestIdsAndBodySizeLimitsAreApplied() throws Exception { + var request = HttpRequest.newBuilder(URI.create(base() + "/users/all")).header("Origin", "http://localhost:3000") + .header("Access-Control-Request-Method", "GET").method("OPTIONS", HttpRequest.BodyPublishers.noBody()).build(); + var allowed = http.send(request, 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() + "/users/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("X-Request-Id")).isPresent(); + assertThat(health.headers().firstValue("Cache-Control")).hasValue("no-store"); + assertThat(request("POST", "/users/create", Map.of("name", "x".repeat(1024 * 1024 + 1)), token(1, "admin")).statusCode()).isEqualTo(413); + } + String base() { return "http://localhost:" + environment.getProperty("local.server.port"); } + HttpResponse 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 userAuditSnapshotsExcludeCredentialsAndSurvivePhysicalDeletion() throws Exception { + String admin=token(1,"admin"); + assertThat(request("POST","/users/create",createBody(),admin).statusCode()).isEqualTo(200); + assertThat(request("PUT","/users/update/6",Map.of("rate",22,"password",NEXT_PASSWORD),admin).statusCode()).isEqualTo(200); + assertThat(request("DELETE","/users/delete/6",null,admin).statusCode()).isEqualTo(200); + var events=jdbc.sql("SELECT before_values::text||after_values::text FROM business_audit_events ORDER BY id").query(String.class).list(); + assertThat(events).hasSize(4); + for(String values:events) assertThat(values).doesNotContain("password","{argon2}","reset_token",NEXT_PASSWORD); + assertThat(jdbc.sql("SELECT count(*) FROM users WHERE id=6").query(Integer.class).single()).isZero(); + assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events WHERE action='user.password_changed' AND before_values='{}'::jsonb AND after_values='{}'::jsonb").query(Integer.class).single()).isEqualTo(1); + assertThat(jdbc.sql("SELECT before_values->>'rate' FROM business_audit_events WHERE action='user.update'").query(String.class).single()).isEqualTo("15.5"); + } + @Test void auditSurvivesDeletingTheActorAndRetainsTheirOriginalName() throws Exception { + assertThat(request("PUT","/users/update/2",Map.of("name","Renombrado"),token(1,"admin")).statusCode()).isEqualTo(200); + assertThat(request("DELETE","/users/delete/1",null,token(1,"admin")).statusCode()).isEqualTo(200); + assertThat(jdbc.sql("SELECT actor_name FROM business_audit_events WHERE action='user.update'").query(String.class).single()).isEqualTo("Ana Apellido"); + assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events").query(Integer.class).single()).isEqualTo(2); + } +} diff --git a/src/test/resources/schema.sql b/src/test/resources/schema.sql new file mode 100644 index 0000000..90438bb --- /dev/null +++ b/src/test/resources/schema.sql @@ -0,0 +1,47 @@ +CREATE TABLE rol (id SERIAL PRIMARY KEY,name VARCHAR(255) NOT NULL); +CREATE TABLE specialization (id SERIAL PRIMARY KEY,name VARCHAR(255) NOT NULL); +CREATE TABLE status (id SERIAL PRIMARY KEY,name VARCHAR(255) NOT NULL,_table VARCHAR(255) NOT NULL); +CREATE TABLE users ( + id SERIAL PRIMARY KEY,name VARCHAR(255) NOT NULL,lastname VARCHAR(255) NOT NULL,email VARCHAR(255) NOT NULL UNIQUE, + rate DOUBLE PRECISION NOT NULL,acronym VARCHAR(255) NOT NULL,password VARCHAR(255) NOT NULL, + created TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,updated TIMESTAMPTZ, + reset_token_hash VARCHAR(255),reset_token_expires_at TIMESTAMPTZ, + id_specialization INTEGER REFERENCES specialization(id),id_rol INTEGER NOT NULL DEFAULT 2 REFERENCES rol(id), + id_status INTEGER NOT NULL DEFAULT 1 REFERENCES status(id) +); +CREATE UNIQUE INDEX normalized_email ON users(lower(btrim(email))); +CREATE TABLE auth_session ( + id UUID PRIMARY KEY,user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL,revoked BOOLEAN NOT NULL DEFAULT FALSE,created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP +); +CREATE TABLE refresh_tokens ( + id SERIAL PRIMARY KEY,user_id INTEGER NOT NULL,token_hash VARCHAR(255) NOT NULL, + expires_at TIMESTAMPTZ,revoked_at TIMESTAMPTZ,session_id UUID REFERENCES auth_session(id) ON DELETE CASCADE +); +CREATE TABLE password_reset_request (user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE); +INSERT INTO rol(id,name) VALUES(1,'admin'),(2,'user'),(9,'supervisor'); +INSERT INTO status(id,name,_table) VALUES(1,'Activo','users'),(2,'Deshabilitado','users'),(7,'Otro','users'); +INSERT INTO specialization(id,name) VALUES(3,'Soporte'); + +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);