diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..836d41d5 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,25 @@ +name: Build + +on: + push: + branches: [DevOps] + pull_request: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 25 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '25' + cache: maven + + - name: Build and test + run: ./mvnw -B clean verify diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 8f96f52c..216df058 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1,19 +1,3 @@ -# 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 -# -# https://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. -wrapperVersion=3.3.2 +wrapperVersion=3.3.4 distributionType=only-script -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip diff --git a/Dockerfile b/Dockerfile index 1e66a772..8a1e0019 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,11 +2,11 @@ # Stage 1 #---------------------------------- -# Import docker image with maven installed -FROM maven:3.8.3-openjdk-17 as builder +# Import docker image with maven and JDK 25 installed +FROM maven:3.9-eclipse-temurin-25 AS builder # Add maintainer, so that new user will understand who had written this Dockerfile -MAINTAINER Madhup Pandey +LABEL maintainer="Madhup Pandey " # Add labels to the image to filter out if we have multiple application running LABEL app=bankapp @@ -25,7 +25,7 @@ RUN mvn clean install -DskipTests=true #-------------------------------------- # Import small size java image -FROM eclipse-temurin:17-jre-alpine as deployer +FROM eclipse-temurin:25-jre-alpine AS deployer # Copy build from stage 1 (builder) COPY --from=builder /src/target/*.jar /src/target/bankapp.jar diff --git a/README-K8S.md b/README-K8S.md index 7554262f..e8dec4f2 100644 --- a/README-K8S.md +++ b/README-K8S.md @@ -83,9 +83,11 @@ sudo su > [!Note] > Make sure the ssh-public-key "eks-nodegroup-key is available in your aws account" - Install Jenkins +> [!Note] +> This JRE only runs the Jenkins server (Jenkins supports Java 21). The bankapp itself is built and run on Java 25 inside its Docker image, so the Jenkins host does not need JDK 25. ```bash sudo apt update -y -sudo apt install fontconfig openjdk-17-jre -y +sudo apt install fontconfig openjdk-21-jre -y sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \ https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key diff --git a/README.md b/README.md index 2f49958e..3b91a871 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ ## End-to-End Bank Application Deployment using DevSecOps on AWS EKS -- This is a multi-tier bank an application written in Java (Springboot). +- This is a multi-tier bank an application written in Java 25 (Spring Boot 4.1). ![Login diagram](images/login.png) ![Transactions diagram](images/transactions.png) @@ -14,6 +14,10 @@ - ArgoCD (CD) - AWS EKS (Kubernetes) - Helm (Monitoring using grafana and prometheus) + +## Requirements +- JDK 25 (the app targets Java 25 / Spring Boot 4.1; the Docker image builds and runs on Java 25) +- Maven via the bundled wrapper (`./mvnw clean test`, `./mvnw spring-boot:run`); no separate Maven install needed ### Steps to deploy: @@ -87,9 +91,11 @@ sudo su > [!Note] > Make sure the ssh-public-key "eks-nodegroup-key is available in your aws account" - Install Jenkins +> [!Note] +> This JRE only runs the Jenkins server (Jenkins supports Java 21). The bankapp itself is built and run on Java 25 inside its Docker image, so the Jenkins host does not need JDK 25. ```bash sudo apt update -y -sudo apt install fontconfig openjdk-17-jre -y +sudo apt install fontconfig openjdk-21-jre -y sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \ https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key diff --git a/mvnw b/mvnw index d7c358e5..bd8896bf 100755 --- a/mvnw +++ b/mvnw @@ -8,7 +8,7 @@ # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version 3.3.2 +# Apache Maven Wrapper startup batch script, version 3.3.4 # # Optional ENV vars # ----------------- @@ -105,14 +105,17 @@ trim() { 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 <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" -[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" +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.*) @@ -130,7 +133,7 @@ maven-mvnd-*bin.*) distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" ;; maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; -*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; esac # apply MVNW_REPOURL and calculate MAVEN_HOME @@ -227,7 +230,7 @@ if [ -n "${distributionSha256Sum-}" ]; then 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 + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then distributionSha256Result=true fi elif command -v shasum >/dev/null; then @@ -252,8 +255,41 @@ if command -v unzip >/dev/null; then else tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" fi -printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" -mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" clean || : exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd index 6f779cff..5761d948 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -1,149 +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 https://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.2 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND) { "/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_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" -if ($env:MAVEN_USER_HOME) { - $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" -} -$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::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 -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -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" +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml index eed97c9e..55fb724e 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 3.3.3 + 4.1.2 com.example @@ -27,7 +27,10 @@ - 17 + 25 + + 3.1.8 + 1.6.5 @@ -52,9 +55,8 @@ - mysql - mysql-connector-java - 8.0.33 + com.mysql + mysql-connector-j runtime @@ -67,6 +69,11 @@ spring-boot-starter-test test + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + org.springframework.security spring-security-test @@ -82,12 +89,25 @@ org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - + maven-enforcer-plugin + + + enforce-versions + + enforce + + + + + [25,) + + + [3.9,) + + + + + diff --git a/src/main/java/com/example/bankapp/config/SecurityConfig.java b/src/main/java/com/example/bankapp/config/SecurityConfig.java index 4dbd1572..c58583c0 100644 --- a/src/main/java/com/example/bankapp/config/SecurityConfig.java +++ b/src/main/java/com/example/bankapp/config/SecurityConfig.java @@ -7,17 +7,21 @@ import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class SecurityConfig { - @Autowired - AccountService accountService; + private final AccountService accountService; + + public SecurityConfig(AccountService accountService) { + this.accountService = accountService; + } @Bean public static PasswordEncoder passwordEncoder() { @@ -27,7 +31,7 @@ public static PasswordEncoder passwordEncoder() { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http - .csrf(csrf -> csrf.disable()) + .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authz -> authz .requestMatchers("/register").permitAll() .anyRequest().authenticated() @@ -41,12 +45,12 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .logout(logout -> logout .invalidateHttpSession(true) .clearAuthentication(true) - .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) + .logoutUrl("/logout") .logoutSuccessUrl("/login?logout") .permitAll() ) .headers(headers -> headers - .frameOptions(frameOptions -> frameOptions.sameOrigin()) + .frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin) ); return http.build(); @@ -55,6 +59,5 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(accountService).passwordEncoder(passwordEncoder()); - } -} \ No newline at end of file +} diff --git a/src/main/java/com/example/bankapp/controller/BankController.java b/src/main/java/com/example/bankapp/controller/BankController.java index 19fcded7..4594f59a 100644 --- a/src/main/java/com/example/bankapp/controller/BankController.java +++ b/src/main/java/com/example/bankapp/controller/BankController.java @@ -2,7 +2,6 @@ import com.example.bankapp.model.Account; import com.example.bankapp.service.AccountService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -15,14 +14,15 @@ @Controller public class BankController { - @Autowired - private AccountService accountService; + private final AccountService accountService; + + public BankController(AccountService accountService) { + this.accountService = accountService; + } @GetMapping("/dashboard") public String dashboard(Model model) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account account = accountService.findAccountByUsername(username); - model.addAttribute("account", account); + model.addAttribute("account", currentAccount()); return "dashboard"; } @@ -49,17 +49,13 @@ public String login() { @PostMapping("/deposit") public String deposit(@RequestParam BigDecimal amount) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account account = accountService.findAccountByUsername(username); - accountService.deposit(account, amount); + accountService.deposit(currentAccount(), amount); return "redirect:/dashboard"; } @PostMapping("/withdraw") public String withdraw(@RequestParam BigDecimal amount, Model model) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account account = accountService.findAccountByUsername(username); - + var account = currentAccount(); try { accountService.withdraw(account, amount); } catch (RuntimeException e) { @@ -67,23 +63,18 @@ public String withdraw(@RequestParam BigDecimal amount, Model model) { model.addAttribute("account", account); return "dashboard"; } - return "redirect:/dashboard"; } @GetMapping("/transactions") public String transactionHistory(Model model) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account account = accountService.findAccountByUsername(username); - model.addAttribute("transactions", accountService.getTransactionHistory(account)); + model.addAttribute("transactions", accountService.getTransactionHistory(currentAccount())); return "transactions"; } @PostMapping("/transfer") public String transferAmount(@RequestParam String toUsername, @RequestParam BigDecimal amount, Model model) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account fromAccount = accountService.findAccountByUsername(username); - + var fromAccount = currentAccount(); try { accountService.transferAmount(fromAccount, toUsername, amount); } catch (RuntimeException e) { @@ -91,8 +82,12 @@ public String transferAmount(@RequestParam String toUsername, @RequestParam BigD model.addAttribute("account", fromAccount); return "dashboard"; } - return "redirect:/dashboard"; } + private Account currentAccount() { + var username = SecurityContextHolder.getContext().getAuthentication().getName(); + return accountService.findAccountByUsername(username); + } + } diff --git a/src/main/java/com/example/bankapp/model/Account.java b/src/main/java/com/example/bankapp/model/Account.java index b5e3f17d..e26ddb63 100644 --- a/src/main/java/com/example/bankapp/model/Account.java +++ b/src/main/java/com/example/bankapp/model/Account.java @@ -1,9 +1,15 @@ package com.example.bankapp.model; -import jakarta.persistence.*; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Transient; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; +import java.io.Serial; import java.math.BigDecimal; import java.util.Collection; import java.util.List; @@ -11,6 +17,9 @@ @Entity public class Account implements UserDetails { + @Serial + private static final long serialVersionUID = 1L; + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -25,7 +34,6 @@ public class Account implements UserDetails { private Collection authorities; public Account() { - } public Account(String username, String password, BigDecimal balance, List transactions, Collection authorities) { diff --git a/src/main/java/com/example/bankapp/model/Transaction.java b/src/main/java/com/example/bankapp/model/Transaction.java index b3f371f9..7d118836 100644 --- a/src/main/java/com/example/bankapp/model/Transaction.java +++ b/src/main/java/com/example/bankapp/model/Transaction.java @@ -1,6 +1,12 @@ package com.example.bankapp.model; -import jakarta.persistence.*; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; + import java.math.BigDecimal; import java.time.LocalDateTime; @@ -19,7 +25,6 @@ public class Transaction { private Account account; public Transaction() { - } public Transaction(BigDecimal amount, String type, LocalDateTime timestamp, Account account) { diff --git a/src/main/java/com/example/bankapp/service/AccountService.java b/src/main/java/com/example/bankapp/service/AccountService.java index 5d7d90ec..b8f0d438 100644 --- a/src/main/java/com/example/bankapp/service/AccountService.java +++ b/src/main/java/com/example/bankapp/service/AccountService.java @@ -4,7 +4,6 @@ import com.example.bankapp.model.Transaction; import com.example.bankapp.repository.AccountRepository; import com.example.bankapp.repository.TransactionRepository; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @@ -15,21 +14,23 @@ import java.math.BigDecimal; import java.time.LocalDateTime; -import java.util.Arrays; import java.util.Collection; import java.util.List; @Service public class AccountService implements UserDetailsService { - @Autowired - PasswordEncoder passwordEncoder; + private final PasswordEncoder passwordEncoder; + private final AccountRepository accountRepository; + private final TransactionRepository transactionRepository; - @Autowired - private AccountRepository accountRepository; - - @Autowired - private TransactionRepository transactionRepository; + public AccountService(PasswordEncoder passwordEncoder, + AccountRepository accountRepository, + TransactionRepository transactionRepository) { + this.passwordEncoder = passwordEncoder; + this.accountRepository = accountRepository; + this.transactionRepository = transactionRepository; + } public Account findAccountByUsername(String username) { return accountRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("Account not found")); @@ -40,25 +41,17 @@ public Account registerAccount(String username, String password) { throw new RuntimeException("Username already exists"); } - Account account = new Account(); + var account = new Account(); account.setUsername(username); account.setPassword(passwordEncoder.encode(password)); // Encrypt password account.setBalance(BigDecimal.ZERO); // Initial balance set to 0 return accountRepository.save(account); } - public void deposit(Account account, BigDecimal amount) { account.setBalance(account.getBalance().add(amount)); accountRepository.save(account); - - Transaction transaction = new Transaction( - amount, - "Deposit", - LocalDateTime.now(), - account - ); - transactionRepository.save(transaction); + transactionRepository.save(new Transaction(amount, "Deposit", LocalDateTime.now(), account)); } public void withdraw(Account account, BigDecimal amount) { @@ -67,14 +60,7 @@ public void withdraw(Account account, BigDecimal amount) { } account.setBalance(account.getBalance().subtract(amount)); accountRepository.save(account); - - Transaction transaction = new Transaction( - amount, - "Withdrawal", - LocalDateTime.now(), - account - ); - transactionRepository.save(transaction); + transactionRepository.save(new Transaction(amount, "Withdrawal", LocalDateTime.now(), account)); } public List getTransactionHistory(Account account) { @@ -83,11 +69,7 @@ public List getTransactionHistory(Account account) { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - - Account account = findAccountByUsername(username); - if (account == null) { - throw new UsernameNotFoundException("Username or Password not found"); - } + var account = findAccountByUsername(username); return new Account( account.getUsername(), account.getPassword(), @@ -97,7 +79,7 @@ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundEx } public Collection authorities() { - return Arrays.asList(new SimpleGrantedAuthority("USER")); + return List.of(new SimpleGrantedAuthority("USER")); } public void transferAmount(Account fromAccount, String toUsername, BigDecimal amount) { @@ -105,7 +87,7 @@ public void transferAmount(Account fromAccount, String toUsername, BigDecimal am throw new RuntimeException("Insufficient funds"); } - Account toAccount = accountRepository.findByUsername(toUsername) + var toAccount = accountRepository.findByUsername(toUsername) .orElseThrow(() -> new RuntimeException("Recipient account not found")); // Deduct from sender's account @@ -117,21 +99,16 @@ public void transferAmount(Account fromAccount, String toUsername, BigDecimal am accountRepository.save(toAccount); // Create transaction records for both accounts - Transaction debitTransaction = new Transaction( + transactionRepository.save(new Transaction( amount, "Transfer Out to " + toAccount.getUsername(), LocalDateTime.now(), - fromAccount - ); - transactionRepository.save(debitTransaction); - - Transaction creditTransaction = new Transaction( + fromAccount)); + transactionRepository.save(new Transaction( amount, "Transfer In from " + fromAccount.getUsername(), LocalDateTime.now(), - toAccount - ); - transactionRepository.save(creditTransaction); + toAccount)); } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 08663a63..fa27074d 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,11 +1,10 @@ spring.application.name=bankapp # MySQL Database configuration -spring.datasource.url=jdbc:mysql://localhost:3306/bankappdb?useSSL=false&serverTimezone=UTC +spring.datasource.url=jdbc:mysql://localhost:3306/bankappdb?sslMode=DISABLED&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=Test@123 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # JPA & Hibernate configuration spring.jpa.hibernate.ddl-auto=update -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.jpa.show-sql=true diff --git a/src/test/java/com/example/bankapp/controller/BankControllerWebTest.java b/src/test/java/com/example/bankapp/controller/BankControllerWebTest.java new file mode 100644 index 00000000..b90a62da --- /dev/null +++ b/src/test/java/com/example/bankapp/controller/BankControllerWebTest.java @@ -0,0 +1,318 @@ +package com.example.bankapp.controller; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import com.example.bankapp.repository.AccountRepository; +import com.example.bankapp.repository.TransactionRepository; +import com.example.bankapp.service.AccountService; +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.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.math.BigDecimal; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +/** + * Full-stack web-layer parity tests: real security filter chain, controller, service and H2 database. + */ +@SpringBootTest +@ActiveProfiles("test") +class BankControllerWebTest { + + @Autowired + private WebApplicationContext context; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private TransactionRepository transactionRepository; + + @Autowired + private AccountService accountService; + + @Autowired + private PasswordEncoder passwordEncoder; + + private MockMvc mockMvc; + + @BeforeEach + void setUp() { + transactionRepository.deleteAll(); + accountRepository.deleteAll(); + mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + } + + private Account givenAccount(String username, String password, String balance) { + Account account = accountService.registerAccount(username, password); + account.setBalance(new BigDecimal(balance)); + return accountRepository.save(account); + } + + // Boot 3 / Security 6 redirects to "http://localhost/login"; Boot 4 / Security 7 to "/login". + private static ResultMatcher redirectsToLogin() { + return header().string("Location", endsWith("/login")); + } + + private BigDecimal balanceOf(String username) { + return accountRepository.findByUsername(username).orElseThrow().getBalance(); + } + + private List transactionsOf(String username) { + return transactionRepository.findByAccountId(accountRepository.findByUsername(username).orElseThrow().getId()); + } + + @Test + void loginPageIsPublic() throws Exception { + mockMvc.perform(get("/login")) + .andExpect(status().isOk()) + .andExpect(view().name("login")); + } + + @Test + void registerPageIsPublic() throws Exception { + mockMvc.perform(get("/register")) + .andExpect(status().isOk()) + .andExpect(view().name("register")); + } + + @Test + void registerCreatesAccountWithEncodedPasswordAndRedirectsToLogin() throws Exception { + mockMvc.perform(post("/register").param("username", "alice").param("password", "secret")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/login")); + + Account saved = accountRepository.findByUsername("alice").orElseThrow(); + assertThat(saved.getPassword()).isNotEqualTo("secret"); + assertThat(passwordEncoder.matches("secret", saved.getPassword())).isTrue(); + assertThat(saved.getBalance()).isEqualByComparingTo("0"); + } + + @Test + void registerDuplicateUsernameRendersRegisterWithError() throws Exception { + givenAccount("alice", "secret", "0"); + + mockMvc.perform(post("/register").param("username", "alice").param("password", "other")) + .andExpect(status().isOk()) + .andExpect(view().name("register")) + .andExpect(model().attribute("error", "Username already exists")); + + assertThat(accountRepository.count()).isEqualTo(1); + } + + @Test + void protectedPagesRedirectAnonymousUsersToLogin() throws Exception { + mockMvc.perform(get("/dashboard")).andExpect(status().is3xxRedirection()).andExpect(redirectsToLogin()); + mockMvc.perform(get("/transactions")).andExpect(status().is3xxRedirection()).andExpect(redirectsToLogin()); + mockMvc.perform(get("/")).andExpect(status().is3xxRedirection()).andExpect(redirectsToLogin()); + mockMvc.perform(post("/deposit").param("amount", "10")).andExpect(status().is3xxRedirection()).andExpect(redirectsToLogin()); + mockMvc.perform(post("/withdraw").param("amount", "10")).andExpect(status().is3xxRedirection()).andExpect(redirectsToLogin()); + mockMvc.perform(post("/transfer").param("toUsername", "bob").param("amount", "10")) + .andExpect(status().is3xxRedirection()).andExpect(redirectsToLogin()); + } + + @Test + void formLoginWithValidCredentialsRedirectsToDashboard() throws Exception { + givenAccount("alice", "secret", "0"); + + mockMvc.perform(formLogin("/login").user("alice").password("secret")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/dashboard")) + .andExpect(authenticated().withUsername("alice")); + } + + @Test + void formLoginWithWrongPasswordRedirectsToLoginError() throws Exception { + givenAccount("alice", "secret", "0"); + + mockMvc.perform(formLogin("/login").user("alice").password("wrong")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/login?error")) + .andExpect(unauthenticated()); + } + + @Test + void formLoginWithUnknownUserRedirectsToLoginError() throws Exception { + mockMvc.perform(formLogin("/login").user("ghost").password("secret")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/login?error")) + .andExpect(unauthenticated()); + } + + @Test + void logoutRedirectsToLoginWithLogoutFlag() throws Exception { + mockMvc.perform(post("/logout").with(user("alice"))) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/login?logout")); + mockMvc.perform(get("/logout").with(user("alice"))) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/login?logout")); + } + + @Test + void dashboardShowsAuthenticatedUsersAccount() throws Exception { + givenAccount("alice", "secret", "12.50"); + + mockMvc.perform(get("/dashboard").with(user("alice"))) + .andExpect(status().isOk()) + .andExpect(view().name("dashboard")) + .andExpect(model().attribute("account", hasProperty("username", is("alice")))) + .andExpect(content().string(containsString("Welcome, alice"))) + .andExpect(content().string(containsString("Current Balance: $12.50"))); + } + + @Test + void dashboardForAuthenticatedUserWithoutAccountFailsWithAccountNotFound() { + assertThatThrownBy(() -> mockMvc.perform(get("/dashboard").with(user("ghost")))) + .hasRootCauseMessage("Account not found"); + } + + @Test + void depositIncreasesBalanceAndRecordsTransaction() throws Exception { + givenAccount("alice", "secret", "10.00"); + + mockMvc.perform(post("/deposit").with(user("alice")).param("amount", "15.25")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/dashboard")); + + assertThat(balanceOf("alice")).isEqualByComparingTo("25.25"); + assertThat(transactionsOf("alice")).extracting(Transaction::getType).containsExactly("Deposit"); + } + + @Test + void depositWithNonNumericAmountIsBadRequest() throws Exception { + givenAccount("alice", "secret", "10.00"); + + mockMvc.perform(post("/deposit").with(user("alice")).param("amount", "abc")) + .andExpect(status().isBadRequest()); + mockMvc.perform(post("/deposit").with(user("alice"))) + .andExpect(status().isBadRequest()); + + assertThat(balanceOf("alice")).isEqualByComparingTo("10.00"); + } + + @Test + void withdrawDecreasesBalanceAndRecordsTransaction() throws Exception { + givenAccount("alice", "secret", "50.00"); + + mockMvc.perform(post("/withdraw").with(user("alice")).param("amount", "20.00")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/dashboard")); + + assertThat(balanceOf("alice")).isEqualByComparingTo("30.00"); + assertThat(transactionsOf("alice")).extracting(Transaction::getType).containsExactly("Withdrawal"); + } + + @Test + void withdrawWithInsufficientFundsRendersDashboardWithError() throws Exception { + givenAccount("alice", "secret", "5.00"); + + mockMvc.perform(post("/withdraw").with(user("alice")).param("amount", "20.00")) + .andExpect(status().isOk()) + .andExpect(view().name("dashboard")) + .andExpect(model().attribute("error", "Insufficient funds")) + .andExpect(model().attribute("account", hasProperty("username", is("alice")))) + .andExpect(content().string(containsString("Insufficient funds"))); + + assertThat(balanceOf("alice")).isEqualByComparingTo("5.00"); + assertThat(transactionsOf("alice")).isEmpty(); + } + + @Test + void transferMovesFundsBetweenAccounts() throws Exception { + givenAccount("alice", "secret", "100.00"); + givenAccount("bob", "secret", "1.00"); + + mockMvc.perform(post("/transfer").with(user("alice")).param("toUsername", "bob").param("amount", "40.00")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/dashboard")); + + assertThat(balanceOf("alice")).isEqualByComparingTo("60.00"); + assertThat(balanceOf("bob")).isEqualByComparingTo("41.00"); + assertThat(transactionsOf("alice")).extracting(Transaction::getType).containsExactly("Transfer Out to bob"); + assertThat(transactionsOf("bob")).extracting(Transaction::getType).containsExactly("Transfer In from alice"); + } + + @Test + void transferToUnknownRecipientRendersDashboardWithError() throws Exception { + givenAccount("alice", "secret", "100.00"); + + mockMvc.perform(post("/transfer").with(user("alice")).param("toUsername", "ghost").param("amount", "10.00")) + .andExpect(status().isOk()) + .andExpect(view().name("dashboard")) + .andExpect(model().attribute("error", "Recipient account not found")); + + assertThat(balanceOf("alice")).isEqualByComparingTo("100.00"); + } + + @Test + void transferWithInsufficientFundsRendersDashboardWithError() throws Exception { + givenAccount("alice", "secret", "5.00"); + givenAccount("bob", "secret", "0.00"); + + mockMvc.perform(post("/transfer").with(user("alice")).param("toUsername", "bob").param("amount", "10.00")) + .andExpect(status().isOk()) + .andExpect(view().name("dashboard")) + .andExpect(model().attribute("error", "Insufficient funds")); + + assertThat(balanceOf("alice")).isEqualByComparingTo("5.00"); + assertThat(balanceOf("bob")).isEqualByComparingTo("0.00"); + } + + @Test + void selfTransferLeavesBalanceUnchangedButRecordsTwoTransactions() throws Exception { + givenAccount("alice", "secret", "10.00"); + + mockMvc.perform(post("/transfer").with(user("alice")).param("toUsername", "alice").param("amount", "4.00")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/dashboard")); + + assertThat(balanceOf("alice")).isEqualByComparingTo("10.00"); + assertThat(transactionsOf("alice")).extracting(Transaction::getType) + .containsExactly("Transfer Out to alice", "Transfer In from alice"); + } + + @Test + void transactionsPageListsOnlyCurrentUsersHistory() throws Exception { + givenAccount("alice", "secret", "0.00"); + givenAccount("bob", "secret", "0.00"); + mockMvc.perform(post("/deposit").with(user("alice")).param("amount", "30.00")); + mockMvc.perform(post("/withdraw").with(user("alice")).param("amount", "10.00")); + mockMvc.perform(post("/deposit").with(user("bob")).param("amount", "99.00")); + + mockMvc.perform(get("/transactions").with(user("alice"))) + .andExpect(status().isOk()) + .andExpect(view().name("transactions")) + .andExpect(model().attribute("transactions", hasSize(2))) + .andExpect(content().string(containsString("Deposit"))) + .andExpect(content().string(containsString("Withdrawal"))); + } +} diff --git a/src/test/java/com/example/bankapp/repository/RepositoryJpaTest.java b/src/test/java/com/example/bankapp/repository/RepositoryJpaTest.java new file mode 100644 index 00000000..66e20605 --- /dev/null +++ b/src/test/java/com/example/bankapp/repository/RepositoryJpaTest.java @@ -0,0 +1,117 @@ +package com.example.bankapp.repository; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.test.context.ActiveProfiles; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DataJpaTest +@ActiveProfiles("test") +class RepositoryJpaTest { + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private TransactionRepository transactionRepository; + + @Autowired + private EntityManager entityManager; + + private Account persistAccount(String username, String balance) { + Account account = new Account(); + account.setUsername(username); + account.setPassword("pw-" + username); + account.setBalance(new BigDecimal(balance)); + return accountRepository.save(account); + } + + private void flushAndClear() { + entityManager.flush(); + entityManager.clear(); + } + + @Test + void saveAssignsGeneratedIdAndFindByUsernameRoundTrips() { + Account saved = persistAccount("alice", "12.34"); + flushAndClear(); + + assertThat(saved.getId()).isNotNull(); + Account found = accountRepository.findByUsername("alice").orElseThrow(); + assertThat(found.getId()).isEqualTo(saved.getId()); + assertThat(found.getPassword()).isEqualTo("pw-alice"); + assertThat(found.getBalance()).isEqualByComparingTo("12.34"); + assertThat(found.getAuthorities()).isNull(); + } + + @Test + void findByUsernameIsEmptyForUnknownUser() { + persistAccount("alice", "0"); + + assertThat(accountRepository.findByUsername("bob")).isEmpty(); + assertThat(accountRepository.findByUsername("ALICE")).isEmpty(); + } + + @Test + void balanceIsStoredWithTwoDecimalScale() { + persistAccount("alice", "10.555"); + flushAndClear(); + + assertThat(accountRepository.findByUsername("alice").orElseThrow().getBalance()) + .isEqualTo(new BigDecimal("10.56")); + } + + @Test + void duplicateUsernamesAreNotPreventedByTheSchema() { + persistAccount("alice", "1"); + persistAccount("alice", "2"); + flushAndClear(); + + assertThat(accountRepository.count()).isEqualTo(2); + assertThatThrownBy(() -> accountRepository.findByUsername("alice")) + .isInstanceOf(IncorrectResultSizeDataAccessException.class); + } + + @Test + void findByAccountIdReturnsOnlyThatAccountsTransactionsInInsertOrder() { + Account alice = persistAccount("alice", "0"); + Account bob = persistAccount("bob", "0"); + LocalDateTime now = LocalDateTime.of(2024, 1, 2, 3, 4, 5); + transactionRepository.save(new Transaction(new BigDecimal("1.00"), "Deposit", now, alice)); + transactionRepository.save(new Transaction(new BigDecimal("2.00"), "Deposit", now, bob)); + transactionRepository.save(new Transaction(new BigDecimal("3.00"), "Withdrawal", now.plusMinutes(1), alice)); + flushAndClear(); + + List history = transactionRepository.findByAccountId(alice.getId()); + + assertThat(history).extracting(Transaction::getType).containsExactly("Deposit", "Withdrawal"); + assertThat(history).extracting(Transaction::getAmount) + .usingElementComparator(BigDecimal::compareTo) + .containsExactly(new BigDecimal("1.00"), new BigDecimal("3.00")); + assertThat(history.get(0).getTimestamp()).isEqualTo(now); + assertThat(history.get(0).getAccount().getUsername()).isEqualTo("alice"); + assertThat(transactionRepository.findByAccountId(-1L)).isEmpty(); + } + + @Test + void accountTransactionsCollectionIsMappedByAccount() { + Account alice = persistAccount("alice", "0"); + transactionRepository.save(new Transaction(BigDecimal.TEN, "Deposit", LocalDateTime.now(), alice)); + flushAndClear(); + + Account reloaded = accountRepository.findById(alice.getId()).orElseThrow(); + assertThat(reloaded.getTransactions()).hasSize(1); + assertThat(reloaded.getTransactions().get(0).getType()).isEqualTo("Deposit"); + } +} diff --git a/src/test/java/com/example/bankapp/service/AccountServiceTest.java b/src/test/java/com/example/bankapp/service/AccountServiceTest.java new file mode 100644 index 00000000..de381df4 --- /dev/null +++ b/src/test/java/com/example/bankapp/service/AccountServiceTest.java @@ -0,0 +1,291 @@ +package com.example.bankapp.service; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import com.example.bankapp.repository.AccountRepository; +import com.example.bankapp.repository.TransactionRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.password.PasswordEncoder; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class AccountServiceTest { + + @Mock + private PasswordEncoder passwordEncoder; + + @Mock + private AccountRepository accountRepository; + + @Mock + private TransactionRepository transactionRepository; + + @InjectMocks + private AccountService accountService; + + private static Account account(Long id, String username, String balance) { + Account account = new Account(); + account.setId(id); + account.setUsername(username); + account.setPassword("{hash}" + username); + account.setBalance(new BigDecimal(balance)); + return account; + } + + @Test + void findAccountByUsernameReturnsAccount() { + Account alice = account(1L, "alice", "10.00"); + when(accountRepository.findByUsername("alice")).thenReturn(Optional.of(alice)); + + assertThat(accountService.findAccountByUsername("alice")).isSameAs(alice); + } + + @Test + void findAccountByUsernameThrowsWhenMissing() { + when(accountRepository.findByUsername("ghost")).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> accountService.findAccountByUsername("ghost")) + .isExactlyInstanceOf(RuntimeException.class) + .hasMessage("Account not found"); + } + + @Test + void registerAccountEncodesPasswordAndStartsAtZeroBalance() { + when(accountRepository.findByUsername("alice")).thenReturn(Optional.empty()); + when(passwordEncoder.encode("secret")).thenReturn("ENCODED"); + when(accountRepository.save(any(Account.class))).thenAnswer(inv -> inv.getArgument(0)); + + Account result = accountService.registerAccount("alice", "secret"); + + ArgumentCaptor saved = ArgumentCaptor.forClass(Account.class); + verify(accountRepository).save(saved.capture()); + assertThat(result).isSameAs(saved.getValue()); + assertThat(result.getUsername()).isEqualTo("alice"); + assertThat(result.getPassword()).isEqualTo("ENCODED"); + assertThat(result.getBalance()).isSameAs(BigDecimal.ZERO); + assertThat(result.getId()).isNull(); + assertThat(result.getTransactions()).isNull(); + assertThat(result.getAuthorities()).isNull(); + } + + @Test + void registerAccountRejectsDuplicateUsername() { + when(accountRepository.findByUsername("alice")).thenReturn(Optional.of(account(1L, "alice", "0"))); + + assertThatThrownBy(() -> accountService.registerAccount("alice", "secret")) + .isExactlyInstanceOf(RuntimeException.class) + .hasMessage("Username already exists"); + verify(accountRepository, never()).save(any()); + verify(passwordEncoder, never()).encode(any()); + } + + @Test + void depositAddsAmountAndRecordsDepositTransaction() { + Account alice = account(1L, "alice", "100.00"); + + accountService.deposit(alice, new BigDecimal("25.50")); + + assertThat(alice.getBalance()).isEqualByComparingTo("125.50"); + InOrder order = inOrder(accountRepository, transactionRepository); + order.verify(accountRepository).save(alice); + ArgumentCaptor tx = ArgumentCaptor.forClass(Transaction.class); + order.verify(transactionRepository).save(tx.capture()); + assertThat(tx.getValue().getType()).isEqualTo("Deposit"); + assertThat(tx.getValue().getAmount()).isEqualByComparingTo("25.50"); + assertThat(tx.getValue().getAccount()).isSameAs(alice); + assertThat(tx.getValue().getTimestamp()).isNotNull(); + } + + @Test + void depositAcceptsNegativeAmountAsIs() { + Account alice = account(1L, "alice", "100.00"); + + accountService.deposit(alice, new BigDecimal("-40.00")); + + assertThat(alice.getBalance()).isEqualByComparingTo("60.00"); + verify(transactionRepository).save(any(Transaction.class)); + } + + @Test + void withdrawSubtractsAmountAndRecordsWithdrawalTransaction() { + Account alice = account(1L, "alice", "100.00"); + + accountService.withdraw(alice, new BigDecimal("30.00")); + + assertThat(alice.getBalance()).isEqualByComparingTo("70.00"); + InOrder order = inOrder(accountRepository, transactionRepository); + order.verify(accountRepository).save(alice); + ArgumentCaptor tx = ArgumentCaptor.forClass(Transaction.class); + order.verify(transactionRepository).save(tx.capture()); + assertThat(tx.getValue().getType()).isEqualTo("Withdrawal"); + assertThat(tx.getValue().getAmount()).isEqualByComparingTo("30.00"); + assertThat(tx.getValue().getAccount()).isSameAs(alice); + assertThat(tx.getValue().getTimestamp()).isNotNull(); + } + + @Test + void withdrawOfEntireBalanceIsAllowed() { + Account alice = account(1L, "alice", "50.00"); + + accountService.withdraw(alice, new BigDecimal("50.00")); + + assertThat(alice.getBalance()).isEqualByComparingTo("0"); + } + + @Test + void withdrawRejectsInsufficientFundsWithoutSaving() { + Account alice = account(1L, "alice", "50.00"); + + assertThatThrownBy(() -> accountService.withdraw(alice, new BigDecimal("50.01"))) + .isExactlyInstanceOf(RuntimeException.class) + .hasMessage("Insufficient funds"); + assertThat(alice.getBalance()).isEqualByComparingTo("50.00"); + verify(accountRepository, never()).save(any()); + verify(transactionRepository, never()).save(any()); + } + + @Test + void withdrawAcceptsNegativeAmountAsIs() { + Account alice = account(1L, "alice", "10.00"); + + accountService.withdraw(alice, new BigDecimal("-5.00")); + + assertThat(alice.getBalance()).isEqualByComparingTo("15.00"); + } + + @Test + void transferMovesFundsAndRecordsBothSides() { + Account alice = account(1L, "alice", "100.00"); + Account bob = account(2L, "bob", "5.00"); + when(accountRepository.findByUsername("bob")).thenReturn(Optional.of(bob)); + + accountService.transferAmount(alice, "bob", new BigDecimal("40.00")); + + assertThat(alice.getBalance()).isEqualByComparingTo("60.00"); + assertThat(bob.getBalance()).isEqualByComparingTo("45.00"); + + InOrder order = inOrder(accountRepository, transactionRepository); + order.verify(accountRepository).save(alice); + order.verify(accountRepository).save(bob); + ArgumentCaptor tx = ArgumentCaptor.forClass(Transaction.class); + order.verify(transactionRepository, times(2)).save(tx.capture()); + + Transaction debit = tx.getAllValues().get(0); + assertThat(debit.getType()).isEqualTo("Transfer Out to bob"); + assertThat(debit.getAmount()).isEqualByComparingTo("40.00"); + assertThat(debit.getAccount()).isSameAs(alice); + assertThat(debit.getTimestamp()).isNotNull(); + + Transaction credit = tx.getAllValues().get(1); + assertThat(credit.getType()).isEqualTo("Transfer In from alice"); + assertThat(credit.getAmount()).isEqualByComparingTo("40.00"); + assertThat(credit.getAccount()).isSameAs(bob); + assertThat(credit.getTimestamp()).isNotNull(); + } + + @Test + void transferChecksFundsBeforeLookingUpRecipient() { + Account alice = account(1L, "alice", "10.00"); + + assertThatThrownBy(() -> accountService.transferAmount(alice, "ghost", new BigDecimal("10.01"))) + .isExactlyInstanceOf(RuntimeException.class) + .hasMessage("Insufficient funds"); + verify(accountRepository, never()).findByUsername(any()); + verify(accountRepository, never()).save(any()); + verify(transactionRepository, never()).save(any()); + } + + @Test + void transferRejectsUnknownRecipientWithoutSaving() { + Account alice = account(1L, "alice", "100.00"); + when(accountRepository.findByUsername("ghost")).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> accountService.transferAmount(alice, "ghost", new BigDecimal("10.00"))) + .isExactlyInstanceOf(RuntimeException.class) + .hasMessage("Recipient account not found"); + assertThat(alice.getBalance()).isEqualByComparingTo("100.00"); + verify(accountRepository, never()).save(any()); + verify(transactionRepository, never()).save(any()); + } + + @Test + void transferAcceptsNegativeAmountAsIs() { + Account alice = account(1L, "alice", "10.00"); + Account bob = account(2L, "bob", "10.00"); + when(accountRepository.findByUsername("bob")).thenReturn(Optional.of(bob)); + + accountService.transferAmount(alice, "bob", new BigDecimal("-5.00")); + + assertThat(alice.getBalance()).isEqualByComparingTo("15.00"); + assertThat(bob.getBalance()).isEqualByComparingTo("5.00"); + } + + @Test + void getTransactionHistoryQueriesByAccountId() { + Account alice = account(7L, "alice", "0"); + List history = new ArrayList<>(); + history.add(new Transaction(BigDecimal.ONE, "Deposit", null, alice)); + when(transactionRepository.findByAccountId(7L)).thenReturn(history); + + assertThat(accountService.getTransactionHistory(alice)).isSameAs(history); + } + + @Test + void loadUserByUsernameReturnsCopyWithUserAuthority() { + Account stored = account(3L, "alice", "42.00"); + List txs = Collections.emptyList(); + stored.setTransactions(txs); + when(accountRepository.findByUsername("alice")).thenReturn(Optional.of(stored)); + + UserDetails details = accountService.loadUserByUsername("alice"); + + assertThat(details).isInstanceOf(Account.class).isNotSameAs(stored); + Account loaded = (Account) details; + assertThat(loaded.getUsername()).isEqualTo("alice"); + assertThat(loaded.getPassword()).isEqualTo("{hash}alice"); + assertThat(loaded.getBalance()).isEqualByComparingTo("42.00"); + assertThat(loaded.getTransactions()).isSameAs(txs); + assertThat(loaded.getId()).isNull(); + assertThat(loaded.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsExactly("USER"); + assertThat(loaded.isEnabled()).isTrue(); + assertThat(loaded.isAccountNonLocked()).isTrue(); + assertThat(loaded.isAccountNonExpired()).isTrue(); + assertThat(loaded.isCredentialsNonExpired()).isTrue(); + } + + @Test + void loadUserByUsernameThrowsPlainRuntimeExceptionWhenMissing() { + when(accountRepository.findByUsername("ghost")).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> accountService.loadUserByUsername("ghost")) + .isExactlyInstanceOf(RuntimeException.class) + .hasMessage("Account not found"); + } + + @Test + void authoritiesIsSingleUserAuthorityWithoutRolePrefix() { + assertThat(accountService.authorities()).extracting(GrantedAuthority::getAuthority).containsExactly("USER"); + } +}