51 Commits

Author SHA1 Message Date
Cedric 7ad72119a8 fix secrets no longer needed
Build and Deploy Spring Boot Server / build (push) Successful in 1m13s
2026-05-14 23:46:40 +02:00
Cedric f7f2bf5768 ci: switch to compose.deploy to force fresh image pull
Build and Deploy Spring Boot Server / build (push) Successful in 1m12s
2026-05-12 23:57:45 +02:00
Cedric 28df2a66ca fix: always pull latest image on redeploy
Build and Deploy Spring Boot Server / build (push) Successful in 1m21s
2026-05-12 23:25:07 +02:00
Cedric 29f26a8a18 feat: add /api/version endpoint returning build time and version
Build and Deploy Spring Boot Server / build (push) Successful in 1m25s
2026-05-12 23:08:37 +02:00
Cedric a3fa59f347 ci: test full pipeline end-to-end
Build and Deploy Spring Boot Server / build (push) Successful in 1m12s
2026-05-12 20:34:42 +02:00
Cedric 2880934644 ci: test full pipeline end-to-end
Build and Deploy Spring Boot Server / build (push) Successful in 1m10s
2026-05-10 23:43:13 +02:00
Cedric b42980200d ci: trigger Dokploy redeploy via API after image push
Build and Deploy Spring Boot Server / build (push) Failing after 1m48s
2026-05-10 23:38:07 +02:00
Cedric 8381cdbffa ci: test full pipeline
Build and Deploy Spring Boot Server / build (push) Successful in 1m20s
2026-05-10 22:59:53 +02:00
Cedric 5cab2fed3b ci: test Dokploy webhook
Build and Deploy Spring Boot Server / build (push) Successful in 1m13s
2026-05-10 22:36:44 +02:00
Cedric 417eef7042 ci: fix Dokploy webhook, token is in URL not Authorization header
Build and Deploy Spring Boot Server / build (push) Failing after 1m11s
2026-05-10 22:29:40 +02:00
Cedric ed5543ce61 ci: fix Java 21 in dockerfile, add Docker Hub login to avoid rate limits
Build and Deploy Spring Boot Server / build (push) Failing after 1m23s
2026-05-10 22:22:06 +02:00
Cedric 40b8f45de8 ci: test with Java 21 runner image
Build and Deploy Spring Boot Server / build (push) Failing after 1m2s
2026-05-10 22:15:16 +02:00
Cedric b221d07b48 ci: use ubuntu-java17 runner image, remove setup-java step
Build and Deploy Spring Boot Server / build (push) Failing after 2m22s
2026-05-10 22:08:23 +02:00
Cedric 0e63b6e4e6 ci: fix mvnw executable permission
Build and Deploy Spring Boot Server / build (push) Has been cancelled
2026-05-10 22:07:30 +02:00
Cedric 4a04c85fe8 ci: use Maven wrapper instead of mvn to fix command not found on Gitea runner
Build and Deploy Spring Boot Server / build (push) Failing after 4m43s
2026-05-10 21:40:25 +02:00
Cedric b8e2c9114d chore: merge main into dev, keep clean docker-compose from main
Build and Deploy Spring Boot Server / build (push) Failing after 9m2s
2026-05-10 21:29:11 +02:00
Cedric 0876eecf50 ci: improve dev pipeline with Dokploy webhook and Docker layer caching 2026-05-10 21:27:28 +02:00
Cedric 5549691d50 ci: test pipeline 2026-05-10 21:24:18 +02:00
Cedric 46c8df45d6 ci: test pipeline 2026-05-10 21:24:10 +02:00
Cedric 50d274f36a chore: resolve merge conflicts, keep Spring Boot 4.0.6 version
Kept our version over remote (security hardening PR #12) for all conflicts:
- pom.xml: Spring Boot 4.0.6 vs 3.4.1, new test deps
- SecurityConfig: new csrf/package API for SB4
- GlobalExceptionHandler: full handler set with SLF4J logging
- AppUserController/ExpenseListController: clean delegation to GlobalExceptionHandler
- Test files: SB4 package paths, extra test coverage

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 20:29:49 +02:00
Cedric ba4f365f06 chore: merge feature/security-hardening into main
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 20:25:12 +02:00
Cedric a5e5824a44 docs: write recent changes section 2026-05-10 20:18:58 +02:00
Cedric 7189e4fb08 docs: write error handling section 2026-05-10 20:18:28 +02:00
Cedric 2782823c3d docs: write data models section 2026-05-10 20:17:55 +02:00
Cedric ddf64305a5 docs: write expense lists endpoint section 2026-05-10 20:17:22 +02:00
Cedric 2b84ed0de8 docs: write home and users endpoint sections 2026-05-10 20:14:22 +02:00
Cedric 18e740bb73 docs: write rate limiting section 2026-05-10 20:13:58 +02:00
Cedric 9b93cd97a6 docs: write authentication section 2026-05-09 23:56:14 +02:00
Cedric 8fb1820bc7 docs: write API overview section 2026-05-09 23:50:42 +02:00
Cedric 9c35bb8435 docs: scaffold API.md with section headings 2026-05-09 23:49:56 +02:00
Cedric 3d456f2f81 Bugfixes 2026-05-09 23:04:27 +02:00
Cedric b1324e3048 test: add jsonPath field assertions to create validation tests 2026-05-06 14:40:11 +02:00
Cedric 8b96433b1a feat: add CreateExpenseListRequest DTO with validation to POST /create endpoint
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 17:28:47 +02:00
Cedric f0de751da4 fix: centralise error handling in GlobalExceptionHandler, add SLF4J logging, remove HTTP 417 and e.printStackTrace()
- Expand GlobalExceptionHandler with handlers for ResourceNotFoundException (404),
  UsernameAlreadyExistsException (409), ResponseStatusException (pass-through),
  RuntimeException (500), and generic Exception (500); add SLF4J logging
- Remove all bare try/catch blocks and e.printStackTrace() calls from
  ExpenseListController; add SLF4J logger field
- Add test: create_returns500_onUnexpectedServiceError

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 17:11:37 +02:00
Cedric 9b95741292 fix: add /docs/superpowers to .gitignore 2026-05-05 17:00:01 +02:00
Cedric 2bd229cc5e Remove docs from tracking 2026-05-05 16:59:35 +02:00
Cedric 797d482ebf fix: use ResourceNotFoundException for not-found cases in updateExpense, IllegalArgumentException for ownership mismatch in deleteCustomCategory 2026-05-05 16:55:01 +02:00
Cedric 906b60d264 fix: single-param JPQL queries, ResourceNotFoundException throughout ExpenseListService, remove addExpenseToList loop
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 16:40:31 +02:00
Cedric 68783cc892 fix: throw ResourceNotFoundException instead of returning null, replace full-table-scan list queries with JPQL 2026-05-05 15:20:46 +02:00
Cedric 9c91da9f30 test: fix ExpenseListRepositoryTest with H2 and proper save-then-find pattern
Added H2 as a test-scoped dependency so @DataJpaTest has an embedded
database. Rewrote the test to save an entity and assert on the returned
ID rather than assuming a record exists at ID=1.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 11:23:51 +02:00
Cedric 024b3880e7 security: add per-user/IP rate limiting via Bucket4j
RateLimitFilter (OncePerRequestFilter) enforces 60 req/min per
authenticated Google ID or client IP, using Bucket4j in-memory
token buckets. Filter is registered after BearerTokenAuthenticationFilter
in the production security chain. Added 4 unit tests covering
allow, block, per-IP isolation, and X-Forwarded-For preference.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 11:19:42 +02:00
Cedric 457efab452 security: enforce JWT-based authorization on AppUserController
Added AuthenticatedUserResolver injection and assertSelf guard to
getUser, getUserByGoogleId, and deleteUser endpoints. createUser
remains open for registration. Added 7 controller tests covering
validation failures and 403 enforcement.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 11:13:05 +02:00
Cedric 95688e5111 test: add unit tests for AuthenticatedUserResolver 2026-05-05 10:03:35 +02:00
Cedric bb2a4d70b2 feat: add ExpenseListController validation and authorization tests 2026-05-04 22:46:29 +02:00
Cedric a948bca2fc feat: add GlobalExceptionHandler, @Valid to user creation, AuthenticatedUserResolver stub, and rewrite ExpenseListController with authorization 2026-05-04 22:44:37 +02:00
Cedric 3bea06fead feat: add Bean Validation annotations to request models 2026-05-04 22:36:20 +02:00
Cedric b7db35defe build: add spring-boot-starter-validation and bucket4j-core 2026-05-04 22:34:10 +02:00
Cedric efe84942ff docs: add security hardening implementation plan
8-task TDD plan covering input validation, JWT-based authorization
enforcement, and Bucket4j rate limiting.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 22:22:54 +02:00
Cedric e3b8917bfc docs: add security hardening design spec
Covers input validation, JWT-based authorization enforcement, and
per-user rate limiting via Bucket4j.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 21:58:20 +02:00
Cedric 726be3f613 bu commit
Build and Deploy Spring Boot Server / build (push) Successful in 10m16s
2025-07-11 14:16:05 +02:00
Cedric 936140e76f dockerCompose backup
Build and Deploy Spring Boot Server / build (push) Successful in 10m4s
2025-05-11 10:15:15 +02:00
20 changed files with 1176 additions and 237 deletions
+8
View File
@@ -0,0 +1,8 @@
{
"permissions": {
"allow": [
"Bash(git add *)",
"Bash(git commit *)"
]
}
}
+37 -34
View File
@@ -7,48 +7,51 @@ on:
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-java17
steps: steps:
# 1. Checkout the code # 1. Checkout the code
- name: Checkout code - name: Checkout code
uses: actions/checkout@v2 uses: actions/checkout@v4
# 2. Set up Java and Maven # 2. Build the Spring Boot application using the Maven wrapper (Java 17 pre-installed in runner image)
- name: Set up JDK (Eclipse Temurin)
uses: actions/setup-java@v3
with:
distribution: "temurin"
java-version: "17"
cache: maven
# 3. Verify Maven installation
- name: Install Maven
run: |
sudo apt-get update
sudo apt-get install -y maven
mvn -version
# 4. Build the Spring Boot application
- name: Build Spring Boot Application - name: Build Spring Boot Application
run: | run: ./mvnw clean package -DskipTests
mvn clean package -DskipTests
# 5. Set up Docker # 4. Set up Docker Buildx (enables layer caching)
- name: Set up Docker - name: Set up Docker Buildx
run: | uses: docker/setup-buildx-action@v3
docker --version
# 6. Build the Docker image # 5. Login to Docker Hub to avoid pull rate limits
- name: Build and Package Docker Image - name: Login to Docker Hub
run: | uses: docker/login-action@v3
docker build -t tea.zendric.de/cedric/xpensely-server:latest . with:
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
# 7. Docker login # 6. Docker login to Gitea registry
- name: Login to Docker Registry - name: Login to Docker Registry
uses: docker/login-action@v3
with:
registry: tea.zendric.de
username: ${{ secrets.TEAUSER }}
password: ${{ secrets.TEAPASSWORD }}
# 7. Build and push Docker image with layer caching
- name: Build and Push Docker Image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: tea.zendric.de/cedric/xpensely-server:latest
cache-from: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache
cache-to: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache,mode=max
# 8. Trigger Dokploy to redeploy the dev server automatically via API
- name: Trigger Dokploy Redeploy
run: | run: |
echo "${{ secrets.TEAPASSWORD }}" | docker login tea.zendric.de -u ${{ secrets.TEAUSER }} --password-stdin curl -X POST "https://dokploy.zendric.de/api/compose.deploy" \
# 8. Push Docker image -H "Content-Type: application/json" \
- name: Push the Docker Image to registry -H "x-api-key: ${{ secrets.DOKPLOY_API_TOKEN }}" \
run: | -d "{\"composeId\": \"${{ secrets.DOKPLOY_COMPOSE_ID }}\"}" \
docker push tea.zendric.de/cedric/xpensely-server:latest --fail
+7
View File
@@ -0,0 +1,7 @@
Run it locally:
1. build the current state:
mvn clean install or mvn clean install -DskipTests
2. docker it up and run it
docker-compose -f dev-docker-compose.yml up --build
+85 -1
View File
@@ -1,6 +1,6 @@
<mxfile host="65bd71144e"> <mxfile host="65bd71144e">
<diagram id="TZX9Tq6sZIlTxQ58HocZ" name="Page-1"> <diagram id="TZX9Tq6sZIlTxQ58HocZ" name="Page-1">
<mxGraphModel dx="826" dy="472" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0"> <mxGraphModel dx="989" dy="570" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
<root> <root>
<mxCell id="0"/> <mxCell id="0"/>
<mxCell id="1" parent="0"/> <mxCell id="1" parent="0"/>
@@ -193,6 +193,90 @@
<mxCell id="73" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;24.12.24 ; Expense ; 24,12 €&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#76608a;fontColor=#ffffff;strokeColor=#432D57;" parent="1" vertex="1"> <mxCell id="73" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;24.12.24 ; Expense ; 24,12 €&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#76608a;fontColor=#ffffff;strokeColor=#432D57;" parent="1" vertex="1">
<mxGeometry x="1399" y="226" width="120" height="20" as="geometry"/> <mxGeometry x="1399" y="226" width="120" height="20" as="geometry"/>
</mxCell> </mxCell>
<mxCell id="86" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="74" target="79">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="74" value="List" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#60a917;fontColor=#ffffff;strokeColor=#2D7600;" vertex="1" parent="1">
<mxGeometry x="1880" y="160" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="75" value="DB-Structure for Categories" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="1930" y="35" width="100" height="30" as="geometry"/>
</mxCell>
<mxCell id="78" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="76" target="77">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="76" value="List Entry" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1920" y="220" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="79" value="Available Categories" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2160" y="150" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="83" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="81" target="79">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="81" value="Standard Categories" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2060" y="35" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="84" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="82" target="79">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="82" value="Custom Categories" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2270" y="35" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="91" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="87" target="90">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="87" value="List Entry" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1920" y="280" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="92" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="88" target="89">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="88" value="List Entry" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1920" y="340" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="89" value="Category" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2150" y="370" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="90" value="Category" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2150" y="315" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="94" value="&lt;h1 style=&quot;font-size: 18px;&quot;&gt;- list id&lt;/h1&gt;&lt;div&gt;- List &amp;lt;String&amp;gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;spacing=5;spacingTop=-20;whiteSpace=wrap;overflow=hidden;rounded=0;fontSize=18;" vertex="1" parent="1">
<mxGeometry x="2410" y="50" width="130" height="70" as="geometry"/>
</mxCell>
<mxCell id="77" value="Category" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="2150" y="260" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="97" value="" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1730" y="510" width="200" height="320" as="geometry"/>
</mxCell>
<mxCell id="98" value="ExpenseList" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1770" y="520" width="120" height="20" as="geometry"/>
</mxCell>
<mxCell id="100" value="+" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="1880" y="790" width="30" height="30" as="geometry"/>
</mxCell>
<mxCell id="101" value="Categorie" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="1770" y="480" width="120" height="30" as="geometry"/>
</mxCell>
<mxCell id="102" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;Amount : 24,12 €&lt;br&gt;Title: Expense&lt;br&gt;Date: 24.12.24&lt;br&gt;From: Jessi&lt;br&gt;Deviation: 0 €&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#76608a;fontColor=#ffffff;strokeColor=#432D57;align=left;spacingLeft=12;" vertex="1" parent="1">
<mxGeometry x="1745" y="550" width="170" height="170" as="geometry"/>
</mxCell>
<mxCell id="105" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;Essen&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#1ba1e2;fontColor=#ffffff;strokeColor=#006EAF;align=left;spacingLeft=12;" vertex="1" parent="1">
<mxGeometry x="1760" y="680" width="40" height="10" as="geometry"/>
</mxCell>
<mxCell id="106" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;Trinken&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#a20025;fontColor=#ffffff;strokeColor=#6F0000;align=left;spacingLeft=12;" vertex="1" parent="1">
<mxGeometry x="1800" y="680" width="40" height="10" as="geometry"/>
</mxCell>
<mxCell id="107" value="&lt;span style=&quot;font-size: 8px;&quot;&gt;Auto&lt;/span&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d80073;fontColor=#ffffff;strokeColor=#A50040;align=left;spacingLeft=12;" vertex="1" parent="1">
<mxGeometry x="1840" y="680" width="40" height="10" as="geometry"/>
</mxCell>
<mxCell id="111" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;fontSize=18;" edge="1" parent="1" source="108" target="74">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="108" value="Actor" style="shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;html=1;outlineConnect=0;fontSize=18;" vertex="1" parent="1">
<mxGeometry x="1715" y="150" width="30" height="60" as="geometry"/>
</mxCell>
</root> </root>
</mxGraphModel> </mxGraphModel>
</diagram> </diagram>
+1 -3
View File
@@ -1,11 +1,9 @@
services: services:
xpensely-server: xpensely-server:
image: tea.zendric.de/cedric/xpensely-server:latest image: tea.zendric.de/cedric/xpensely-server:latest
pull_policy: always
restart: always restart: always
environment: environment:
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET}
DB_PORT: 5432 DB_PORT: 5432
DB_P_NAME: ${POSTGRES_DB} DB_P_NAME: ${POSTGRES_DB}
DB_USERNAME: ${POSTGRES_USER} DB_USERNAME: ${POSTGRES_USER}
+1 -1
View File
@@ -1,4 +1,4 @@
FROM eclipse-temurin:17-jdk FROM eclipse-temurin:21-jdk
COPY ./target/*.jar app.jar COPY ./target/*.jar app.jar
+732
View File
@@ -0,0 +1,732 @@
# Xpensely Server — API Reference
> Last updated: 2026-05-14 · Branch: `dev`
## Table of Contents
1. [Overview](#1-overview)
2. [Authentication](#2-authentication)
3. [Rate Limiting](#3-rate-limiting)
4. [Endpoints](#4-endpoints)
- 4.1 [Home](#41-home)
- 4.2 [Users](#42-users)
- 4.3 [Expense Lists](#43-expense-lists)
5. [Data Models](#5-data-models)
6. [Error Handling](#6-error-handling)
7. [Recent Changes — `feature/security-hardening`](#7-recent-changes)
---
## 1. Overview
Xpensely Server is a Spring Boot REST API that manages shared expense lists for pairs of users. It uses Google OAuth2 JWT tokens for authentication. All protected endpoints require a valid Bearer token in the `Authorization` header.
**Base URL (local dev):** `http://localhost:8080`
**Content-Type:** `application/json` for all request and response bodies.
**Public endpoints (no auth required):**
| Method | Path | Description |
|--------|------|-------------|
| GET | `/` | Health check — returns `"Welcome"` |
| GET | `/api/version` | Returns build version and timestamp |
| POST | `/api/users/createUser` | Register a new user |
| GET | `/api/users/byName` | Look up a user by username |
All other endpoints require authentication (see [Section 2](#2-authentication)).
## 2. Authentication
The server uses **OAuth2 Resource Server** authentication with **Google ID JWT tokens**.
### How it works
1. The client authenticates with Google and receives a Google ID JWT.
2. Every protected API request must include this token in the header:
```
Authorization: Bearer <google-id-jwt>
```
3. The server validates the JWT signature and extracts the `sub` claim (Google User ID).
4. The `sub` value is used to look up the registered `AppUser` in the database via `AuthenticatedUserResolver`.
5. If no `AppUser` exists for that Google ID, the request is rejected with **403 Forbidden**.
### Test profile
When the application runs under the `test` Spring profile (`-Dspring.profiles.active=test`), **all security is disabled** — every endpoint is accessible without a token. This is used for automated tests only.
### User registration flow
Before a user can call any protected endpoint they must first be registered:
1. Authenticate with Google to obtain a Google ID JWT.
2. Call `POST /api/users/createUser` with the JWT's `sub` value as `googleId` and a chosen `username`.
3. All subsequent protected calls use the same JWT — the server resolves the caller automatically.
## 3. Rate Limiting
All requests pass through a `RateLimitFilter` (implemented with **Bucket4j**).
| Setting | Value |
|---------|-------|
| Limit | 60 requests per minute |
| Window | Rolling 1-minute bucket |
| Key (authenticated) | JWT `sub` claim (Google User ID) |
| Key (unauthenticated) | `X-Forwarded-For` header, falling back to remote IP |
When the limit is exceeded the server responds with:
```
HTTP 429 Too Many Requests
```
No `Retry-After` header is currently returned. Clients should back off and retry after 60 seconds.
> **Note:** Rate limiting applies in the `!test` profile only. Tests run without rate limiting.
## 4. Endpoints
### 4.1 Home
#### `GET /`
Health check. No authentication required.
**Response:** `200 OK`
```
Welcome
```
---
#### `GET /api/version`
Returns the application version and build timestamp. No authentication required.
**Response:** `200 OK`
```json
{
"version": "0.0.1-SNAPSHOT",
"builtAt": "2026-05-09T10:00:00Z"
}
```
| Field | Type | Notes |
|-------|------|-------|
| `version` | String | Maven project version |
| `builtAt` | String (ISO-8601) | UTC timestamp of the build |
---
### 4.2 Users
Base path: `/api/users`
---
#### `POST /api/users/createUser` — Register a user
**Auth required:** No
**Request body:**
```json
{
"username": "alice",
"googleId": "118400012345678901234"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `username` | String | Required. 330 chars. Pattern: `^[a-zA-Z0-9_.\-]+$` |
| `googleId` | String | Required. Non-blank. Must match the JWT `sub` from Google. |
**Success response:** `201 Created` — returns the created [AppUser](#appuser) object.
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure (field errors returned as `{"fieldName": "message"}`) |
| 409 | `username` already taken |
---
#### `GET /api/users` — Get user by ID
**Auth required:** Yes
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | Long | Yes | Database ID of the user |
**Success response:** `200 OK` — returns [AppUser](#appuser).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Authenticated user's ID does not match the requested `id` |
| 404 | No user found for `id` |
---
#### `GET /api/users/byName` — Get user by username
**Auth required:** No
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `username` | String | Yes | Exact username (case-sensitive) |
**Success response:** `200 OK` — returns [AppUser](#appuser).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 404 | No user found for `username` |
---
#### `GET /api/users/byGoogleId` — Get user by Google ID
**Auth required:** Yes
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | String | Yes | Google `sub` claim |
**Success response:** `200 OK` — returns [AppUser](#appuser).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Requested Google ID does not match the authenticated user's Google ID |
| 404 | No user found for that Google ID |
---
#### `DELETE /api/users` — Delete a user
**Auth required:** Yes
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | Long | Yes | Database ID of the user to delete |
**Success response:** `200 OK` — returns a plain string: `"User deleted: <username>"`.
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Authenticated user's ID does not match the requested `id` |
| 404 | No user found for `id` |
---
### 4.3 Expense Lists
Base path: `/api/expenselist`
All endpoints in this group require authentication. The authenticated caller is resolved from the JWT and used for ownership checks.
---
#### `GET /api/expenselist/mine` — Get caller's expense lists
Returns all expense lists where the caller is the owner **or** has been shared the list.
**Auth required:** Yes
**Request body:** None
**Success responses:**
| Status | Condition |
|--------|-----------|
| 200 OK | Returns array of [ExpenseList](#expenselist) |
| 204 No Content | Caller has no expense lists |
```json
[
{
"id": 1,
"name": "Holiday Trip",
"inviteCode": null,
"owner": { "id": 1, "username": "alice" },
"sharedWith": null,
"expenses": [],
"customCategories": []
}
]
```
---
#### `GET /api/expenselist/byId` — Get expense list by ID
**Auth required:** Yes
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | Long | Yes | Expense list database ID |
The caller must be the owner or the shared user of the list.
**Success response:** `200 OK` — returns [ExpenseList](#expenselist).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Caller is neither owner nor shared user |
| 404 | No list found for `id` |
---
#### `POST /api/expenselist/create` — Create an expense list
**Auth required:** Yes
**Request body:**
```json
{
"name": "Road Trip 2026"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `name` | String | Required. Max 100 chars. |
The authenticated caller becomes the `owner` of the new list. The list is initialised with the default Xpensely standard categories.
**Success response:** `201 Created` — returns the created [ExpenseList](#expenselist).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure |
---
#### `DELETE /api/expenselist/{id}` — Delete an expense list
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `id` | Long | Expense list database ID |
Only the **owner** may delete a list. Deleting a list cascades to all its expenses and custom categories.
**Success response:** `204 No Content`
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Caller is not the owner |
| 404 | No list found for `id` |
---
#### `POST /api/expenselist/{id}/add` — Add an expense to a list
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `id` | Long | Expense list database ID |
**Request body:**
```json
{
"title": "Dinner",
"owner": "alice",
"amount": 42.50,
"personalUseAmount": 21.25,
"otherPersonAmount": 21.25,
"date": "2026-05-09",
"category": "Food"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `title` | String | Required. Max 100 chars. |
| `owner` | String | Required. Username of the person who paid. |
| `amount` | Double | Required. Min 0.01. |
| `personalUseAmount` | Double | Optional. Caller's share. |
| `otherPersonAmount` | Double | Optional. Other person's share. |
| `date` | String (ISO-8601) | Required. Format: `YYYY-MM-DD`. |
| `category` | String | Required. Non-blank category name. |
**Success response:** `201 Created` — returns the created [Expense](#expense).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure |
| 403 | Caller is not a member (owner or sharedWith) of the list |
| 404 | List not found |
---
#### `PUT /api/expenselist/{id}/update` — Update an expense
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `id` | Long | Expense list database ID |
**Request body:**
```json
{
"id": 7,
"title": "Dinner (updated)",
"ownerName": "alice",
"amount": 50.00,
"personalUseAmount": 25.00,
"otherPersonAmount": 25.00,
"date": "2026-05-09",
"category": "Food"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `id` | Long | Required. ID of the expense to update. |
| `title` | String | Required. Max 100 chars. |
| `ownerName` | String | Required. Username of the payer. |
| `amount` | Double | Required. Min 0.01. |
| `personalUseAmount` | Double | Optional. |
| `otherPersonAmount` | Double | Optional. |
| `date` | String (ISO-8601) | Required. `YYYY-MM-DD`. |
| `category` | String | Required. |
Caller must be a member of the list. Expense must belong to the specified list.
**Success response:** `200 OK` — returns the updated [Expense](#expense).
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure or expense does not belong to this list |
| 403 | Caller is not a member of the list |
| 404 | List or expense not found |
---
#### `DELETE /api/expenselist/{id}/delete` — Remove an expense from a list
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `id` | Long | Expense list database ID |
**Query params:**
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `expenseId` | Long | Yes | ID of the expense to remove |
Caller must be a member of the list.
**Success response:** `204 No Content`
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Caller is not a member of the list |
| 404 | List or expense not found |
---
#### `POST /api/expenselist/{listId}/invite` — Generate an invite code
Generates (or refreshes) a 6-character uppercase invite code for the list, valid for **1 week**.
**Auth required:** Yes
**Path params:**
| Param | Type | Description |
|-------|------|-------------|
| `listId` | Long | Expense list database ID |
Caller must be the **owner** of the list.
**Success response:** `200 OK` — returns the invite code as a plain string.
```
AB3X7Q
```
**Error responses:**
| Status | Condition |
|--------|-----------|
| 403 | Caller is not the owner |
| 404 | List not found |
---
#### `POST /api/expenselist/accept-invite` — Accept an invite
Joins the caller to a shared expense list using an invite code.
**Auth required:** Yes
**Request body:**
```json
{
"inviteCode": "AB3X7Q"
}
```
| Field | Type | Constraints |
|-------|------|-------------|
| `inviteCode` | String | Required. Exactly 6 characters. |
**Success response:** `200 OK` — returns a plain string: `"User added to the list"`.
**Error responses:**
| Status | Condition |
|--------|-----------|
| 400 | Validation failure or caller is already the owner of the list |
| 404 | Invite code not found or expired |
| 226 IM Used | List already has a second member (`sharedWith` is not null) |
---
## 5. Data Models
### AppUser
Returned by all `/api/users` endpoints. Sensitive fields (`googleId`, `createdAt`) are hidden from API responses via `@JsonIgnore`.
```json
{
"id": 1,
"username": "alice"
}
```
| Field | Type | Notes |
|-------|------|-------|
| `id` | Long | Auto-generated primary key |
| `username` | String | Unique. 330 chars. |
---
### ExpenseList
```json
{
"id": 1,
"name": "Road Trip",
"inviteCode": "AB3X7Q",
"owner": { "id": 1, "username": "alice" },
"sharedWith": { "id": 2, "username": "bob" },
"xpenselyStandardCategories": {
"id": 1,
"categories": [
{ "id": 1, "name": "Food", "colorCode": "#FF5733" }
]
},
"customCategories": [],
"expenses": []
}
```
| Field | Type | Notes |
|-------|------|-------|
| `id` | Long | Auto-generated primary key |
| `name` | String | Display name of the list |
| `inviteCode` | String \| null | 6-char code; `null` if not yet generated or expired |
| `owner` | AppUser | User who created the list |
| `sharedWith` | AppUser \| null | Second member of the list; `null` until an invite is accepted |
| `xpenselyStandardCategories` | XpenselyStandardCategories | Default category set assigned at creation |
| `customCategories` | XpenselyCustomCategory[] | User-defined categories, ordered A→Z |
| `expenses` | Expense[] | All expenses, ordered by date ASC then id ASC |
> `inviteCodeExpiration` is hidden from API responses (`@JsonIgnore`).
---
### Expense
```json
{
"id": 7,
"title": "Dinner",
"owner": { "id": 1, "username": "alice" },
"amount": 42.50,
"personalUseAmount": 21.25,
"otherPersonAmount": 21.25,
"category": "Food",
"date": "2026-05-09"
}
```
| Field | Type | Notes |
|-------|------|-------|
| `id` | Long | Auto-generated |
| `title` | String | Description of the expense |
| `owner` | AppUser | Who paid |
| `amount` | Double | Total amount. Min 0.01. |
| `personalUseAmount` | Double \| null | Caller's share |
| `otherPersonAmount` | Double \| null | Other member's share |
| `category` | String | Category name (free text — must match a category on the list) |
| `date` | String (ISO-8601) | `YYYY-MM-DD` |
> The `expenseList` back-reference is excluded via `@JsonBackReference` to prevent circular serialisation.
---
### XpenselyStandardCategories
A named group of standard categories assigned to every new expense list.
```json
{
"id": 1,
"categories": [
{ "id": 1, "name": "Food", "colorCode": "#FF5733" },
{ "id": 2, "name": "Transport", "colorCode": "#3498DB" }
]
}
```
---
### XpenselyCustomCategory
A user-defined category attached to a specific expense list.
```json
{
"id": 5,
"name": "Souvenirs",
"colorCode": "#9B59B6"
}
```
| Field | Type | Notes |
|-------|------|-------|
| `id` | Long | Auto-generated |
| `name` | String | Category label |
| `colorCode` | String | 7-char hex string e.g. `#RRGGBB` |
> The `expenseList` back-reference is excluded via `@JsonBackReference`.
## 6. Error Handling
All errors are returned as JSON. The `GlobalExceptionHandler` (`@RestControllerAdvice`) maps exceptions to HTTP status codes consistently across every endpoint.
### Error response format
Most errors:
```json
{
"error": "Human-readable message"
}
```
Validation errors (`400`):
```json
{
"username": "size must be between 3 and 30",
"googleId": "must not be blank"
}
```
### Status code reference
| HTTP Status | Condition | Source |
|-------------|-----------|--------|
| 400 Bad Request | Input validation failed (missing/invalid fields) | `MethodArgumentNotValidException` via `@Valid` |
| 400 Bad Request | Business rule violation (e.g. expense not in this list) | `IllegalArgumentException` |
| 403 Forbidden | User not registered in the system | `AuthenticatedUserResolver``ResponseStatusException(FORBIDDEN)` |
| 403 Forbidden | Ownership check failed (e.g. deleting someone else's list) | `ResponseStatusException(FORBIDDEN)` in controller |
| 404 Not Found | Entity does not exist (user, list, expense) | `ResourceNotFoundException` |
| 409 Conflict | Username already taken | `UsernameAlreadyExistsException` |
| 429 Too Many Requests | Rate limit exceeded | `RateLimitFilter` (returned directly, not via exception handler) |
| 500 Internal Server Error | Unexpected runtime or generic exception | `RuntimeException` / `Exception` — message is hidden from client |
## 7. Recent Changes — `feature/security-hardening`
This section summarises API-visible changes introduced on the `feature/security-hardening` branch (commits `3d456f2``b1324e3``8b96433``f0de751`). A developer or agent reading this document should be aware of these differences compared to the `main` branch.
---
### New: Centralised error handling (`GlobalExceptionHandler`)
**File:** `src/main/java/.../controller/GlobalExceptionHandler.java`
All error responses now follow the consistent JSON shape described in [Section 6](#6-error-handling). Previously, individual controllers returned ad-hoc responses, including HTTP 417 and raw stack trace output. Both have been removed. SLF4J logging has been added for server-side error visibility.
---
### New: `AuthenticatedUserResolver`
**File:** `src/main/java/.../security/AuthenticatedUserResolver.java`
A new component that extracts the Google ID from the JWT `sub` claim and resolves the corresponding `AppUser`. Injected into all protected controller methods. Returns `403 Forbidden` if the token is valid but the user has never called `POST /api/users/createUser`.
---
### New: `RateLimitFilter` — 60 req/min
**File:** `src/main/java/.../security/RateLimitFilter.java`
Rate limiting was not present on `main`. See [Section 3](#3-rate-limiting) for full details.
---
### New: `CreateExpenseListRequest` DTO with validation
**File:** `src/main/java/.../model/CreateExpenseListRequest.java`
`POST /api/expenselist/create` previously accepted a raw `ExpenseList` body. It now requires a `CreateExpenseListRequest` with a single validated `name` field (`@NotBlank`, `@Size(max=100)`). Clients must update their request body shape.
---
### Updated: Validation constraints tightened on existing DTOs
| DTO | Field | Change |
|-----|-------|--------|
| `AppUserCreateRequest` | `username` | Added `@Pattern(regexp="^[a-zA-Z0-9_.\-]+$")` — special characters (other than `_`, `.`, `-`) now rejected |
| `InviteRequest` | `inviteCode` | Added `@Size(min=6, max=6)` — non-6-char codes now rejected at binding |
| `ExpenseInput` | `amount` | Added `@DecimalMin("0.01")` — zero and negative amounts now rejected |
| `ExpenseChangeRequest` | `amount` | Added `@DecimalMin("0.01")` — zero and negative amounts now rejected |
---
### Updated: `SecurityConfig` — test-profile isolation
**File:** `src/main/java/.../security/SecurityConfig.java`
Two separate `SecurityFilterChain` beans now exist:
- `@Profile("test")` — all endpoints permitted, CSRF disabled (for automated tests only).
- `@Profile("!test")` — full JWT/OAuth2 enforcement (production behaviour).
Previously a single config was used for both, which made tests fragile.
---
### Fixed: `ExpenseListService` — JPQL and exception consistency
- Single `@Param` used in all JPQL queries (multi-param variant was broken).
- `ResourceNotFoundException` is now thrown consistently instead of returning `null` or a generic `RuntimeException`.
- `addExpenseToList` delegates directly to `ExpenseList.addExpense()` rather than looping.
---
### Fixed: `UserService` — null returns replaced with exceptions
All not-found paths in `UserService` now throw `ResourceNotFoundException` instead of returning `null`. Callers that previously needed to null-check responses will now receive a `404` response.
Vendored Regular → Executable
View File
+137 -119
View File
@@ -1,124 +1,142 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <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"> 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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.1</version> <version>4.0.6</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/> <!-- lookup parent from repository -->
</parent> </parent>
<groupId>de.zendric.app</groupId> <groupId>de.zendric.app</groupId>
<artifactId>XpenselyServer</artifactId> <artifactId>XpenselyServer</artifactId>
<version>1.0.0</version> <version>1.0.0</version>
<name>XpenselyServer</name> <name>XpenselyServer</name>
<description>XpenselyServer used to handle the Xpensely App</description> <description>XpenselyServer used to handle the Xpensely App</description>
<url/> <url/>
<licenses> <licenses>
<license/> <license/>
</licenses> </licenses>
<developers> <developers>
<developer/> <developer/>
</developers> </developers>
<scm> <scm>
<connection/> <connection/>
<developerConnection/> <developerConnection/>
<tag/> <tag/>
<url/> <url/>
</scm> </scm>
<properties> <properties>
<java.version>21</java.version> <java.version>21</java.version>
</properties> <lombok.version>1.18.46</lombok.version>
<dependencies> </properties>
<dependency> <dependencies>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-data-jpa</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-data-jpa</artifactId>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-security</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-security</artifactId>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-validation</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-validation</artifactId>
<dependency> </dependency>
<groupId>com.bucket4j</groupId> <dependency>
<artifactId>bucket4j-core</artifactId> <groupId>com.bucket4j</groupId>
<version>8.10.1</version> <artifactId>bucket4j-core</artifactId>
</dependency> <version>8.10.1</version>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-oauth2-client</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-oauth2-client</artifactId>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-web</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-web</artifactId>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-devtools</artifactId> <groupId>org.springframework.boot</groupId>
<scope>runtime</scope> <artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <scope>runtime</scope>
</dependency> <optional>true</optional>
<dependency> </dependency>
<groupId>org.postgresql</groupId> <dependency>
<artifactId>postgresql</artifactId> <groupId>org.postgresql</groupId>
<scope>runtime</scope> <artifactId>postgresql</artifactId>
</dependency> <scope>runtime</scope>
<dependency> </dependency>
<groupId>org.projectlombok</groupId> <dependency>
<artifactId>lombok</artifactId> <groupId>org.projectlombok</groupId>
<optional>true</optional> <artifactId>lombok</artifactId>
</dependency> <optional>true</optional>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-test</artifactId> <groupId>org.springframework.boot</groupId>
<scope>test</scope> <artifactId>spring-boot-starter-test</artifactId>
</dependency> <scope>test</scope>
<dependency> </dependency>
<groupId>com.h2database</groupId> <dependency>
<artifactId>h2</artifactId> <groupId>org.springframework.boot</groupId>
<scope>test</scope> <artifactId>spring-boot-starter-webmvc-test</artifactId>
</dependency> <scope>test</scope>
<dependency> </dependency>
<groupId>org.springframework.security</groupId> <dependency>
<artifactId>spring-security-test</artifactId> <groupId>org.springframework.boot</groupId>
<scope>test</scope> <artifactId>spring-boot-starter-data-jpa-test</artifactId>
</dependency> <scope>test</scope>
</dependencies> </dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <configuration>
<annotationProcessorPaths> <annotationProcessorPaths>
<path> <path>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
</path> </path>
</annotationProcessorPaths> </annotationProcessorPaths>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration> <configuration>
<excludes> <excludes>
<exclude> <exclude>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
</exclude> </exclude>
</excludes> </excludes>
</configuration> </configuration>
</plugin> <executions>
</plugins> <execution>
</build> <goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>
@@ -9,7 +9,6 @@ import org.springframework.web.server.ResponseStatusException;
import de.zendric.app.xpensely_server.model.AppUser; import de.zendric.app.xpensely_server.model.AppUser;
import de.zendric.app.xpensely_server.model.AppUserCreateRequest; import de.zendric.app.xpensely_server.model.AppUserCreateRequest;
import de.zendric.app.xpensely_server.model.Exception.UsernameAlreadyExistsException;
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver; import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
import de.zendric.app.xpensely_server.services.UserService; import de.zendric.app.xpensely_server.services.UserService;
@@ -47,15 +46,9 @@ public class AppUserController {
@PostMapping("/createUser") @PostMapping("/createUser")
public ResponseEntity<AppUser> createUser(@RequestBody @Valid AppUserCreateRequest userRequest) { public ResponseEntity<AppUser> createUser(@RequestBody @Valid AppUserCreateRequest userRequest) {
try { AppUser convertedUser = userRequest.convertToAppUser();
AppUser convertedUser = userRequest.convertToAppUser(); AppUser nUser = userService.createUser(convertedUser);
AppUser nUser = userService.createUser(convertedUser); return new ResponseEntity<>(nUser, HttpStatus.CREATED);
return new ResponseEntity<>(nUser, HttpStatus.CREATED);
} catch (UsernameAlreadyExistsException e) {
return new ResponseEntity<>(null, HttpStatus.CONFLICT);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
} }
@DeleteMapping @DeleteMapping
@@ -5,6 +5,8 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
@@ -21,6 +23,8 @@ import de.zendric.app.xpensely_server.services.UserService;
@RequestMapping("/api/expenselist") @RequestMapping("/api/expenselist")
public class ExpenseListController { public class ExpenseListController {
private static final Logger log = LoggerFactory.getLogger(ExpenseListController.class);
private final ExpenseListService expenseListService; private final ExpenseListService expenseListService;
private final UserService userService; private final UserService userService;
private final CategoryService categoryService; private final CategoryService categoryService;
@@ -54,22 +58,18 @@ public class ExpenseListController {
} }
@PostMapping("/create") @PostMapping("/create")
public ResponseEntity<ExpenseList> create(@RequestBody ExpenseList expenseList, public ResponseEntity<ExpenseList> create(@RequestBody @Valid CreateExpenseListRequest request,
Authentication authentication) { Authentication authentication) {
try { AppUser authenticatedUser = authenticatedUserResolver.resolveCurrentUser(authentication);
AppUser authenticatedUser = authenticatedUserResolver.resolveCurrentUser(authentication); ExpenseList expenseList = new ExpenseList();
expenseList.setOwner(authenticatedUser); expenseList.setName(request.getName());
XpenselyStandardCategories standardCategories = categoryService.getDefaultCategories(); expenseList.setOwner(authenticatedUser);
expenseList.setXpenselyStandardCategories(standardCategories); XpenselyStandardCategories standardCategories = categoryService.getDefaultCategories();
expenseList.setSharedWith(null); expenseList.setXpenselyStandardCategories(standardCategories);
ExpenseList savedItem = expenseListService.createList(expenseList); expenseList.setSharedWith(null);
return new ResponseEntity<>(savedItem, HttpStatus.CREATED); ExpenseList savedItem = expenseListService.createList(expenseList);
} catch (ResponseStatusException e) { log.debug("Created expense list '{}' for user {}", savedItem.getName(), authenticatedUser.getId());
throw e; return new ResponseEntity<>(savedItem, HttpStatus.CREATED);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED);
}
} }
@DeleteMapping("{id}") @DeleteMapping("{id}")
@@ -79,12 +79,8 @@ public class ExpenseListController {
if (listOpt.isEmpty()) if (listOpt.isEmpty())
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
assertOwner(user, listOpt.get()); assertOwner(user, listOpt.get());
try { expenseListService.deleteById(id);
expenseListService.deleteById(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
}
} }
@PostMapping("/{id}/add") @PostMapping("/{id}/add")
@@ -97,14 +93,10 @@ public class ExpenseListController {
if (listOpt.isEmpty()) if (listOpt.isEmpty())
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
assertMember(user, listOpt.get()); assertMember(user, listOpt.get());
try { AppUser expenseOwner = userService.getUserByName(expenseInput.getOwner());
AppUser expenseOwner = userService.getUserByName(expenseInput.getOwner()); Expense expense = expenseInput.convertToExpense(expenseOwner.getId());
Expense expense = expenseInput.convertToExpense(expenseOwner.getId()); Expense addedExpense = expenseListService.addExpenseToList(expenseListId, expense);
Expense addedExpense = expenseListService.addExpenseToList(expenseListId, expense); return new ResponseEntity<>(addedExpense, HttpStatus.CREATED);
return new ResponseEntity<>(addedExpense, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
@PutMapping("/{id}/update") @PutMapping("/{id}/update")
@@ -115,16 +107,12 @@ public class ExpenseListController {
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication); AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
Optional<ExpenseList> expenseListOpt = expenseListService.findById(expenseListId); Optional<ExpenseList> expenseListOpt = expenseListService.findById(expenseListId);
if (expenseListOpt.isEmpty()) if (expenseListOpt.isEmpty())
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
assertMember(user, expenseListOpt.get()); assertMember(user, expenseListOpt.get());
try { AppUser expenseOwner = userService.getUserByName(expenseChangeRequest.getOwnerName());
AppUser expenseOwner = userService.getUserByName(expenseChangeRequest.getOwnerName()); Expense expense = expenseChangeRequest.convertToExpense(expenseOwner.getId(), expenseListOpt.get());
Expense expense = expenseChangeRequest.convertToExpense(expenseOwner.getId(), expenseListOpt.get()); Expense updatedExpense = expenseListService.updateExpense(expenseListId, expense);
Expense updatedExpense = expenseListService.updateExpense(expenseListId, expense); return new ResponseEntity<>(updatedExpense, HttpStatus.OK);
return new ResponseEntity<>(updatedExpense, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
} }
@DeleteMapping("/{id}/delete") @DeleteMapping("/{id}/delete")
@@ -137,12 +125,8 @@ public class ExpenseListController {
if (listOpt.isEmpty()) if (listOpt.isEmpty())
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
assertMember(user, listOpt.get()); assertMember(user, listOpt.get());
try { expenseListService.deleteExpenseFromList(expenseListId, expenseId);
expenseListService.deleteExpenseFromList(expenseListId, expenseId); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED);
}
} }
@PostMapping("/{listId}/invite") @PostMapping("/{listId}/invite")
@@ -1,11 +1,16 @@
package de.zendric.app.xpensely_server.controller; package de.zendric.app.xpensely_server.controller;
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
import de.zendric.app.xpensely_server.model.Exception.UsernameAlreadyExistsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError; import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -13,6 +18,8 @@ import java.util.Map;
@RestControllerAdvice @RestControllerAdvice
public class GlobalExceptionHandler { public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(MethodArgumentNotValidException.class) @ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) { public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>(); Map<String, String> errors = new HashMap<>();
@@ -27,4 +34,36 @@ public class GlobalExceptionHandler {
return ResponseEntity.status(HttpStatus.BAD_REQUEST) return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", ex.getMessage())); .body(Map.of("error", ex.getMessage()));
} }
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Map<String, String>> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("error", ex.getMessage()));
}
@ExceptionHandler(UsernameAlreadyExistsException.class)
public ResponseEntity<Map<String, String>> handleUsernameConflict(UsernameAlreadyExistsException ex) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Map.of("error", ex.getMessage()));
}
@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<Map<String, String>> handleResponseStatus(ResponseStatusException ex) {
return ResponseEntity.status(ex.getStatusCode())
.body(Map.of("error", ex.getReason() != null ? ex.getReason() : ex.getMessage()));
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Map<String, String>> handleRuntime(RuntimeException ex) {
log.error("Unhandled runtime exception", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "An unexpected error occurred"));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, String>> handleGeneric(Exception ex) {
log.error("Unhandled exception", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "An unexpected error occurred"));
}
} }
@@ -1,13 +1,30 @@
package de.zendric.app.xpensely_server.controller; package de.zendric.app.xpensely_server.controller;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController @RestController
class HomeController { class HomeController {
private final BuildProperties buildProperties;
HomeController(BuildProperties buildProperties) {
this.buildProperties = buildProperties;
}
@GetMapping("/") @GetMapping("/")
public String getAll() { public String getAll() {
return "Welcome"; return "Welcome";
} }
@GetMapping("/api/version")
public Map<String, String> version() {
return Map.of(
"version", buildProperties.getVersion(),
"builtAt", buildProperties.getTime().toString()
);
}
} }
@@ -0,0 +1,17 @@
package de.zendric.app.xpensely_server.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class CreateExpenseListRequest {
@NotBlank(message = "List name is required")
@Size(max = 100, message = "List name must not exceed 100 characters")
private String name;
}
@@ -6,7 +6,7 @@ import org.springframework.context.annotation.Profile;
import org.springframework.security.config.Customizer; import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 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.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter; import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
@Configuration @Configuration
@@ -18,7 +18,7 @@ public class SecurityConfig {
http http
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
.anyRequest().permitAll()) .anyRequest().permitAll())
.csrf().disable(); .csrf(csrf -> csrf.disable());
return http.build(); return http.build();
} }
@@ -28,12 +28,12 @@ public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http http
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
.requestMatchers("/api/version").permitAll()
.anyRequest().authenticated()) .anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2 .oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())) .jwt(Customizer.withDefaults()))
.oauth2Login(Customizer.withDefaults())
.addFilterAfter(new RateLimitFilter(), BearerTokenAuthenticationFilter.class) .addFilterAfter(new RateLimitFilter(), BearerTokenAuthenticationFilter.class)
.csrf().disable(); .csrf(csrf -> csrf.disable());
return http.build(); return http.build();
} }
@@ -31,18 +31,10 @@ public class ExpenseListService {
this.customCategoryRepository = customCategoryRepository; this.customCategoryRepository = customCategoryRepository;
} }
public List<ExpenseList> getAllLists() {
return repository.findAll();
}
public ExpenseList createList(ExpenseList list) { public ExpenseList createList(ExpenseList list) {
return repository.save(list); return repository.save(list);
} }
public void deleteList(Long id) {
repository.deleteById(id);
}
public void deleteById(Long id) { public void deleteById(Long id) {
repository.deleteById(id); repository.deleteById(id);
} }
@@ -51,10 +43,6 @@ public class ExpenseListService {
return repository.findById(id); return repository.findById(id);
} }
public Iterable<ExpenseList> findAll() {
return repository.findAll();
}
public ExpenseList save(ExpenseList expenseList) { public ExpenseList save(ExpenseList expenseList) {
return repository.save(expenseList); return repository.save(expenseList);
} }
@@ -3,8 +3,6 @@ spring.application.name=XpenselyServer
#Security #Security
spring.security.enabled=false spring.security.enabled=false
spring.security.oauth2.client.registration.google.client-id=${GOOGLE_CLIENT_ID}
spring.security.oauth2.client.registration.google.client-secret=${GOOGLE_CLIENT_SECRET}
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://accounts.google.com spring.security.oauth2.resourceserver.jwt.issuer-uri=https://accounts.google.com
# PostgreSQL Configuration # PostgreSQL Configuration
@@ -4,7 +4,7 @@ import de.zendric.app.xpensely_server.model.ExpenseList;
import de.zendric.app.xpensely_server.repo.ExpenseListRepository; import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import java.util.Optional; import java.util.Optional;
@@ -6,8 +6,11 @@ import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
import de.zendric.app.xpensely_server.services.UserService; import de.zendric.app.xpensely_server.services.UserService;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.security.oauth2.client.autoconfigure.OAuth2ClientAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.security.oauth2.client.autoconfigure.servlet.OAuth2ClientWebSecurityAutoConfiguration;
import org.springframework.boot.security.oauth2.server.resource.autoconfigure.servlet.OAuth2ResourceServerAutoConfiguration;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoBean;
@@ -18,7 +21,11 @@ import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(AppUserController.class) @WebMvcTest(value = AppUserController.class, excludeAutoConfiguration = {
OAuth2ClientAutoConfiguration.class,
OAuth2ClientWebSecurityAutoConfiguration.class,
OAuth2ResourceServerAutoConfiguration.class
})
@AutoConfigureMockMvc(addFilters = false) @AutoConfigureMockMvc(addFilters = false)
@ActiveProfiles("test") @ActiveProfiles("test")
class AppUserControllerTest { class AppUserControllerTest {
@@ -9,8 +9,11 @@ import de.zendric.app.xpensely_server.services.ExpenseListService;
import de.zendric.app.xpensely_server.services.UserService; import de.zendric.app.xpensely_server.services.UserService;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.security.oauth2.client.autoconfigure.OAuth2ClientAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.security.oauth2.client.autoconfigure.servlet.OAuth2ClientWebSecurityAutoConfiguration;
import org.springframework.boot.security.oauth2.server.resource.autoconfigure.servlet.OAuth2ResourceServerAutoConfiguration;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoBean;
@@ -24,7 +27,11 @@ import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(ExpenseListController.class) @WebMvcTest(value = ExpenseListController.class, excludeAutoConfiguration = {
OAuth2ClientAutoConfiguration.class,
OAuth2ClientWebSecurityAutoConfiguration.class,
OAuth2ResourceServerAutoConfiguration.class
})
@AutoConfigureMockMvc(addFilters = false) @AutoConfigureMockMvc(addFilters = false)
@ActiveProfiles("test") @ActiveProfiles("test")
class ExpenseListControllerTest { class ExpenseListControllerTest {
@@ -132,4 +139,43 @@ class ExpenseListControllerTest {
mockMvc.perform(get("/api/expenselist/mine")) mockMvc.perform(get("/api/expenselist/mine"))
.andExpect(status().isOk()); .andExpect(status().isOk());
} }
@Test
void create_returns500_onUnexpectedServiceError() throws Exception {
AppUser user = new AppUser();
user.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
when(categoryService.getDefaultCategories()).thenThrow(new RuntimeException("db down"));
mockMvc.perform(post("/api/expenselist/create")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Groceries\"}"))
.andExpect(status().isInternalServerError());
}
@Test
void create_returns400_whenNameIsBlank() throws Exception {
AppUser user = new AppUser();
user.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
mockMvc.perform(post("/api/expenselist/create")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.name").exists());
}
@Test
void create_returns400_whenBodyIsEmpty() throws Exception {
AppUser user = new AppUser();
user.setId(1L);
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
mockMvc.perform(post("/api/expenselist/create")
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.name").exists());
}
} }