add base of lab3

This commit is contained in:
2026-11-07 16:26:47 +03:00
parent ed976854d5
commit c1bd817abf
64 changed files with 4194 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
HELP.md
target/
.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
+3
View File
@@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
Vendored
+295
View File
@@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
+189
View File
@@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+123
View File
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.5</version>
<relativePath/>
</parent>
<groupId>com.vnp</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mtusi-messenger</name>
<properties>
<java.version>21</java.version>
<maven.compiler.release>21</maven.compiler.release>
</properties>
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- PostgreSQL -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Flyway -->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Boot Tests -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.78.1</version>
</dependency>
<!-- REST Assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring Boot Maven Plugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,63 @@
package com.vnp.demo;
import org.springframework.http.HttpStatus;
public class BusinessException extends RuntimeException {
private final String code;
private final HttpStatus status;
public BusinessException(String code, String message, HttpStatus status) {
super(message);
this.code = code;
this.status = status;
}
public String getCode() {
return code;
}
public HttpStatus getStatus() {
return status;
}
public static BusinessException notFound() {
return new BusinessException(
"not_found",
"Объект не найден",
HttpStatus.NOT_FOUND
);
}
public static BusinessException conflict() {
return conflict("Конфликт");
}
public static BusinessException conflict(String message) {
return new BusinessException(
"conflict",
message,
HttpStatus.CONFLICT
);
}
public static BusinessException unauthorized() {
return unauthorized("Пользователь не найден");
}
public static BusinessException unauthorized(String message) {
return new BusinessException(
"unauthorized",
message,
HttpStatus.UNAUTHORIZED
);
}
public static BusinessException invalid(String message) {
return new BusinessException(
"invalid_request",
message,
HttpStatus.BAD_REQUEST
);
}
}
@@ -0,0 +1,184 @@
package com.vnp.demo;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.Base64;
import java.util.UUID;
import org.springframework.stereotype.Component;
@Component
public class CursorCodec {
public record ChatCursor(Instant createdAt, UUID id) {
}
public record MessageCursor(Instant createdAt, UUID id) {
}
public String encodeIndex(int index) {
return Base64.getUrlEncoder()
.withoutPadding()
.encodeToString(
("i:" + index).getBytes(StandardCharsets.UTF_8)
);
}
public int decodeIndex(String cursor, int size) {
try {
String decoded = new String(
Base64.getUrlDecoder().decode(cursor),
StandardCharsets.UTF_8
);
if (!decoded.startsWith("i:")) {
throw new IllegalArgumentException();
}
int idx = Integer.parseInt(decoded.substring(2));
if (idx < 0 || idx > size) {
throw new IllegalArgumentException();
}
return idx;
} catch (IllegalArgumentException ex) {
throw BusinessException.invalid("Неверный cursor");
}
}
public String encodeChat(
UUID userId,
Instant createdAt,
UUID chatId
) {
String value = "chat:v1:"
+ userId + ":"
+ createdAt + ":"
+ chatId;
return Base64.getUrlEncoder()
.withoutPadding()
.encodeToString(
value.getBytes(StandardCharsets.UTF_8)
);
}
public ChatCursor decodeChat(String cursor, UUID userId) {
try {
String value = decodeBase64(cursor);
if (!value.startsWith("chat:v1:")) {
throw new IllegalArgumentException();
}
String content = value.substring("chat:v1:".length());
int firstSeparator = content.indexOf(':');
int lastSeparator = content.lastIndexOf(':');
if (firstSeparator < 0
|| lastSeparator <= firstSeparator) {
throw new IllegalArgumentException();
}
UUID cursorUserId = UUID.fromString(
content.substring(0, firstSeparator)
);
if (!cursorUserId.equals(userId)) {
throw new IllegalArgumentException();
}
Instant createdAt = Instant.parse(
content.substring(
firstSeparator + 1,
lastSeparator
)
);
UUID chatId = UUID.fromString(
content.substring(lastSeparator + 1)
);
return new ChatCursor(createdAt, chatId);
} catch (IllegalArgumentException | DateTimeParseException ex) {
throw BusinessException.invalid("Неверный cursor");
}
}
public String encodeMessage(
UUID chatId,
Instant createdAt,
UUID messageId
) {
String value = "message:v1:"
+ chatId + ":"
+ createdAt + ":"
+ messageId;
return Base64.getUrlEncoder()
.withoutPadding()
.encodeToString(
value.getBytes(StandardCharsets.UTF_8)
);
}
public MessageCursor decodeMessage(String cursor, UUID chatId) {
try {
String value = decodeBase64(cursor);
if (!value.startsWith("message:v1:")) {
throw new IllegalArgumentException();
}
String content = value.substring("message:v1:".length());
int firstSeparator = content.indexOf(':');
int lastSeparator = content.lastIndexOf(':');
if (firstSeparator < 0
|| lastSeparator <= firstSeparator) {
throw new IllegalArgumentException();
}
UUID cursorChatId = UUID.fromString(
content.substring(0, firstSeparator)
);
if (!cursorChatId.equals(chatId)) {
throw new IllegalArgumentException();
}
Instant createdAt = Instant.parse(
content.substring(
firstSeparator + 1,
lastSeparator
)
);
UUID messageId = UUID.fromString(
content.substring(lastSeparator + 1)
);
return new MessageCursor(createdAt, messageId);
} catch (IllegalArgumentException | DateTimeParseException ex) {
throw BusinessException.invalid("Неверный cursor");
}
}
private String decodeBase64(String cursor) {
if (cursor == null || cursor.isBlank()) {
throw new IllegalArgumentException();
}
return new String(
Base64.getUrlDecoder().decode(cursor),
StandardCharsets.UTF_8
);
}
}
@@ -0,0 +1,146 @@
package com.vnp.demo;
import org.slf4j.MDC;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import com.vnp.demo.dto.ErrorResponse;
import jakarta.servlet.http.HttpServletRequest;
@RestControllerAdvice
public class GlobalExceptionHandler {
private ErrorResponse build(String code, String msg) {
return new ErrorResponse(
new ErrorResponse.ErrorBody(
code,
msg,
MDC.get("requestId")
)
);
}
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ErrorResponse> handleBusiness(
BusinessException e,
HttpServletRequest request
) {
ResponseEntity.BodyBuilder builder =
ResponseEntity.status(e.getStatus());
if (e.getStatus() == HttpStatus.UNAUTHORIZED) {
String path = request.getRequestURI();
String challenge = path.equals("/api/v1/auth/sessions")
? "Basic realm=\"messenger\", charset=\"UTF-8\""
: "Bearer realm=\"messenger\"";
builder.header("WWW-Authenticate", challenge);
}
return builder.body(
build(e.getCode(), e.getMessage())
);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(
MethodArgumentNotValidException e
) {
String msg = e.getBindingResult()
.getFieldErrors()
.stream()
.findFirst()
.map(f -> f.getField() + ": " + f.getDefaultMessage())
.orElse("Ошибка валидации");
return ResponseEntity.badRequest()
.body(build("invalid_request", msg));
}
@ExceptionHandler({
HttpMessageNotReadableException.class,
MethodArgumentTypeMismatchException.class
})
public ResponseEntity<ErrorResponse> handleMalformed(Exception e) {
return ResponseEntity.badRequest()
.body(build(
"invalid_request",
"Неверный формат запроса"
));
}
@ExceptionHandler(NoResourceFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(
NoResourceFoundException e
) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(build(
"not_found",
"Ресурс не найден"
));
}
@ExceptionHandler(MissingRequestHeaderException.class)
public ResponseEntity<ErrorResponse> handleMissingHeader(
MissingRequestHeaderException e
) {
return ResponseEntity.badRequest()
.body(build(
"invalid_request",
"Отсутствует обязательный заголовок: "
+ e.getHeaderName()
));
}
@ExceptionHandler(DataAccessException.class)
public ResponseEntity<ErrorResponse> handleDataAccess(
DataAccessException e
) {
return ResponseEntity
.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(build(
"service_unavailable",
"Сервис временно недоступен"
));
}
@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<ErrorResponse> handleStatus(
ResponseStatusException e
) {
int status = e.getStatusCode().value();
String code = status == 503
? "service_unavailable"
: "request_failed";
String message = status == 503
? "Сервис временно недоступен"
: "Запрос не может быть выполнен";
return ResponseEntity.status(status)
.body(build(code, message));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneric(Exception e) {
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(build(
"internal_error",
"Внутренняя ошибка"
));
}
}
@@ -0,0 +1,13 @@
package com.vnp.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MessengerApplication {
public static void main(String[] args) {
SpringApplication.run(MessengerApplication.class, args);
}
}
@@ -0,0 +1,24 @@
package com.vnp.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Map;
@RestControllerAdvice
public class SessionStoreExceptionHandler {
@ExceptionHandler(SessionStoreUnavailableException.class)
public ResponseEntity<Map<String, String>> handleSessionStoreUnavailable(
SessionStoreUnavailableException ex
) {
return ResponseEntity
.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of(
"error", "SERVICE_UNAVAILABLE",
"message", "Session storage is temporarily unavailable"
));
}
}
@@ -0,0 +1,8 @@
package com.vnp.demo;
public class SessionStoreUnavailableException extends RuntimeException {
public SessionStoreUnavailableException(Throwable cause) {
super("Session storage is temporarily unavailable", cause);
}
}
@@ -0,0 +1,22 @@
package main.java.com.vnp.demo.config;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.cfg.CoercionAction;
import com.fasterxml.jackson.databind.cfg.CoercionInputShape;
import com.fasterxml.jackson.databind.type.LogicalType;
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer strictTextValues() {
return builder -> builder.postConfigurer(mapper ->
mapper.coercionConfigFor(LogicalType.Textual)
.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail)
.setCoercion(CoercionInputShape.Float, CoercionAction.Fail)
.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail));
}
}
@@ -0,0 +1,15 @@
package com.vnp.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
}
}
@@ -0,0 +1,75 @@
package com.vnp.demo.config;
import java.util.Map;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vnp.demo.filter.BearerAuthenticationFilter;
import com.vnp.demo.service.AuthService;
import jakarta.servlet.http.HttpServletResponse;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http,
AuthService authService,
ObjectMapper objectMapper
) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.httpBasic(basic -> basic.disable())
.formLogin(form -> form.disable())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.authorizeHttpRequests(auth -> auth
.requestMatchers(
"/health/live",
"/health/ready"
).permitAll()
.requestMatchers(
org.springframework.http.HttpMethod.POST,
"/api/v1/users",
"/api/v1/auth/sessions"
).permitAll()
.anyRequest().authenticated()
)
.exceptionHandling(ex -> ex
.authenticationEntryPoint((request, response, exception) -> {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader(
HttpHeaders.WWW_AUTHENTICATE,
"Bearer realm=\"messenger\""
);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
objectMapper.writeValue(
response.getWriter(),
Map.of("error", Map.of(
"code", "unauthorized",
"message", "Требуется авторизация",
"request_id", response.getHeader("X-Request-Id")
))
);
})
)
.addFilterBefore(
new BearerAuthenticationFilter(authService, objectMapper),
UsernamePasswordAuthenticationFilter.class
)
.build();
}
}
@@ -0,0 +1,93 @@
package com.vnp.demo.controllers;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.vnp.demo.BusinessException;
import com.vnp.demo.dto.SessionResponse;
import com.vnp.demo.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/api/v1/auth/sessions")
public class AuthController {
private final AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public SessionResponse login(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false)
String authorization,
HttpServletRequest request
) throws IOException {
if (request.getInputStream().read() != -1) {
throw BusinessException.invalid("Тело запроса создания сессии должно быть пустым");
}
if (authorization == null
|| !authorization.startsWith("Basic ")) {
throw BusinessException.unauthorized();
}
String encoded = authorization.substring(6).trim();
String credentials;
try {
byte[] decoded = Base64.getDecoder().decode(encoded);
credentials = StandardCharsets.UTF_8
.newDecoder()
.decode(ByteBuffer.wrap(decoded))
.toString();
} catch (IllegalArgumentException | CharacterCodingException ex) {
throw BusinessException.unauthorized();
}
int separator = credentials.indexOf(':');
if (separator < 0) {
throw BusinessException.unauthorized();
}
String username = credentials.substring(0, separator);
String password = credentials.substring(separator + 1);
if (!username.matches("[a-z0-9_]{3,32}")) {
throw BusinessException.unauthorized();
}
return authService.login(username, password);
}
@DeleteMapping("/current")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void logout(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false)
String authorization
) {
if (authorization == null
|| !authorization.startsWith("Bearer ")) {
throw BusinessException.unauthorized();
}
authService.logout(authorization.substring(7).trim());
}
}
@@ -0,0 +1,58 @@
package com.vnp.demo.controllers;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.vnp.demo.dto.ChatCreateRequest;
import com.vnp.demo.dto.ChatPageResponse;
import com.vnp.demo.dto.ChatResponse;
import com.vnp.demo.service.ChatService;
import jakarta.validation.Valid;
@RestController
@RequestMapping("/api/v1/chats")
public class ChatController {
private final ChatService chatService;
public ChatController(ChatService chatService) {
this.chatService = chatService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ChatResponse create(
@AuthenticationPrincipal UUID userId,
@Valid @RequestBody ChatCreateRequest request
) {
return chatService.create(userId, request);
}
@GetMapping
public ChatPageResponse list(
@AuthenticationPrincipal UUID userId,
@RequestParam(defaultValue = "50") int limit,
@RequestParam(required = false) String cursor
) {
return chatService.list(userId, limit, cursor);
}
@GetMapping("/{chat_id}")
public ChatResponse get(
@AuthenticationPrincipal UUID userId,
@PathVariable("chat_id") UUID chatId
) {
return chatService.get(userId, chatId);
}
}
@@ -0,0 +1,38 @@
package com.vnp.demo.controllers;
import org.springframework.boot.availability.ApplicationAvailability;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.vnp.demo.BusinessException;
import com.vnp.demo.dto.HealthResponse;
@RestController
@RequestMapping("/health")
public class HealthController {
private final JdbcTemplate jdbc;
private final StringRedisTemplate redis;
private final ApplicationAvailability availability;
public HealthController(JdbcTemplate jdbc, StringRedisTemplate redis, ApplicationAvailability availability) {
this.jdbc = jdbc; this.redis = redis; this.availability = availability;
}
@GetMapping("/live")
public HealthResponse live() { return HealthResponse.ok(); }
@GetMapping("/ready")
public HealthResponse ready() {
try {
if (availability.getReadinessState() != ReadinessState.ACCEPTING_TRAFFIC) throw new IllegalStateException();
if (!Integer.valueOf(1).equals(jdbc.queryForObject("SELECT 1", Integer.class))) throw new IllegalStateException();
String pong = redis.execute((org.springframework.data.redis.core.RedisCallback<String>) c -> c.ping());
if (!"PONG".equals(pong)) throw new IllegalStateException();
return HealthResponse.ok();
} catch (Exception ex) {
throw new BusinessException("unavailable", "Сервис не готов", HttpStatus.SERVICE_UNAVAILABLE);
}
}
}
@@ -0,0 +1,53 @@
package com.vnp.demo.controllers;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.vnp.demo.dto.MessageCreateRequest;
import com.vnp.demo.dto.MessagePageResponse;
import com.vnp.demo.dto.MessageResponse;
import com.vnp.demo.service.MessageService;
import jakarta.validation.Valid;
@RestController
@RequestMapping("/api/v1/chats/{chat_id}/messages")
public class MessageController {
private final MessageService messageService;
public MessageController(MessageService messageService) {
this.messageService = messageService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public MessageResponse create(
@AuthenticationPrincipal UUID userId,
@PathVariable("chat_id") UUID chatId,
@org.springframework.web.bind.annotation.RequestHeader("Idempotency-Key") String key,
@Valid @RequestBody MessageCreateRequest request
) {
return messageService.create(userId, chatId, request, key);
}
@GetMapping
public MessagePageResponse list(
@AuthenticationPrincipal UUID userId,
@PathVariable("chat_id") UUID chatId,
@RequestParam(defaultValue = "50") int limit,
@RequestParam(required = false) String cursor
) {
return messageService.list(userId, chatId, limit, cursor);
}
}
@@ -0,0 +1,44 @@
package com.vnp.demo.controllers;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.vnp.demo.dto.UserCreateRequest;
import com.vnp.demo.dto.UserResponse;
import com.vnp.demo.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public UserResponse register(
@Valid @RequestBody UserCreateRequest request
) {
return userService.register(request);
}
@GetMapping("/me")
public UserResponse getCurrent(
@AuthenticationPrincipal UUID userId
) {
return userService.getCurrent(userId);
}
}
@@ -0,0 +1,23 @@
package com.vnp.demo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.hibernate.validator.constraints.UniqueElements;
import java.util.List;
import java.util.UUID;
public record ChatCreateRequest(
@NotBlank
@Size(max = 100)
String title,
@NotEmpty
@Size(max = 100)
@UniqueElements
@JsonProperty("member_ids")
List<@NotNull UUID> memberIds
) {}
@@ -0,0 +1,10 @@
package com.vnp.demo.dto;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public record ChatPageResponse(
List<ChatResponse> items,
@JsonProperty("next_cursor") String nextCursor
) {}
@@ -0,0 +1,16 @@
package com.vnp.demo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public record ChatResponse(
UUID id,
String title,
@JsonProperty("member_ids")
List<UUID> memberIds,
@JsonProperty("created_at")
Instant createdAt
) {}
@@ -0,0 +1,14 @@
package com.vnp.demo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public record ErrorResponse(ErrorBody error) {
public record ErrorBody(
String code,
String message,
@JsonProperty("request_id")
String requestId
) {}
}
@@ -0,0 +1,6 @@
package com.vnp.demo.dto;
public record HealthResponse(String status) {
public static HealthResponse ok()
{ return new HealthResponse("ok"); }
}
@@ -0,0 +1,8 @@
package com.vnp.demo.dto;
import jakarta.validation.constraints.NotBlank;
public record MessageCreateRequest(
@NotBlank String text
) {
}
@@ -0,0 +1,10 @@
package com.vnp.demo.dto;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public record MessagePageResponse(
List<MessageResponse> items,
@JsonProperty("next_cursor") String nextCursor
) {}
@@ -0,0 +1,21 @@
package com.vnp.demo.dto;
import java.time.Instant;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonProperty;
public record MessageResponse(
UUID id,
@JsonProperty("chat_id")
UUID chat_id,
@JsonProperty("sender_id")
UUID sender_id,
String text,
@JsonProperty("created_at")
Instant createdAt
){}
@@ -0,0 +1,13 @@
package com.vnp.demo.dto;
import java.time.Instant;
import com.fasterxml.jackson.annotation.JsonProperty;
public record SessionResponse(
String token,
@JsonProperty("token_type") String tokenType,
@JsonProperty("expires_at") Instant expiresAt,
UserResponse user
) {
}
@@ -0,0 +1,18 @@
package com.vnp.demo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.*;
public record UserCreateRequest(
@NotBlank
@Pattern(regexp = "^[a-z0-9_]{3,32}$")
String username,
@JsonProperty("display_name")
@NotBlank
String displayName,
@NotNull
String password
) {}
@@ -0,0 +1,21 @@
package com.vnp.demo.dto;
import java.time.Instant;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonProperty;
public record UserResponse(
UUID id,
String username,
@JsonProperty("display_name")
String displayName,
@JsonProperty("created_at")
Instant createdAt
) {
}
@@ -0,0 +1,148 @@
package com.vnp.demo.filter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.server.ResponseStatusException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vnp.demo.BusinessException;
import com.vnp.demo.SessionStoreUnavailableException;
import com.vnp.demo.models.User;
import com.vnp.demo.service.AuthService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class BearerAuthenticationFilter extends OncePerRequestFilter {
private final AuthService authService;
private final ObjectMapper objectMapper;
public BearerAuthenticationFilter(
AuthService authService,
ObjectMapper objectMapper
) {
this.authService = authService;
this.objectMapper = objectMapper;
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain
) throws ServletException, IOException {
String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
if (authorization == null || !authorization.startsWith("Bearer ")) {
chain.doFilter(request, response);
return;
}
String token = authorization.substring(7).trim();
User user;
try {
user = authService.authenticate(token);
} catch (BusinessException ex) {
SecurityContextHolder.clearContext();
response.setHeader(
HttpHeaders.WWW_AUTHENTICATE,
"Bearer realm=\"messenger\""
);
writeError(
response,
HttpServletResponse.SC_UNAUTHORIZED,
"unauthorized",
"Недействительный токен"
);
return;
} catch (SessionStoreUnavailableException | DataAccessException | CannotCreateTransactionException ex) {
SecurityContextHolder.clearContext();
writeError(
response,
HttpServletResponse.SC_SERVICE_UNAVAILABLE,
"unavailable",
"Сервис временно недоступен"
);
return;
} catch (ResponseStatusException ex) {
SecurityContextHolder.clearContext();
if (ex.getStatusCode().value() == 503) {
writeError(
response,
HttpServletResponse.SC_SERVICE_UNAVAILABLE,
"unavailable",
"Сервис временно недоступен"
);
return;
}
throw ex;
}
try {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
user.getId(),
null,
List.of()
);
SecurityContextHolder.getContext()
.setAuthentication(authentication);
chain.doFilter(request, response);
} finally {
SecurityContextHolder.clearContext();
}
}
private void writeError(
HttpServletResponse response,
int status,
String code,
String message
) throws IOException {
response.setStatus(status);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
String requestId = response.getHeader("X-Request-Id");
objectMapper.writeValue(
response.getWriter(),
Map.of(
"error", Map.of(
"code", code,
"message", message,
"request_id",
requestId != null ? requestId : ""
)
)
);
}
}
@@ -0,0 +1,77 @@
package com.vnp.demo.filter;
import java.io.IOException;
import java.util.UUID;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestIdFilter extends OncePerRequestFilter {
private final String instanceId = System.getenv().getOrDefault("HOSTNAME", UUID.randomUUID().toString());
public static final String HEADER = "X-Request-Id";
public static final String MDC_KEY = "requestId";
private static final int MAX_REQUEST_ID_LENGTH = 128;
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain
) throws ServletException, IOException {
String requestId = request.getHeader(HEADER);
if (requestId == null
|| requestId.isBlank()
|| requestId.length() > MAX_REQUEST_ID_LENGTH
|| !isValidRequestId(requestId)) {
requestId = UUID.randomUUID()
.toString()
.replace("-", "");
}
response.setHeader(HEADER, requestId);
response.setHeader("X-Instance-Id", instanceId);
request.setAttribute(MDC_KEY, requestId);
MDC.put(MDC_KEY, requestId);
try {
chain.doFilter(request, response);
} finally {
MDC.remove(MDC_KEY);
}
}
private boolean isValidRequestId(String requestId) {
for (int i = 0; i < requestId.length(); i++) {
char c = requestId.charAt(i);
if (!(
(c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '-'
|| c == '_'
)) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,46 @@
package com.vnp.demo.models;
import java.time.Instant;
import java.util.UUID;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "chats")
public class Chat {
@Id
private UUID id = UUID.randomUUID();
@Column(nullable = false, length = 400)
private String title;
@Column(name = "created_at", nullable = false)
private Instant createdAt = Instant.now();
protected Chat() {
}
public Chat(String title) {
this.title = title;
}
public UUID getId() {
return id;
}
public String getTitle() {
return title;
}
public Instant getCreatedAt() {
return createdAt;
}
public void setTitle(String title) {
this.title = title;
}
}
@@ -0,0 +1,45 @@
package com.vnp.demo.models;
import jakarta.persistence.*;
@Entity
@Table(name = "chat_members")
public class ChatMember {
@EmbeddedId
private ChatMemberId id;
@MapsId("chatId")
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "chat_id", nullable = false)
private Chat chat;
@MapsId("userId")
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private User user;
protected ChatMember() {
}
public ChatMember(Chat chat, User user) {
this.chat = chat;
this.user = user;
this.id = new ChatMemberId(
chat.getId(),
user.getId()
);
}
public ChatMemberId getId() {
return id;
}
public Chat getChat() {
return chat;
}
public User getUser() {
return user;
}
}
@@ -0,0 +1,53 @@
package com.vnp.demo.models;
import java.io.Serializable;
import java.util.Objects;
import java.util.UUID;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
@Embeddable
public class ChatMemberId implements Serializable {
@Column(name = "chat_id", nullable = false)
private UUID chatId;
@Column(name = "user_id", nullable = false)
private UUID userId;
protected ChatMemberId() {
}
public ChatMemberId(UUID chatId, UUID userId) {
this.chatId = chatId;
this.userId = userId;
}
public UUID getChatId() {
return chatId;
}
public UUID getUserId() {
return userId;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ChatMemberId other)) {
return false;
}
return Objects.equals(chatId, other.chatId)
&& Objects.equals(userId, other.userId);
}
@Override
public int hashCode() {
return Objects.hash(chatId, userId);
}
}
@@ -0,0 +1,63 @@
package com.vnp.demo.models;
import java.time.Instant;
import java.util.UUID;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "messages")
public class Message {
@Id
private UUID id = UUID.randomUUID();
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "chat_id", nullable = false)
private Chat chat;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "sender_id", nullable = false)
private User sender;
@Column(name = "text", nullable = false, columnDefinition = "text")
private String text;
@Column(name = "created_at", nullable = false)
private Instant createdAt = Instant.now();
protected Message() {
}
public Message(Chat chat, User sender, String text) {
this.chat = chat;
this.sender = sender;
this.text = text;
}
public UUID getId() {
return id;
}
public Chat getChat() {
return chat;
}
public User getSender() {
return sender;
}
public String getText() {
return text;
}
public Instant getCreatedAt() {
return createdAt;
}
}
@@ -0,0 +1,90 @@
package com.vnp.demo.models;
import java.sql.Types;
import java.time.Instant;
import java.util.UUID;
import org.hibernate.annotations.JdbcTypeCode;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "sessions")
public class Session {
@Id
private UUID id = UUID.randomUUID();
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@JdbcTypeCode(Types.CHAR)
@Column(
name = "token_hash",
nullable = false,
unique = true,
length = 64,
columnDefinition = "CHAR(64)"
)
private String tokenHash;
@Column(name = "expires_at", nullable = false)
private Instant expiresAt;
@Column(name = "revoked_at")
private Instant revokedAt;
@Column(name = "created_at", nullable = false)
private Instant createdAt = Instant.now();
protected Session() {
}
public Session(User user, String tokenHash, Instant expiresAt) {
this.user = user;
this.tokenHash = tokenHash;
this.expiresAt = expiresAt;
}
public UUID getId() {
return id;
}
public User getUser() {
return user;
}
public String getTokenHash() {
return tokenHash;
}
public Instant getExpiresAt() {
return expiresAt;
}
public Instant getRevokedAt() {
return revokedAt;
}
public Instant getCreatedAt() {
return createdAt;
}
public boolean isValid() {
return revokedAt == null
&& expiresAt.isAfter(Instant.now());
}
public void revoke() {
if (revokedAt == null) {
revokedAt = Instant.now();
}
}
}
@@ -0,0 +1,63 @@
package com.vnp.demo.models;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
private UUID id = UUID.randomUUID();
@Column(nullable = false, unique = true, length = 32)
private String username;
@Column(name = "display_name", nullable = false)
private String displayName;
@Column(name = "password_hash", nullable = false)
private String passwordHash;
@Column(name = "created_at", nullable = false)
private Instant createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
protected User() {
}
public User(String username, String displayName, String passwordHash) {
this.username = username;
this.displayName = displayName;
this.passwordHash = passwordHash;
}
public UUID getId() {
return id;
}
public String getUsername() {
return username;
}
public String getDisplayName() {
return displayName;
}
public String getPasswordHash() {
return passwordHash;
}
public Instant getCreatedAt() {
return createdAt;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
}
@@ -0,0 +1,19 @@
package com.vnp.demo.repositories;
import java.util.List;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import com.vnp.demo.models.ChatMember;
import com.vnp.demo.models.ChatMemberId;
public interface ChatMemberRepository
extends JpaRepository<ChatMember, ChatMemberId> {
boolean existsByIdChatIdAndIdUserId(UUID chatId, UUID userId);
List<ChatMember> findByIdChatId(UUID chatId);
boolean existsByChat_IdAndUser_Id(UUID chatId, UUID userId);
}
@@ -0,0 +1,56 @@
package com.vnp.demo.repositories;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.vnp.demo.models.Chat;
public interface ChatRepository extends JpaRepository<Chat, UUID> {
@Query("""
SELECT c
FROM Chat c
WHERE EXISTS (
SELECT 1
FROM ChatMember cm
WHERE cm.chat.id = c.id
AND cm.user.id = :userId
)
ORDER BY c.createdAt ASC, c.id ASC
""")
List<Chat> findFirstPage(
@Param("userId") UUID userId,
Pageable pageable
);
@Query("""
SELECT c
FROM Chat c
WHERE EXISTS (
SELECT 1
FROM ChatMember cm
WHERE cm.chat.id = c.id
AND cm.user.id = :userId
)
AND (
c.createdAt > :cursorTime
OR (
c.createdAt = :cursorTime
AND c.id > :cursorId
)
)
ORDER BY c.createdAt ASC, c.id ASC
""")
List<Chat> findNextPage(
@Param("userId") UUID userId,
@Param("cursorTime") Instant cursorTime,
@Param("cursorId") UUID cursorId,
Pageable pageable
);
}
@@ -0,0 +1,40 @@
package com.vnp.demo.repositories;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.vnp.demo.models.Message;
public interface MessageRepository extends JpaRepository<Message, UUID> {
@Query(value = """
SELECT m.*
FROM messages m
WHERE m.chat_id = :chatId
ORDER BY m.created_at ASC, m.id ASC
""", nativeQuery = true)
List<Message> findFirstPage(
@Param("chatId") UUID chatId,
Pageable pageable
);
@Query(value = """
SELECT m.*
FROM messages m
WHERE m.chat_id = :chatId
AND (m.created_at, m.id) > (:cursorTime, :cursorId)
ORDER BY m.created_at ASC, m.id ASC
""", nativeQuery = true)
List<Message> findNextPage(
@Param("chatId") UUID chatId,
@Param("cursorTime") Instant cursorTime,
@Param("cursorId") UUID cursorId,
Pageable pageable
);
}
@@ -0,0 +1,12 @@
package com.vnp.demo.repositories;
import com.vnp.demo.models.Session;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
import java.util.UUID;
public interface SessionRepository extends JpaRepository<Session, UUID> {
Optional<Session> findByTokenHash(String tokenHash);
}
@@ -0,0 +1,14 @@
package com.vnp.demo.repositories;
import com.vnp.demo.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
import java.util.UUID;
public interface UserRepository extends JpaRepository<User, UUID> {
Optional<User> findByUsername(String username);
boolean existsByUsername(String username);
}
@@ -0,0 +1,143 @@
package com.vnp.demo.service;
import com.vnp.demo.BusinessException;
import com.vnp.demo.dto.SessionResponse;
import com.vnp.demo.dto.UserResponse;
import com.vnp.demo.models.Session;
import com.vnp.demo.models.User;
import com.vnp.demo.repositories.SessionRepository;
import com.vnp.demo.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64;
import java.util.HexFormat;
@Service
public class AuthService {
private static final SecureRandom RANDOM = new SecureRandom();
private final UserRepository userRepository;
private final SessionRepository sessionRepository;
private final SessionCacheService sessionCacheService;
private final PasswordEncoder passwordEncoder;
private final TransactionTemplate transactions;
private final long sessionTtlSeconds;
public AuthService(
UserRepository userRepository,
SessionRepository sessionRepository,
SessionCacheService sessionCacheService,
PasswordEncoder passwordEncoder,
PlatformTransactionManager transactionManager,
@Value("${app.session.ttl-seconds:3600}") long sessionTtlSeconds
) {
if (sessionTtlSeconds <= 0) {
throw new IllegalArgumentException("Session TTL must be positive");
}
this.userRepository = userRepository;
this.sessionRepository = sessionRepository;
this.sessionCacheService = sessionCacheService;
this.passwordEncoder = passwordEncoder;
this.transactions = new TransactionTemplate(transactionManager);
this.sessionTtlSeconds = sessionTtlSeconds;
}
public SessionResponse login(String username, String password) {
byte[] bytes = new byte[32];
RANDOM.nextBytes(bytes);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
String tokenHash = hashToken(token);
Instant expiresAt = Instant.now().plusSeconds(sessionTtlSeconds);
// TransactionTemplate returns only after the database commit completes.
UserResponse userResponse = transactions.execute(status -> {
User user = userRepository.findByUsername(username)
.orElseThrow(BusinessException::unauthorized);
if (!passwordEncoder.matches(password, user.getPasswordHash())) {
throw BusinessException.unauthorized();
}
sessionRepository.save(new Session(user, tokenHash, expiresAt));
return new UserResponse(
user.getId(), user.getUsername(),
user.getDisplayName(), user.getCreatedAt()
);
});
// Never publish a usable token before the PostgreSQL commit.
// If Redis fails, the DB row remains inert: it cannot authenticate.
try {
sessionCacheService.cache(tokenHash, userResponse.id(), expiresAt);
} catch (RuntimeException activationFailure) {
// The token is never returned. Best-effort cleanup handles an
// uncertain Redis write and records the failed activation in PG.
try {
sessionCacheService.invalidate(tokenHash);
} catch (RuntimeException cleanupFailure) {
activationFailure.addSuppressed(cleanupFailure);
}
try {
transactions.executeWithoutResult(status ->
sessionRepository.findByTokenHash(tokenHash)
.ifPresent(Session::revoke)
);
} catch (RuntimeException cleanupFailure) {
activationFailure.addSuppressed(cleanupFailure);
}
throw activationFailure;
}
return new SessionResponse(token, "Bearer", expiresAt, userResponse);
}
public User authenticate(String token) {
if (token == null || token.isBlank()) {
throw BusinessException.unauthorized();
}
var cached = sessionCacheService.find(hashToken(token))
.orElseThrow(BusinessException::unauthorized);
return userRepository.findById(cached.userId())
.orElseThrow(BusinessException::unauthorized);
}
public void logout(String token) {
if (token == null || token.isBlank()) {
throw BusinessException.unauthorized();
}
String tokenHash = hashToken(token);
if (sessionCacheService.find(tokenHash).isEmpty()) {
throw BusinessException.unauthorized();
}
if (!sessionCacheService.invalidate(tokenHash)) {
throw BusinessException.unauthorized();
}
transactions.executeWithoutResult(status -> {
Session session = sessionRepository.findByTokenHash(tokenHash)
.orElseThrow(() -> new ResponseStatusException(
HttpStatus.SERVICE_UNAVAILABLE, "Session record unavailable"));
session.revoke();
});
}
private String hashToken(String token) {
try {
byte[] hash = MessageDigest.getInstance("SHA-256")
.digest(token.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(hash);
} catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("SHA-256 unavailable", ex);
}
}
}
@@ -0,0 +1,195 @@
package com.vnp.demo.service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.vnp.demo.BusinessException;
import com.vnp.demo.CursorCodec;
import com.vnp.demo.dto.ChatCreateRequest;
import com.vnp.demo.dto.ChatPageResponse;
import com.vnp.demo.dto.ChatResponse;
import com.vnp.demo.models.Chat;
import com.vnp.demo.models.ChatMember;
import com.vnp.demo.models.User;
import com.vnp.demo.repositories.ChatMemberRepository;
import com.vnp.demo.repositories.ChatRepository;
import com.vnp.demo.repositories.UserRepository;
@Service
public class ChatService {
private final ChatRepository chatRepository;
private final ChatMemberRepository chatMemberRepository;
private final UserRepository userRepository;
private final CursorCodec cursorCodec;
public ChatService(
ChatRepository chatRepository,
ChatMemberRepository chatMemberRepository,
UserRepository userRepository,
CursorCodec cursorCodec
) {
this.chatRepository = chatRepository;
this.chatMemberRepository = chatMemberRepository;
this.userRepository = userRepository;
this.cursorCodec = cursorCodec;
}
@Transactional
public ChatResponse create(
UUID currentUserId,
ChatCreateRequest request
) {
String title = request.title();
if (title == null
|| title.isBlank()
|| title.codePointCount(0, title.length()) > 100) {
throw BusinessException.invalid(
"Некорректное название чата"
);
}
List<UUID> memberIds = request.memberIds();
if (memberIds == null
|| memberIds.isEmpty()
|| !memberIds.contains(currentUserId)) {
throw BusinessException.invalid(
"Создатель должен быть участником чата"
);
}
if (memberIds.stream().distinct().count() != memberIds.size()) {
throw BusinessException.invalid(
"Список участников содержит дубликаты"
);
}
List<User> users = userRepository.findAllById(memberIds);
if (users.size() != memberIds.size()) {
throw BusinessException.invalid("Один или несколько участников не найдены");
}
// Создаём чат через конструктор существующей модели.
Chat chat = new Chat(title);
chatRepository.save(chat);
// Создание чата и участников происходит в одной транзакции.
for (User user : users) {
ChatMember member = new ChatMember(chat, user);
chatMemberRepository.save(member);
}
return toResponse(chat, memberIds);
}
@Transactional(readOnly = true)
public ChatResponse get(
UUID currentUserId,
UUID chatId
) {
Chat chat = chatRepository.findById(chatId)
.orElseThrow(BusinessException::notFound);
if (!chatMemberRepository.existsByIdChatIdAndIdUserId(
chatId,
currentUserId
)) {
throw BusinessException.notFound();
}
return toResponse(chat, getMemberIds(chatId));
}
@Transactional(readOnly = true)
public ChatPageResponse list(
UUID currentUserId,
Integer limit,
String cursor
) {
int pageSize = limit == null ? 20 : limit;
if (pageSize < 1 || pageSize > 100) {
throw BusinessException.invalid(
"limit должен быть от 1 до 100"
);
}
List<Chat> chats;
if (cursor == null) {
chats = chatRepository.findFirstPage(
currentUserId,
PageRequest.of(0, pageSize + 1)
);
} else {
CursorCodec.ChatCursor decoded =
cursorCodec.decodeChat(cursor, currentUserId);
chats = chatRepository.findNextPage(
currentUserId,
decoded.createdAt(),
decoded.id(),
PageRequest.of(0, pageSize + 1)
);
}
boolean hasNext = chats.size() > pageSize;
List<Chat> page = hasNext
? chats.subList(0, pageSize)
: chats;
List<ChatResponse> items = new ArrayList<>();
for (Chat chat : page) {
items.add(
toResponse(
chat,
getMemberIds(chat.getId())
)
);
}
String nextCursor = null;
if (hasNext && !page.isEmpty()) {
Chat last = page.get(page.size() - 1);
nextCursor = cursorCodec.encodeChat(
currentUserId,
last.getCreatedAt(),
last.getId()
);
}
return new ChatPageResponse(items, nextCursor);
}
private List<UUID> getMemberIds(UUID chatId) {
return chatMemberRepository.findByIdChatId(chatId)
.stream()
.map(member -> member.getId().getUserId())
.sorted()
.toList();
}
private ChatResponse toResponse(
Chat chat,
List<UUID> memberIds
) {
return new ChatResponse(
chat.getId(),
chat.getTitle(),
memberIds,
chat.getCreatedAt()
);
}
}
@@ -0,0 +1,212 @@
package com.vnp.demo.service;
import java.util.List;
import java.util.UUID;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.vnp.demo.BusinessException;
import com.vnp.demo.CursorCodec;
import com.vnp.demo.dto.MessageCreateRequest;
import com.vnp.demo.dto.MessagePageResponse;
import com.vnp.demo.dto.MessageResponse;
import com.vnp.demo.models.Chat;
import com.vnp.demo.models.Message;
import com.vnp.demo.models.User;
import com.vnp.demo.repositories.ChatMemberRepository;
import com.vnp.demo.repositories.ChatRepository;
import com.vnp.demo.repositories.MessageRepository;
import com.vnp.demo.repositories.UserRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
@Service
public class MessageService {
private final MessageRepository messageRepository;
private final ChatRepository chatRepository;
private final ChatMemberRepository chatMemberRepository;
private final UserRepository userRepository;
private final CursorCodec cursorCodec;
@PersistenceContext
private EntityManager entityManager;
public MessageService(
MessageRepository messageRepository,
ChatRepository chatRepository,
ChatMemberRepository chatMemberRepository,
UserRepository userRepository,
CursorCodec cursorCodec
) {
this.messageRepository = messageRepository;
this.chatRepository = chatRepository;
this.chatMemberRepository = chatMemberRepository;
this.userRepository = userRepository;
this.cursorCodec = cursorCodec;
}
@Transactional
public MessageResponse create(
UUID userId,
UUID chatId,
MessageCreateRequest request, String key
) {
if (key == null || !key.matches("[A-Za-z0-9._:-]{1,128}")) {
throw BusinessException.invalid("Некорректный Idempotency-Key");
}
checkAccess(userId, chatId);
if (request == null
|| request.text() == null
|| request.text().isBlank()
|| request.text().codePointCount(
0,
request.text().length()
) > 4000) {
throw BusinessException.invalid(
"Текст сообщения должен содержать от 1 до 4000 символов"
);
}
String scope = userId + ":" + chatId + ":" + key;
entityManager.createNativeQuery("SELECT 1 FROM pg_advisory_xact_lock(hashtextextended(:scope, 0))")
.setParameter("scope", scope).getResultList();
@SuppressWarnings("unchecked")
List<Object[]> existing = entityManager.createNativeQuery(
"SELECT message_id, request_text FROM message_idempotency " +
"WHERE user_id = :user AND chat_id = :chat AND key = :key")
.setParameter("user", userId).setParameter("chat", chatId)
.setParameter("key", key).getResultList();
if (!existing.isEmpty()) {
Object[] row = existing.get(0);
if (!request.text().equals(row[1])) {
throw BusinessException.conflict("Ключ уже использован с другим сообщением");
}
return toResponse(messageRepository.findById((UUID) row[0]).orElseThrow());
}
Chat chat = chatRepository.findById(chatId)
.orElseThrow(BusinessException::notFound);
User sender = userRepository.findById(userId)
.orElseThrow(BusinessException::unauthorized);
Message message = new Message(
chat,
sender,
request.text()
);
Message saved = messageRepository.saveAndFlush(message);
// Перечитываем значения, фактически сохранённые PostgreSQL.
entityManager.refresh(saved);
entityManager.createNativeQuery(
"INSERT INTO message_idempotency(user_id, chat_id, key, request_text, message_id) " +
"VALUES (:user, :chat, :key, :text, :message)")
.setParameter("user", userId).setParameter("chat", chatId)
.setParameter("key", key).setParameter("text", request.text())
.setParameter("message", saved.getId()).executeUpdate();
return toResponse(saved);
}
@Transactional(readOnly = true)
public MessagePageResponse list(
UUID userId,
UUID chatId,
int limit,
String cursor
) {
checkAccess(userId, chatId);
if (limit < 1 || limit > 100) {
throw BusinessException.invalid(
"limit должен быть от 1 до 100"
);
}
CursorCodec.MessageCursor position = null;
if (cursor != null) {
position = cursorCodec.decodeMessage(cursor, chatId);
}
List<Message> messages;
if (position == null) {
messages = messageRepository.findFirstPage(
chatId,
PageRequest.of(0, limit + 1)
);
} else {
messages = messageRepository.findNextPage(
chatId,
position.createdAt(),
position.id(),
PageRequest.of(0, limit + 1)
);
}
boolean hasNext = messages.size() > limit;
List<Message> page = hasNext
? messages.subList(0, limit)
: messages;
List<MessageResponse> items = page.stream()
.map(this::toResponse)
.toList();
String nextCursor = null;
if (hasNext && !page.isEmpty()) {
Message last = page.get(page.size() - 1);
nextCursor = cursorCodec.encodeMessage(
chatId,
last.getCreatedAt(),
last.getId()
);
}
return new MessagePageResponse(
items,
nextCursor
);
}
private void checkAccess(
UUID userId,
UUID chatId
) {
boolean isMember = chatMemberRepository
.existsByIdChatIdAndIdUserId(
chatId,
userId
);
if (!isMember) {
throw BusinessException.notFound();
}
}
private MessageResponse toResponse(Message message) {
return new MessageResponse(
message.getId(),
message.getChat().getId(),
message.getSender().getId(),
message.getText(),
message.getCreatedAt()
);
}
}
@@ -0,0 +1,72 @@
package com.vnp.demo.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vnp.demo.SessionStoreUnavailableException;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
@Service
public class SessionCacheService {
private static final String PREFIX = "session:";
private final StringRedisTemplate redis;
private final ObjectMapper mapper;
public SessionCacheService(StringRedisTemplate redis, ObjectMapper mapper) {
this.redis = redis;
this.mapper = mapper;
}
public record CachedSession(UUID userId, Instant expiresAt) {}
public Optional<CachedSession> find(String tokenHash) {
try {
String json = redis.opsForValue().get(PREFIX + tokenHash);
if (json == null) return Optional.empty();
CachedSession session = mapper.readValue(json, CachedSession.class);
if (!session.expiresAt().isAfter(Instant.now())) return Optional.empty();
return Optional.of(session);
} catch (DataAccessException ex) {
throw unavailable(ex);
} catch (JsonProcessingException | IllegalArgumentException ex) {
throw unavailable(ex);
}
}
public void cache(String tokenHash, UUID userId, Instant expiresAt) {
Duration ttl = Duration.between(Instant.now(), expiresAt);
if (ttl.isNegative() || ttl.isZero()) {
throw new IllegalStateException("Session already expired");
}
try {
String json = mapper.writeValueAsString(new CachedSession(userId, expiresAt));
redis.opsForValue().set(PREFIX + tokenHash, json, ttl);
} catch (DataAccessException ex) {
throw unavailable(ex);
} catch (JsonProcessingException ex) {
throw new IllegalStateException("Cannot serialize session", ex);
}
}
public boolean invalidate(String tokenHash) {
try {
Boolean deleted = redis.delete(PREFIX + tokenHash);
return Boolean.TRUE.equals(deleted);
} catch (DataAccessException ex) {
throw new SessionStoreUnavailableException(ex);
}
}
private ResponseStatusException unavailable(Exception ex) {
return new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Session store unavailable", ex);
}
}
@@ -0,0 +1,86 @@
package com.vnp.demo.service;
import java.util.UUID;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import com.vnp.demo.BusinessException;
import com.vnp.demo.dto.UserCreateRequest;
import com.vnp.demo.dto.UserResponse;
import com.vnp.demo.models.User;
import com.vnp.demo.repositories.UserRepository;
import com.vnp.demo.validation.UserInputValidator;
@Service
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final TransactionTemplate transactionTemplate;
public UserService(
UserRepository userRepository,
PasswordEncoder passwordEncoder,
TransactionTemplate transactionTemplate
) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.transactionTemplate = transactionTemplate;
}
public UserResponse register(UserCreateRequest request) {
String username = request.username();
String displayName = request.displayName();
String password = request.password();
UserInputValidator.validate(displayName, password);
String passwordHash = passwordEncoder.encode(password);
try {
return transactionTemplate.execute(status -> {
if (userRepository.existsByUsername(username)) {
throw BusinessException.conflict("Username already exists");
}
User user = new User(
username,
displayName,
passwordHash
);
User saved = userRepository.saveAndFlush(user);
return toResponse(saved);
});
} catch (DataIntegrityViolationException ex) {
throw BusinessException.conflict(
"Username already exists"
);
}
}
@org.springframework.transaction.annotation.Transactional(readOnly = true)
public UserResponse getCurrent(UUID userId) {
User user = userRepository.findById(userId)
.orElseThrow(BusinessException::notFound);
return toResponse(user);
}
public UserResponse toResponse(User user) {
return new UserResponse(
user.getId(),
user.getUsername(),
user.getDisplayName(),
user.getCreatedAt()
);
}
}
@@ -0,0 +1,32 @@
package com.vnp.demo.validation;
import com.vnp.demo.BusinessException;
public final class UserInputValidator {
private UserInputValidator() {
}
public static void validate(String displayName, String password) {
if (displayName == null
|| displayName.isBlank()
|| codePoints(displayName) > 100) {
throw BusinessException.invalid(
"Некорректное отображаемое имя"
);
}
if (password == null
|| codePoints(password) < 12
|| codePoints(password) > 128) {
throw BusinessException.invalid(
"Пароль должен содержать от 12 до 128 символов"
);
}
}
private static int codePoints(String value) {
return value.codePointCount(0, value.length());
}
}
+49
View File
@@ -0,0 +1,49 @@
server:
shutdown: graceful
tomcat:
threads:
max: 64
connection-timeout: 2s
spring:
application:
name: messenger
lifecycle:
timeout-per-shutdown-phase: 15s
jackson:
default-property-inclusion: always
deserialization:
fail-on-unknown-properties: true
fail-on-trailing-tokens: true
mapper:
allow-coercion-of-scalars: false
datasource:
url: ${DB_URL:jdbc:postgresql://localhost:5432/messenger}
username: ${DB_USERNAME:messenger}
password: ${DB_PASSWORD:messenger}
hikari:
maximum-pool-size: ${DB_POOL_SIZE:8}
minimum-idle: 1
connection-timeout: 1000
validation-timeout: 500
data-source-properties:
connectTimeout: 2
socketTimeout: 8
options: "-c statement_timeout=5000 -c lock_timeout=3000"
data:
redis:
host: ${REDIS_HOST:localhost}
port: 6379
password: ${REDIS_PASSWORD:}
timeout: 1s
connect-timeout: 1s
flyway:
enabled: ${FLYWAY_ENABLED:true}
jpa:
hibernate:
ddl-auto: validate
open-in-view: false
transaction:
default-timeout: 8s
app:
session:
ttl-seconds: 86400
@@ -0,0 +1,77 @@
CREATE TABLE users (
id UUID PRIMARY KEY,
username VARCHAR(32) NOT NULL UNIQUE,
display_name VARCHAR(400) NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT chk_username
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT chk_display_name
CHECK (
char_length(display_name) BETWEEN 1 AND 100
AND length(btrim(display_name)) > 0
)
);
CREATE TABLE chats (
id UUID PRIMARY KEY,
title VARCHAR(400) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT chk_chat_title
CHECK (
char_length(title) BETWEEN 1 AND 100
AND length(btrim(title)) > 0
)
);
CREATE TABLE chat_members (
chat_id UUID NOT NULL REFERENCES chats(id),
user_id UUID NOT NULL REFERENCES users(id),
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE messages (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id),
sender_id UUID NOT NULL,
text VARCHAR(16000) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT fk_message_membership
FOREIGN KEY (chat_id, sender_id)
REFERENCES chat_members(chat_id, user_id),
CONSTRAINT chk_message_text
CHECK (
char_length(text) BETWEEN 1 AND 4000
AND length(btrim(text)) > 0
)
);
CREATE TABLE sessions (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id),
token_hash CHAR(64) NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL,
revoked_at TIMESTAMPTZ,
CONSTRAINT chk_session_expiry
CHECK (expires_at > created_at)
);
CREATE INDEX idx_chat_members_user
ON chat_members(user_id, chat_id);
CREATE INDEX idx_chats_history
ON chats(created_at, id);
CREATE INDEX idx_messages_history
ON messages(chat_id, created_at, id);
CREATE INDEX idx_sessions_user
ON sessions(user_id);
@@ -0,0 +1,9 @@
CREATE TABLE message_idempotency (
user_id UUID NOT NULL REFERENCES users(id),
chat_id UUID NOT NULL REFERENCES chats(id),
key VARCHAR(128) COLLATE "C" NOT NULL,
request_text TEXT NOT NULL,
message_id UUID NOT NULL UNIQUE REFERENCES messages(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, chat_id, key)
);
@@ -0,0 +1,89 @@
package com.vnp.demo;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import com.vnp.demo.dto.UserCreateRequest;
import com.vnp.demo.repositories.UserRepository;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ConcurrentRegistrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private UserRepository userRepository;
@Test
void concurrentRegistrationAllowsOnlyOneUser() throws Exception {
String username = "race_" +
UUID.randomUUID().toString().substring(0, 8);
UserCreateRequest request = new UserCreateRequest(
username,
"Race Test",
"Password123!"
);
ExecutorService executor = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
Callable<ResponseEntity<String>> task = () -> {
start.await();
return restTemplate.postForEntity(
"/api/v1/users",
request,
String.class
);
};
Future<ResponseEntity<String>> first =
executor.submit(task);
Future<ResponseEntity<String>> second =
executor.submit(task);
start.countDown();
int status1 = first.get(15, TimeUnit.SECONDS)
.getStatusCode().value();
int status2 = second.get(15, TimeUnit.SECONDS)
.getStatusCode().value();
assertTrue(
(status1 == 201 && status2 == 409)
|| (status1 == 409 && status2 == 201),
"Expected 201 and 409, got " +
status1 + " and " + status2
);
assertEquals(
1,
userRepository.findAll().stream()
.filter(user ->
username.equals(user.getUsername()))
.count()
);
} finally {
executor.shutdownNow();
}
}
}
@@ -0,0 +1,155 @@
package com.vnp.demo;
import java.time.Instant;
import java.util.UUID;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.vnp.demo.models.User;
import com.vnp.demo.repositories.UserRepository;
import com.vnp.demo.service.SessionCacheService;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.given;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class InfrastructureFailureIntegrationTest {
@LocalServerPort
private int port;
@SpyBean
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@SpyBean
private SessionCacheService sessionCacheService;
private String username;
private final String password = "Password123!";
@BeforeEach
void setUp() {
RestAssured.baseURI = "http://localhost";
RestAssured.port = port;
username = "failure_" + UUID.randomUUID()
.toString()
.substring(0, 8);
User user = new User(
username,
"Failure Test",
passwordEncoder.encode(password)
);
userRepository.saveAndFlush(user);
}
@Test
void redisUnavailableDuringLoginReturns503() {
doThrow(new DataAccessResourceFailureException(
"Redis unavailable"
)).when(sessionCacheService).cache(
anyString(),
any(UUID.class),
any(Instant.class)
);
given()
.auth()
.preemptive()
.basic(username, password)
.when()
.post("/api/v1/auth/sessions")
.then()
.statusCode(503)
.body(
"error.code",
equalTo("service_unavailable")
);
}
@Test
void anonymousUserCannotBypassAuthentication() {
given()
.header(
"X-User-Id",
UUID.randomUUID().toString()
)
.when()
.get("/api/v1/users/me")
.then()
.statusCode(401);
}
@Test
void redisUnavailableDuringAuthenticationDoesNotGrantAccess() {
String token = given()
.auth()
.preemptive()
.basic(username, password)
.when()
.post("/api/v1/auth/sessions")
.then()
.statusCode(201)
.extract()
.path("token");
doThrow(new DataAccessResourceFailureException(
"Redis unavailable"
)).when(sessionCacheService).find(anyString());
given()
.header(
"Authorization",
"Bearer " + token
)
.when()
.get("/api/v1/users/me")
.then()
.statusCode(503)
.body(
"error.code",
equalTo("service_unavailable")
);
}
@Test
void databaseUnavailableDuringLoginReturns503() {
doThrow(new DataAccessResourceFailureException(
"PostgreSQL unavailable"
)).when(userRepository).findByUsername(
eq(username)
);
given()
.auth()
.preemptive()
.basic(username, password)
.when()
.post("/api/v1/auth/sessions")
.then()
.statusCode(503)
.body(
"error.code",
equalTo("service_unavailable")
);
}
}
@@ -0,0 +1,154 @@
package com.vnp.demo;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vnp.demo.models.User;
import com.vnp.demo.repositories.UserRepository;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.given;
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "app.session.ttl-seconds=2"
)
class SessionIntegrationTest {
private static final String PASSWORD = "TestPassword123!";
@LocalServerPort
private int port;
@Autowired
private ObjectMapper mapper;
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
private String username;
@BeforeEach
void setUp() {
RestAssured.baseURI = "http://localhost";
RestAssured.port = port;
username = "test_" + UUID.randomUUID()
.toString().substring(0, 8);
userRepository.saveAndFlush(
new User(
username,
"Test User",
passwordEncoder.encode(PASSWORD)
)
);
}
private String login(String password) throws Exception {
String credentials = username + ":" + password;
String basic = Base64.getEncoder().encodeToString(
credentials.getBytes(StandardCharsets.UTF_8)
);
var response = given()
.header("Authorization", "Basic " + basic)
.post("/api/v1/auth/sessions");
response.then().log().all();
response.then().statusCode(201);
JsonNode json = mapper.readTree(response.asString());
return json.get("token").asText();
}
@Test
void validSessionAllowsAccess() throws Exception {
String token = login(PASSWORD);
given()
.header("Authorization", "Bearer " + token)
.get("/api/v1/users/me")
.then()
.statusCode(200)
.body("username", equalTo(username));
}
@Test
void expiredSessionReturns401() throws Exception {
String token = login(PASSWORD);
Thread.sleep(3000);
given()
.header("Authorization", "Bearer " + token)
.get("/api/v1/users/me")
.then()
.statusCode(401);
}
@Test
void logoutRevokesSession() throws Exception {
String token = login(PASSWORD);
given()
.header("Authorization", "Bearer " + token)
.delete("/api/v1/auth/sessions/current")
.then()
.statusCode(204);
given()
.header("Authorization", "Bearer " + token)
.get("/api/v1/users/me")
.then()
.statusCode(401);
}
@Test
void wrongPasswordReturns401() {
String credentials = username + ":WrongPassword123!";
String basic = Base64.getEncoder().encodeToString(
credentials.getBytes(StandardCharsets.UTF_8)
);
given()
.header("Authorization", "Basic " + basic)
.post("/api/v1/auth/sessions")
.then()
.statusCode(401);
}
@Test
void missingTokenReturns401() {
given()
.get("/api/v1/users/me")
.then()
.statusCode(401);
}
@Test
void fakeUserIdHeaderCannotAuthenticate() {
given()
.header("X-User-Id", UUID.randomUUID().toString())
.get("/api/v1/users/me")
.then()
.statusCode(401);
}
}
@@ -0,0 +1,73 @@
package com.vnp.demo;
import com.vnp.demo.dto.ChatCreateRequest;
import com.vnp.demo.models.ChatMember;
import com.vnp.demo.models.User;
import com.vnp.demo.repositories.ChatMemberRepository;
import com.vnp.demo.repositories.ChatRepository;
import com.vnp.demo.repositories.UserRepository;
import com.vnp.demo.service.ChatService;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@SpringBootTest
class TransactionRollbackTest {
@Autowired
private ChatService chatService;
@Autowired
private ChatRepository chatRepository;
@Autowired
private UserRepository userRepository;
@SpyBean
private ChatMemberRepository chatMemberRepository;
@Test
void shouldRollbackChatCreationWhenMemberSaveFails() {
User user = userRepository.saveAndFlush(
new User(
"rollback_" + UUID.randomUUID()
.toString()
.substring(0, 8),
"Rollback Test",
"test-password-hash"
)
);
long chatsBefore = chatRepository.count();
doThrow(new IllegalStateException("Simulated failure"))
.when(chatMemberRepository)
.save(any(ChatMember.class));
ChatCreateRequest request = new ChatCreateRequest(
"Rollback test chat",
List.of(user.getId())
);
assertThrows(
IllegalStateException.class,
() -> chatService.create(user.getId(), request)
);
assertEquals(
chatsBefore,
chatRepository.count(),
"Chat must not be saved after transaction rollback"
);
}
}
@@ -0,0 +1,89 @@
BEGIN;
INSERT INTO users (
id,
username,
display_name,
password_hash
)
VALUES (
'11111111-1111-4111-8111-111111111111',
'benchmark_user',
'Benchmark User',
'benchmark-hash'
)
ON CONFLICT (id) DO NOTHING;
INSERT INTO chats (
id,
title
)
VALUES (
'22222222-2222-4222-8222-222222222222',
'Benchmark Chat'
)
ON CONFLICT (id) DO NOTHING;
INSERT INTO chat_members (
chat_id,
user_id
)
VALUES (
'22222222-2222-4222-8222-222222222222',
'11111111-1111-4111-8111-111111111111'
)
ON CONFLICT DO NOTHING;
INSERT INTO messages (
id,
chat_id,
sender_id,
text,
created_at
)
SELECT
(
'33333333-3333-4333-8333-' ||
lpad(g::text, 12, '0')
)::uuid,
'22222222-2222-4222-8222-222222222222'::uuid,
'11111111-1111-4111-8111-111111111111'::uuid,
'Benchmark message ' || g,
NOW() - INTERVAL '1 day'
+ g * INTERVAL '1 second'
FROM generate_series(1, 10000) AS g
ON CONFLICT (id) DO NOTHING;
COMMIT;
ANALYZE messages;
SELECT COUNT(*)
FROM messages
WHERE chat_id =
'22222222-2222-4222-8222-222222222222';
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id =
'22222222-2222-4222-8222-222222222222'
ORDER BY created_at, id
LIMIT 50;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id =
'22222222-2222-4222-8222-222222222222'
AND (created_at, id) > (
(
SELECT created_at
FROM messages
WHERE id =
'33333333-3333-4333-8333-000000000050'
),
'33333333-3333-4333-8333-000000000050'::uuid
)
ORDER BY created_at, id
LIMIT 50;