81 changed files with 3445 additions and 40 deletions
+21
View File
@@ -1,9 +1,15 @@
# Git
.git
.github
.gitignore
.gitattributes
# Environment / secrets
.env
.env.*
!.env.example
secrets
certs
volumes
data
@@ -18,3 +24,18 @@ __pycache__
node_modules
evidence
.DS_Store
# Gradle
.gradle/
build/
# IDE
.idea/
*.iml
.vscode/
.project
.classpath
.settings/
# Documentation
*.md
+19 -3
View File
@@ -5,7 +5,23 @@ APP_PORT=8080
APP_ENV=lab
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url
DATABASE_NAME=messenger
DATABASE_USER=messenger
DATABASE_PASSWORD=change-me-for-local-development
DATABASE_URL=jdbc:postgresql://postgres:5432/messenger
DATABASE_PORT=5432
DATABASE_POOL_SIZE=10
DATABASE_MIN_IDLE=2
DATABASE_QUERY_TIMEOUT_SECONDS=5
DATABASE_TRANSACTION_TIMEOUT_SECONDS=5
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_EXPOSED_PORT=6379
REDIS_CONNECT_TIMEOUT=1s
REDIS_COMMAND_TIMEOUT=500ms
REDIS_POOL_MAX_ACTIVE=8
REDIS_POOL_MAX_IDLE=8
REDIS_POOL_MIN_IDLE=0
REDIS_POOL_MAX_WAIT=500ms
USER_CACHE_TTL_SECONDS=300
+48 -14
View File
@@ -1,18 +1,52 @@
## Лабораторная 2
Автор / группа: TODO
Целевая оценка (3/4/5): TODO
Трек 5, если заявлен: TODO
Автор / группа: Антипин Егор Иванович, БПИ2301
Целевая оценка (3/4/5): 4
Трек 5, если заявлен: не заявлен
Что реализовано и что перенесено: TODO
Команды запуска из чистого clone: TODO
Результаты проверок и ссылка на REPORT.md: TODO
Ограничения / известные ошибки: TODO
Источники и использование ИИ: TODO
Что реализовано и что перенесено: пользователи, чаты, членство, сообщения и действующие
сессии перенесены в PostgreSQL. Добавлены версионируемые Flyway-миграции, первичные и внешние
ключи, уникальность username, атомарное создание чата и keyset-пагинация истории. Реализованы
password KDF, Basic-вход только через `POST /auth/sessions`, opaque Bearer-сессии с expiry и logout,
Spring Security и Swagger UI. Redis используется как cache-aside-кэш пользователей с TTL и
fallback в PostgreSQL; включён AOF. Настроены ограниченные пулы соединений и таймауты.
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [ ] Контракт и публичные тесты не ослаблены.
- [ ] make check и make test выполнены; приложен реальный вывод.
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
Команды запуска из чистого clone:
```sh
cp .env.example .env
# Задать DATABASE_PASSWORD в локальном .env
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --wait
python3 -m pip install -r requirements-dev.txt
make check
make validate
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-operational
make explain-history
```
Результаты проверок и ссылка на REPORT.md: `make check`, `make validate` и `make test` — PASS;
`make test-persistence ACTION_SCRIPT=scripts/restart.sh` подтвердил сохранение данных и действующей
сессии после рестарта; `make test-operational` проверил expiry, logout, неверный пароль, отказы Redis
и PostgreSQL, гонку регистрации и rollback создания чата; `make explain-history` подтвердил
`Index Scan` без полного сканирования таблицы на 10 000 сообщениях. Подробности: [REPORT.md](../REPORT.md),
план запроса: [evidence/message-history-explain.md](../evidence/message-history-explain.md).
Ограничения / известные ошибки: запущен один экземпляр API, высокая доступность не заявлена.
Проверка каждой Bearer-сессии обращается в PostgreSQL для строгого expiry/logout; Redis кэширует
только данные пользователя. Защита от cache stampede и нагрузочное исследование на 100 000+
сообщениях относятся к треку 5 и не реализованы. Известных ошибок обязательного уровня 4 нет.
Источники и использование ИИ: использованы материалы и контракт лабораторной работы, документация
Spring Boot/Spring Security, PostgreSQL, Flyway и Redis. ИИ применялся для анализа архитектуры,
подготовки реализации и тестовых сценариев; результат проверен автоматическими тестами и ручным
просмотром изменений. Секреты, токены и приватные ключи ИИ не передавались и в Git не добавлялись.
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [x] Контракт и публичные тесты не ослаблены.
- [x] make check и make test выполнены; приложен реальный вывод.
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
+1
View File
@@ -28,5 +28,6 @@ coverage/
.DS_Store
.idea/
.vscode/
.gradle/
# Keep small, sanitized evidence summaries in evidence/ under version control.
# Inspect git diff --cached: ignore rules are not a secret scanner.
+35
View File
@@ -0,0 +1,35 @@
# Stage 1: Build
FROM eclipse-temurin:23-jdk AS build
WORKDIR /app
COPY gradlew .
COPY gradle gradle
COPY build.gradle settings.gradle ./
COPY src src
RUN --mount=type=cache,target=/root/.gradle \
chmod +x gradlew && ./gradlew bootJar --no-daemon
# Stage 2: Runtime
FROM eclipse-temurin:23-jre
WORKDIR /app
COPY --from=build /app/build/libs/*.jar app.jar
RUN apt-get update \
&& apt-get install --yes --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --system --create-home messenger
USER messenger
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
CMD curl --fail --silent --show-error http://localhost:8080/health/live || exit 1
ENTRYPOINT ["java", "-jar", "app.jar"]
+12 -2
View File
@@ -4,10 +4,10 @@ CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence
.PHONY: help check validate test load test-persistence test-operational explain-history
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "check/validate: contract; test: API; test-persistence: restart; test-operational: failure/race/rollback; explain-history: 10k index plan"
check:
$(PYTHON) scripts/check_contract.py
@@ -22,5 +22,15 @@ load:
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-persistence:
ifeq ($(OS),Windows_NT)
@if "$(ACTION_SCRIPT)"=="" (echo Set ACTION_SCRIPT to your implemented executable restart hook & exit /b 2)
else
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
endif
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-operational:
$(PYTHON) tests/operational.py --base-url "$(BASE_URL)"
explain-history:
$(PYTHON) scripts/explain_history.py
+62 -20
View File
@@ -1,37 +1,79 @@
# Отчёт — лабораторная 2
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Антипин Егор Иванович, БПИ2301
- Целевая оценка: 4.
- Commit/PR: заполнить после публикации.
- Runtime: Java 23, Spring Boot 4.1.1, PostgreSQL 16.4, Redis 7.4, Python 3.11.
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Требуются Docker Desktop/Compose, JDK 23 и Python 3.9+.
## Архитектура и решения
```sh
cp .env.example .env
# Заменить DATABASE_PASSWORD в локальном .env; файл игнорируется Git.
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --wait
python3 -m pip install -r requirements-dev.txt
```
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
Безопасная остановка сохраняет данные: `docker compose --env-file .env stop`.
Намеренное удаление учебных данных: `docker compose --env-file .env down -v`.
## Архитектура и источники истины
Путь запроса: клиент → Spring Security/API → PostgreSQL. Redis является необязательным
cache-aside-ускорителем чтения пользователя после проверки Bearer-сессии.
PostgreSQL — источник истины для пользователей, чатов, членства, сообщений и сессий.
Сессия хранит SHA-256-хеш opaque-токена, абсолютный `expires_at` и `revoked_at`. Каждый Bearer-запрос
сначала проверяет в PostgreSQL, что сессия существует, не отозвана и не истекла. Только после этого
пользователь берётся из Redis либо PostgreSQL. Поэтому Redis не может авторизовать отозванный токен.
Redis хранит `messenger:user:<uuid>` с TTL 300 секунд. Cache miss и недоступность Redis приводят к
чтению PostgreSQL. Повреждённая запись удаляется. API пока не содержит изменения/удаления пользователя;
при появлении такой операции ключ должен удаляться после commit. Redis настроен с AOF
`appendfsync everysec` и именованным volume, хотя корректность не зависит от сохранности кэша.
Все JDBC-значения передаются параметрами. Динамические части запросов состоят только из статических
фрагментов приложения. HikariCP ограничен 10 соединениями, JDBC-запросы/транзакции имеют таймаут
5 секунд. Lettuce pool ограничен 8 соединениями, connect timeout — 1 секунда, command/max-wait —
500 мс.
Создание чата — транзакция: INSERT чата и все INSERT членства либо фиксируются вместе, либо полностью
откатываются. Уникальность username обеспечивается PostgreSQL, поэтому работает между процессами API;
предварительный SELECT служит только быстрым путём ответа.
Подробное описание находится в `infra/database-design.md`.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| Критерий | Команда/сценарий | Наблюдаемый результат | Доказательство |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
| Контракт и структура | `make check`, `make validate` | PASS | stdout команд |
| Публичный API | `make test` | `PASS: lab2 public API scenario` | `tests/smoke.py` |
| Полный рестарт | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | сообщение и сессия сохранены | hook перезапускает `postgres redis api` без `down -v` |
| Expiry/logout/password/отказы | `make test-operational` | PASS для всех сценариев | `tests/operational.py` |
| Гонка username | 12 параллельных POST одного username | один 201, остальные 409 | `tests/operational.py` |
| Rollback чата | временный trigger отклоняет участника | API 503, строки чата нет | `tests/operational.py` |
| Индекс истории | `make explain-history` | Index Scan, без Seq Scan, 10 000 строк | `evidence/message-history-explain.md` |
| Java integration tests | `gradlew test` с локальными DS env | BUILD SUCCESSFUL, 10 тестов | Gradle report |
| Secrets/volumes | `git ls-files` и ignore-файлы | приватные файлы не отслеживаются | `.gitignore`, `.dockerignore` |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
## Эксперименты отказов
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| Воздействие | Ожидание | Наблюдение | Восстановление / потеря |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
| Redis остановлен | cache-aside обходит кэш | Bearer `/users/me` остаётся 200 через PostgreSQL | после start кэш заполняется снова; потери нет |
| PostgreSQL остановлен | кэш не обходит проверку сессии | Bearer получает 503; анонимный запрос — 401 | соединения восстанавливаются; потери нет |
| TTL сессии 2 секунды | токен перестаёт действовать | до expiry 200, после 2.5 секунды 401 | повторный Basic login создаёт новую сессию |
| Logout | текущий токен отозван | DELETE 204, следующий запрос 401 | отзыв постоянный в PostgreSQL |
| Рестарт всех компонентов | volumes сохраняются | прежний токен и сообщение доступны | автоматическое ожидание readiness; потери нет |
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
- Стенд содержит один экземпляр API; высокая доступность API не заявлена.
- Redis ускоряет чтение пользователя, но проверка сессии всегда обращается в PostgreSQL ради строгих
expiry/logout. Это осознанный компромисс корректности и производительности.
- Защита от cache stampede и измерение latency/числа SQL-запросов относятся к треку 5 и не заявлены.
- `EXPLAIN` проверяет 10 000 равномерных сообщений; набор 100 000+ относится к треку 5.
+55
View File
@@ -0,0 +1,55 @@
plugins {
id 'java'
id 'org.springframework.boot' version '4.1.1'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(23)
}
}
repositories {
mavenCentral()
}
dependencies {
// implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-flyway'
implementation 'org.flywaydb:flyway-core'
implementation 'org.flywaydb:flyway-database-postgresql'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.bouncycastle:bcprov-jdk18on:1.84'
implementation 'org.apache.commons:commons-pool2'
runtimeOnly 'org.postgresql:postgresql'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.3'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
// testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test'
// testImplementation 'org.springframework.boot:spring-boot-starter-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
testCompileOnly 'org.projectlombok:lombok'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testAnnotationProcessor 'org.projectlombok:lombok'
implementation("com.github.f4b6a3:uuid-creator:6.1.1")
}
tasks.named('test') {
useJUnitPlatform()
}
+72
View File
@@ -0,0 +1,72 @@
services:
postgres:
image: postgres:16.4-bookworm
environment:
POSTGRES_DB: ${DATABASE_NAME:-messenger}
POSTGRES_USER: ${DATABASE_USER:-messenger}
POSTGRES_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env}
volumes:
- postgres-data:/var/lib/postgresql/data
ports:
- "127.0.0.1:${DATABASE_PORT:-5432}:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 3s
retries: 20
restart: unless-stopped
redis:
image: redis:7.4-bookworm
command:
- redis-server
- --appendonly
- "yes"
- --appendfsync
- everysec
volumes:
- redis-data:/data
ports:
- "127.0.0.1:${REDIS_EXPOSED_PORT:-6379}:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 20
restart: unless-stopped
api:
build:
context: .
environment:
APP_HOST: 0.0.0.0
APP_PORT: 8080
DATABASE_URL: jdbc:postgresql://postgres:5432/${DATABASE_NAME:-messenger}
DATABASE_USER: ${DATABASE_USER:-messenger}
DATABASE_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env}
DATABASE_POOL_SIZE: ${DATABASE_POOL_SIZE:-10}
DATABASE_MIN_IDLE: ${DATABASE_MIN_IDLE:-2}
DATABASE_QUERY_TIMEOUT_SECONDS: ${DATABASE_QUERY_TIMEOUT_SECONDS:-5}
DATABASE_TRANSACTION_TIMEOUT_SECONDS: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:-5}
REDIS_HOST: redis
REDIS_PORT: 6379
REDIS_CONNECT_TIMEOUT: ${REDIS_CONNECT_TIMEOUT:-1s}
REDIS_COMMAND_TIMEOUT: ${REDIS_COMMAND_TIMEOUT:-500ms}
REDIS_POOL_MAX_ACTIVE: ${REDIS_POOL_MAX_ACTIVE:-8}
REDIS_POOL_MAX_IDLE: ${REDIS_POOL_MAX_IDLE:-8}
REDIS_POOL_MIN_IDLE: ${REDIS_POOL_MIN_IDLE:-0}
REDIS_POOL_MAX_WAIT: ${REDIS_POOL_MAX_WAIT:-500ms}
USER_CACHE_TTL_SECONDS: ${USER_CACHE_TTL_SECONDS:-300}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
ports:
- "127.0.0.1:${APP_PORT:-8080}:8080"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
restart: unless-stopped
volumes:
postgres-data:
redis-data:
+38
View File
@@ -0,0 +1,38 @@
# Message history index evidence
Проверка выполнена командой `make explain-history`. Скрипт `scripts/explain_message_history.sql`
создаёт 10 000 сообщений внутри транзакции, выполняет `ANALYZE` и
`EXPLAIN (ANALYZE, BUFFERS)`, после чего делает `ROLLBACK`.
Проверяемый запрос соответствует JDBC-запросу страницы истории:
```sql
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT 100;
```
Фактический существенный фрагмент плана:
```text
Limit (cost=0.29..10.75 rows=100 width=74) (actual time=0.008..0.028 rows=100 loops=1)
Buffers: shared hit=6
-> Index Scan using messages_chat_created_id_idx on messages
(cost=0.29..524.11 rows=5007 width=74)
(actual time=0.007..0.021 rows=100 loops=1)
Index Cond: ((chat_id = '70000000-0000-4000-8000-000000000002'::uuid)
AND (ROW(created_at, id) > ROW(
'2026-01-01 00:00:05+00'::timestamptz,
'70000000-0000-4000-8000-000000005000'::uuid)))
Buffers: shared hit=6
Planning Time: 0.177 ms
Execution Time: 0.062 ms
```
Вывод: PostgreSQL начинает чтение с позиции курсора по индексу
`messages_chat_created_id_idx(chat_id, created_at, id)` и останавливается после 100 строк.
`Seq Scan on messages` отсутствует; стоимость страницы не требует повторного полного просмотра
10 000 предыдущих сообщений.
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed 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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+82
View File
@@ -0,0 +1,82 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem 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, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+77
View File
@@ -0,0 +1,77 @@
# Модель данных PostgreSQL
PostgreSQL является первоисточником данных о пользователях, чатах, участниках чатов, сообщениях и сессиях.
При запуске API инструмент Flyway применяет схему базы данных, описанную в файлах из директории `src/main/resources/db/migration`. Инициализация новой пустой базы данных выполняется с помощью скрипта `V1__create_messenger_schema.sql`.
## Таблицы и ограничения
- `users`: первичный ключ типа UUID, уникальное имя пользователя (username), проверка формата имени пользователя и длины отображаемого имени (display name), Argon2id-хеш пароля. Пароли в открытом виде не сохраняются.
- `chats`: первичный ключ типа UUID, проверка длины названия чата.
- `chat_members`: составной первичный ключ `(chat_id, user_id)`, внешние ключи, ссылающиеся на таблицы `chats` и `users`. Первичный ключ предотвращает дублирование записей об участии пользователя в чате.
- `messages`: первичный ключ типа UUID. Составной внешний ключ `(chat_id, sender_id) -> chat_members(chat_id, user_id)` гарантирует, что сообщение может быть сохранено только от имени пользователя, который является участником данного чата.
- `sessions`: первичный ключ типа UUID, внешний ключ пользователя, уникальный SHA-256-хеш токена, время создания и истечения, а также необязательное время отзыва. Сам Bearer-токен в базе не хранится.
Проверка строковых данных осуществляется как на уровне HTTP-валидации, так и с помощью базовых ограничений SQL. Проверка символов Unicode (включая пробельные символы) выполняется на уровне приложения, поскольку механизмы регулярных выражений в PostgreSQL и классификация символов Unicode в Java не полностью идентичны.
## Индексы и структура запросов
- `chat_members(user_id, chat_id)` — индекс для поиска чатов, в которых состоит пользователь.
- `chats(created_at, id)` — индекс для обеспечения детерминированного порядка сортировки чатов.
- `messages(chat_id, created_at, id)` — индекс, поддерживающий пагинацию на основе курсоров (keyset pagination) без использования смещения (offset) или полной сортировки данных в оперативной памяти.
- `messages(sender_id, created_at)` — индекс для диагностики действий конкретного пользователя и выполнения аудиторских запросов в будущем.
- `sessions(expires_at) WHERE revoked_at IS NULL` — частичный индекс для поиска и очистки истёкших активных сессий.
Курсоры для сообщений и чатов используют тот же кортеж `(created_at, id)`, что и соответствующее предложение `ORDER BY` в запросах.
Запрос страницы истории имеет вид `WHERE chat_id = ? AND (created_at, id) > (?, ?)
ORDER BY created_at, id LIMIT ?`. Все значения передаются параметрами `JdbcTemplate`, поэтому данные
пользователя не становятся частью SQL. Составной индекс `messages_chat_created_id_idx` сначала сужает
диапазон по `chat_id`, затем начинает чтение непосредственно после курсора. Проверка
`make explain-history` создаёт 10 000 сообщений внутри откатываемой транзакции и выполняет
`EXPLAIN (ANALYZE, BUFFERS)`. Проверка завершается ошибкой при отсутствии Index Scan по этому индексу
или при появлении `Seq Scan on messages`.
## Redis: роль, TTL и отказ
Redis используется как cache-aside-кэш объектов пользователей на горячем пути Bearer-аутентификации.
Он не является источником истины для сессий: перед использованием кэша API всегда параметризованным
запросом проверяет в PostgreSQL, что токен существует, не отозван и `expires_at > CURRENT_TIMESTAMP`.
Поэтому устаревшая запись Redis не может восстановить отозванную или истёкшую сессию.
Ключи имеют вид `messenger:user:<uuid>` и TTL, задаваемый `USER_CACHE_TTL_SECONDS` (по умолчанию
300 секунд). При cache miss пользователь читается из PostgreSQL и помещается в Redis. Изменения и
удаление пользователей API пока не поддерживает; при появлении таких операций соответствующий ключ
должен удаляться после успешного commit. Повреждённая запись удаляется. При таймауте или недоступности
Redis API пропускает кэш и читает PostgreSQL. Redis имеет ограниченный Lettuce pool и короткие таймауты.
В Compose также включён AOF `appendfsync everysec` и именованный volume `redis-data`, хотя потеря кэша
не влияет на корректность.
Сессии истекают по абсолютному `expires_at` в PostgreSQL. Logout атомарно заполняет `revoked_at`.
Если PostgreSQL недоступен, защищённый запрос получает ограниченный ответ `503 unavailable`; кэш не
используется для обхода проверки токена. Запрос без Bearer-токена остаётся `401` и никогда не получает
доверенную личность из `X-User-Id`.
## Пулы и таймауты
HikariCP ограничен `DATABASE_POOL_SIZE` (по умолчанию 10), имеет конечные connection/validation
timeouts, а JDBC-запросы и транзакции — таймаут 5 секунд. Lettuce pool ограничен 8 активными
соединениями, ожидание соединения и сетевые операции Redis также имеют конечные таймауты.
## Границы транзакций
Создание чата выполняется в рамках одной транзакции базы данных. Сначала вставляется запись в таблицу `chats`, затем — записи для каждого участника в таблицу `chat_members`. Если возникает дубликат или отсутствует запись об участнике, вся операция откатывается (rollback); таким образом, чат никогда не будет зафиксирован в базе данных (commit) без полного набора участников.
`make test-operational` устанавливает временный тестовый trigger, который намеренно отклоняет вставку
одного участника после вставки чата, и проверяет отсутствие строки чата после ошибки. Trigger всегда
удаляется в `finally`.
Создание пользователя или сообщения выполняется как атомарная транзакция, состоящая из одного SQL-оператора. Уникальность имени пользователя (username) обеспечивается на уровне базы данных с помощью ограничения `users_username_uk`; в случае одновременной попытки создания дубликата API возвращает ответ `409 Conflict`.
Предварительная проверка username нужна только для быстрого понятного ответа. Корректность при гонке
обеспечивает именно уникальное ограничение PostgreSQL и обработка `DuplicateKeyException`.
`make test-operational` отправляет 12 одновременных регистраций: ровно одна должна получить `201`,
остальные — `409`.
Создание сессии сохраняет хеш токена и срок действия одним SQL-оператором. Bearer-аутентификация выбирает только неотозванную сессию, у которой `expires_at > CURRENT_TIMESTAMP`. Logout атомарно устанавливает `revoked_at`. Сессии находятся в PostgreSQL и переживают рестарт API и PostgreSQL при сохранении именованного volume.
Операции получения списка и поиска выполняются в режиме изоляции `READ COMMITTED`. Контракт API не предусматривает использование единого снимка данных (snapshot) для нескольких HTTP-запросов в рамках постраничного вывода (пагинации).
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env python3
"""Run the 10k-row message history plan probe inside a rolled-back transaction."""
from pathlib import Path
import subprocess
root = Path(__file__).resolve().parents[1]
sql = (root / 'scripts' / 'explain_message_history.sql').read_text(encoding='utf-8')
result = subprocess.run(
[
'docker', 'compose', '--env-file', '.env', 'exec', '-T', 'postgres',
'sh', '-lc', 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
],
cwd=root,
input=sql,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
check=False,
)
print(result.stdout, end='')
if result.returncode != 0:
raise SystemExit(result.returncode)
plan = result.stdout[result.stdout.find('QUERY PLAN'):]
if 'Index Scan' not in plan or 'messages_chat_created_id_idx' not in plan:
raise SystemExit('FAIL: expected messages_chat_created_id_idx index scan')
if 'Seq Scan on messages' in plan:
raise SystemExit('FAIL: message history used a sequential scan')
print('PASS: 10,000-row keyset page used messages_chat_created_id_idx without a full scan.')
+47
View File
@@ -0,0 +1,47 @@
BEGIN;
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (
'70000000-0000-4000-8000-000000000001',
'explain_probe',
'EXPLAIN probe',
'$argon2id$v=19$m=16384,t=2,p=1$probe$probe',
'2026-01-01T00:00:00Z'
);
INSERT INTO chats (id, title, created_at)
VALUES (
'70000000-0000-4000-8000-000000000002',
'EXPLAIN history probe',
'2026-01-01T00:00:00Z'
);
INSERT INTO chat_members (chat_id, user_id)
VALUES (
'70000000-0000-4000-8000-000000000002',
'70000000-0000-4000-8000-000000000001'
);
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT
('70000000-0000-4000-8000-' || lpad(series::text, 12, '0'))::uuid,
'70000000-0000-4000-8000-000000000002'::uuid,
'70000000-0000-4000-8000-000000000001'::uuid,
'history probe ' || series,
'2026-01-01T00:00:00Z'::timestamptz + series * interval '1 millisecond'
FROM generate_series(1, 10000) AS series;
ANALYZE messages;
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = '70000000-0000-4000-8000-000000000002'::uuid
AND (created_at, id) > (
'2026-01-01T00:00:05Z'::timestamptz,
'70000000-0000-4000-8000-000000005000'::uuid
)
ORDER BY created_at, id
LIMIT 100;
ROLLBACK;
Executable → Regular
View File
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
# Restart every stateful component used by the application without deleting the
# named PostgreSQL/Redis volumes. The persistence test waits for readiness afterwards.
docker compose --env-file .env restart postgres redis api
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'mtusi-messenger'
@@ -0,0 +1,13 @@
package com.example.mtusi_messenger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MtusiMessengerApplication {
public static void main(String[] args) {
SpringApplication.run(MtusiMessengerApplication.class, args);
}
}
@@ -0,0 +1,83 @@
package com.example.mtusi_messenger.cache;
import com.example.mtusi_messenger.model.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
@Component
public class UserCache {
private static final Logger log = LoggerFactory.getLogger(UserCache.class);
private static final String KEY_PREFIX = "messenger:user:";
private final StringRedisTemplate redis;
private final ObjectMapper mapper;
private final Duration ttl;
public UserCache(
StringRedisTemplate redis,
ObjectMapper mapper,
@Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds
) {
if (ttlSeconds <= 0) {
throw new IllegalArgumentException("User cache TTL must be positive");
}
this.redis = redis;
this.mapper = mapper;
this.ttl = Duration.ofSeconds(ttlSeconds);
}
public Optional<User> find(UUID userId) {
try {
String value = redis.opsForValue().get(key(userId));
if (value == null) {
return Optional.empty();
}
User cachedUser = mapper.readValue(value, User.class);
if (cachedUser == null) {
log.warn("Ignoring null Redis user cache entry for {}", userId);
evict(userId);
return Optional.empty();
}
return Optional.of(cachedUser);
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; using PostgreSQL fallback");
return Optional.empty();
} catch (JsonProcessingException e) {
log.warn("Ignoring malformed Redis user cache entry for {}", userId);
evict(userId);
return Optional.empty();
}
}
public void put(User user) {
try {
redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl);
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; user was not cached");
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize user cache entry", e);
}
}
public void evict(UUID userId) {
try {
redis.delete(key(userId));
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; cache eviction was skipped");
}
}
private String key(UUID userId) {
return KEY_PREFIX + userId;
}
}
@@ -0,0 +1,28 @@
package com.example.mtusi_messenger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
import tools.jackson.databind.cfg.CoercionAction;
import tools.jackson.databind.cfg.CoercionInputShape;
import tools.jackson.databind.type.LogicalType;
@Configuration
public class JacksonConfig {
@Bean
JsonMapperBuilderCustomizer strictStringTypes() {
return builder -> builder.withCoercionConfig(
LogicalType.Textual,
config -> {
config.setCoercion(
CoercionInputShape.Integer, CoercionAction.Fail);
config.setCoercion(
CoercionInputShape.Float, CoercionAction.Fail);
config.setCoercion(
CoercionInputShape.Boolean, CoercionAction.Fail);
}
);
}
}
@@ -0,0 +1,21 @@
package com.example.mtusi_messenger.config;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.context.annotation.Configuration;
@SecurityScheme(
name = "basicAuth",
type = SecuritySchemeType.HTTP,
scheme = "basic"
)
@SecurityScheme(
name = "bearerAuth",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "opaque session token"
)
@Configuration
public class OpenApiConfig {
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordConfig {
@Bean
PasswordEncoder passwordEncoder() {
return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
}
}
@@ -0,0 +1,90 @@
package com.example.mtusi_messenger.config;
import com.example.mtusi_messenger.security.ApiAuthenticationFilter;
import com.example.mtusi_messenger.security.DatabaseAuthenticationProvider;
import com.example.mtusi_messenger.security.RestAuthenticationEntryPoint;
import com.example.mtusi_messenger.service.AuthenticationService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
@Configuration
public class SecurityConfig {
@Bean
AuthenticationManager authenticationManager(DatabaseAuthenticationProvider provider) {
return new ProviderManager(provider);
}
@Bean
RestAuthenticationEntryPoint basicAuthenticationEntryPoint(ObjectMapper mapper) {
return new RestAuthenticationEntryPoint(
mapper,
"Basic realm=\"messenger\", charset=\"UTF-8\"");
}
@Bean
RestAuthenticationEntryPoint bearerAuthenticationEntryPoint(ObjectMapper mapper) {
return new RestAuthenticationEntryPoint(mapper, "Bearer realm=\"messenger\"");
}
@Bean
ApiAuthenticationFilter apiAuthenticationFilter(
AuthenticationManager authenticationManager,
AuthenticationService authenticationService,
@Qualifier("basicAuthenticationEntryPoint") RestAuthenticationEntryPoint basicAuthenticationEntryPoint,
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
) {
return new ApiAuthenticationFilter(
authenticationManager,
authenticationService,
basicAuthenticationEntryPoint,
bearerAuthenticationEntryPoint);
}
@Bean
FilterRegistrationBean<ApiAuthenticationFilter> disableServletFilterRegistration(
ApiAuthenticationFilter filter
) {
var registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
@Bean
SecurityFilterChain securityFilterChain(
HttpSecurity http,
ApiAuthenticationFilter apiAuthenticationFilter,
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
) throws Exception {
http
.csrf(csrf -> csrf.disable())
.formLogin(form -> form.disable())
.httpBasic(basic -> basic.disable())
.logout(logout -> logout.disable())
.requestCache(cache -> cache.disable())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(errors -> errors
.authenticationEntryPoint(bearerAuthenticationEntryPoint))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(HttpMethod.GET, "/health/**").permitAll()
.requestMatchers(
"/swagger-ui.html",
"/swagger-ui/**",
"/v3/api-docs/**"
).permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll()
.anyRequest().authenticated())
.addFilterBefore(apiAuthenticationFilter, AnonymousAuthenticationFilter.class);
return http.build();
}
}
@@ -0,0 +1,19 @@
package com.example.mtusi_messenger.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfig {
@Bean
ObjectMapper objectMapper() {
return JsonMapper.builder().findAndAddModules()
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
.build();
}
}
@@ -0,0 +1,83 @@
package com.example.mtusi_messenger.controller;
import com.example.mtusi_messenger.exception.ApiExceptions;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import com.example.mtusi_messenger.dto.*;
import com.example.mtusi_messenger.model.Chat;
import com.example.mtusi_messenger.service.ChatService;
import com.example.mtusi_messenger.security.SessionPrincipal;
import java.util.List;
import java.util.UUID;
import static com.example.mtusi_messenger.service.UuidValidator.parse;
@RestController
@RequestMapping("/api/v1/chats")
@SecurityRequirement(name = "bearerAuth")
@RequiredArgsConstructor
public class ChatController {
private final ChatService chats;
@PostMapping
public ResponseEntity<ChatResponse> create(@AuthenticationPrincipal SessionPrincipal principal,
@Valid @RequestBody CreateChatRequest body
) {
UUID userId = principal.user().id();
Chat c = chats.create(body, userId);
return ResponseEntity.status(HttpStatus.CREATED).body(ChatResponse.from(c));
}
@GetMapping
public ChatPageResponse list(@AuthenticationPrincipal SessionPrincipal principal,
@RequestParam(required = false) String limit,
@RequestParam(required = false) String cursor
) {
UUID userId = principal.user().id();
int parsedLimit = validateLimit(limit);
validateCursorPresence(cursor);
List<Chat> page = chats.page(userId, parsedLimit, cursor);
boolean hasNext = page.size() > parsedLimit;
if (hasNext) page = page.subList(0, parsedLimit);
return new ChatPageResponse(page.stream().map(ChatResponse::from).toList(), page.isEmpty() ? null :
chats.nextCursor(userId, page.get(page.size() - 1), hasNext));
}
@GetMapping("/{chatId}")
public ChatResponse get(@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String chatId
) {
UUID userId = principal.user().id();
return ChatResponse.from(chats.getAccessible(parse(chatId), userId));
}
private static int validateLimit(String limit) {
if (limit == null) {
return 50;
}
if (!limit.matches("[0-9]+")) {
throw ApiExceptions.invalid("Invalid limit");
}
try {
int value = Integer.parseInt(limit);
if (value < 1 || value > 100) {
throw ApiExceptions.invalid("Invalid limit");
}
return value;
} catch (NumberFormatException ex) {
throw ApiExceptions.invalid("Invalid limit");
}
}
private static void validateCursorPresence(String c) {
if (c != null && c.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
}
}
@@ -0,0 +1,33 @@
package com.example.mtusi_messenger.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.mtusi_messenger.dto.HealthResponse;
import com.example.mtusi_messenger.exception.ApiExceptions;
@RestController
public class HealthController {
private final JdbcTemplate jdbc;
public HealthController(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@GetMapping("/health/live")
public ResponseEntity<HealthResponse> live() {
return ResponseEntity.ok(new HealthResponse("ok"));
}
@GetMapping("/health/ready")
public ResponseEntity<HealthResponse> ready() {
try {
jdbc.queryForObject("SELECT 1", Integer.class);
return ResponseEntity.ok(new HealthResponse("ok"));
} catch (DataAccessException e) {
throw ApiExceptions.unavailable("Database is unavailable");
}
}
}
@@ -0,0 +1,74 @@
package com.example.mtusi_messenger.controller;
import com.example.mtusi_messenger.exception.ApiExceptions;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import com.example.mtusi_messenger.dto.*;
import com.example.mtusi_messenger.model.Message;
import com.example.mtusi_messenger.service.MessageService;
import com.example.mtusi_messenger.security.SessionPrincipal;
import java.util.List;
import java.util.UUID;
import static com.example.mtusi_messenger.service.UuidValidator.parse;
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/chats/{chatId}/messages")
@SecurityRequirement(name = "bearerAuth")
public class MessageController {
private final MessageService messages;
@PostMapping
public ResponseEntity<MessageResponse> create(@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String chatId,
@Valid @RequestBody CreateMessageRequest body
) {
UUID userId = principal.user().id();
UUID parsedChatId = parse(chatId);
Message m = messages.create(parsedChatId, userId, body);
return ResponseEntity.status(HttpStatus.CREATED).body(MessageResponse.from(m));
}
@GetMapping
public MessagePageResponse list(@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String chatId,
@RequestParam(required = false) String limit,
@RequestParam(required=false) String cursor
) {
UUID userId = principal.user().id();
UUID parsedChatId = parse(chatId);
int parsedLimit = validateLimit(limit);
if (cursor != null && cursor.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
List<Message> page = messages.page(parsedChatId, userId, parsedLimit, cursor);
boolean hasNext = page.size() > parsedLimit; if (hasNext) page = page.subList(0, parsedLimit);
return new MessagePageResponse(page.stream().map(MessageResponse::from).toList(),
page.isEmpty() ? null : messages.nextCursor(parsedChatId, page.get(page.size()-1), hasNext));
}
private static int validateLimit(String limit) {
if (limit == null) {
return 50;
}
if (!limit.matches("[0-9]+")) {
throw ApiExceptions.invalid("Invalid limit");
}
try {
int value = Integer.parseInt(limit);
if (value < 1 || value > 100) {
throw ApiExceptions.invalid("Invalid limit");
}
return value;
} catch (NumberFormatException ex) {
throw ApiExceptions.invalid("Invalid limit");
}
}
}
@@ -0,0 +1,41 @@
package com.example.mtusi_messenger.controller;
import com.example.mtusi_messenger.dto.SessionResponse;
import com.example.mtusi_messenger.dto.UserResponse;
import com.example.mtusi_messenger.service.AuthenticationService;
import com.example.mtusi_messenger.model.User;
import com.example.mtusi_messenger.security.SessionPrincipal;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/auth/sessions")
@RequiredArgsConstructor
public class SessionController {
private final AuthenticationService authentication;
@PostMapping
@SecurityRequirement(name = "basicAuth")
public ResponseEntity<SessionResponse> create(@AuthenticationPrincipal User user) {
var issued = authentication.issueSession(user);
return ResponseEntity.status(HttpStatus.CREATED).body(new SessionResponse(
issued.token(),
"Bearer",
issued.expiresAt(),
UserResponse.from(issued.user())));
}
@DeleteMapping("/current")
@SecurityRequirement(name = "bearerAuth")
public ResponseEntity<Void> revoke(@AuthenticationPrincipal SessionPrincipal principal) {
authentication.revoke(principal);
return ResponseEntity.noContent().build();
}
}
@@ -0,0 +1,32 @@
package com.example.mtusi_messenger.controller;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import com.example.mtusi_messenger.dto.*;
import com.example.mtusi_messenger.service.UserService;
import com.example.mtusi_messenger.security.SessionPrincipal;
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {
private final UserService users;
@PostMapping
public ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
var user = users.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(UserResponse.from(user));
}
@GetMapping("/me")
@SecurityRequirement(name = "bearerAuth")
public UserResponse me(@AuthenticationPrincipal SessionPrincipal principal) {
return UserResponse.from(principal.user());
}
}
@@ -0,0 +1,8 @@
package com.example.mtusi_messenger.dto;
import java.util.List;
public record ChatPageResponse(
List<ChatResponse> items,
String next_cursor
) {}
@@ -0,0 +1,18 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.model.Chat;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public record ChatResponse(UUID id,
String title,
List<UUID> member_ids,
Instant created_at) {
public static ChatResponse from(Chat c) {
return new ChatResponse(
c.id(),
c.title(),
c.memberIds(),
c.createdAt()); }
}
@@ -0,0 +1,19 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.web.NotUnicodeBlank;
import com.example.mtusi_messenger.web.UnicodeSize;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import java.util.List;
import java.util.UUID;
public record CreateChatRequest(
@NotUnicodeBlank
@UnicodeSize(min = 1, max = 100)
String title,
@NotEmpty
@Size(min = 1, max = 100)
List<UUID> member_ids
) {}
@@ -0,0 +1,8 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.web.NotUnicodeBlank;
import com.example.mtusi_messenger.web.UnicodeSize;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public record CreateMessageRequest( @NotUnicodeBlank @UnicodeSize(min = 1, max = 4000) String text) {}
@@ -0,0 +1,20 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.web.NotUnicodeBlank;
import com.example.mtusi_messenger.web.UnicodeSize;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
public record CreateUserRequest(
@NotBlank
@Pattern(regexp = "[a-z0-9_]{3,32}")
String username,
@NotUnicodeBlank
@UnicodeSize(min = 1, max = 100)
String display_name,
@NotUnicodeBlank
@UnicodeSize(min = 12, max = 128)
String password
) {}
@@ -0,0 +1,8 @@
package com.example.mtusi_messenger.dto;
public record ErrorResponse(ErrorBody error) {
public record ErrorBody(String code,
String message,
String request_id)
{}
}
@@ -0,0 +1,3 @@
package com.example.mtusi_messenger.dto;
public record HealthResponse(String status) {}
@@ -0,0 +1,8 @@
package com.example.mtusi_messenger.dto;
import java.util.List;
public record MessagePageResponse(
List<MessageResponse> items,
String next_cursor
) {}
@@ -0,0 +1,19 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.model.Message;
import java.time.Instant;
import java.util.UUID;
public record MessageResponse(UUID id,
UUID chat_id,
UUID sender_id,
String text,
Instant created_at) {
public static MessageResponse from(Message m) {
return new MessageResponse(m.id(),
m.chatId(),
m.senderId(),
m.text(),
m.createdAt());
}
}
@@ -0,0 +1,10 @@
package com.example.mtusi_messenger.dto;
import java.time.Instant;
public record SessionResponse(
String token,
String token_type,
Instant expires_at,
UserResponse user
) {}
@@ -0,0 +1,18 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.model.User;
import java.time.Instant;
import java.util.UUID;
public record UserResponse(UUID id,
String username,
String display_name,
Instant created_at) {
public static UserResponse from(User u) {
return new UserResponse(
u.id(),
u.username(),
u.displayName(),
u.createdAt());
}
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.exception;
import org.springframework.http.HttpStatus;
public class ApiException extends RuntimeException {
private final String code; private final HttpStatus status; private final String authenticate;
public ApiException(String code, HttpStatus status, String message) { this(code, status, message, null); }
public ApiException(String code, HttpStatus status, String message, String authenticate) {
super(message); this.code = code; this.status = status; this.authenticate = authenticate;
}
public String code() { return code; }
public HttpStatus status() { return status; }
public String authenticate() { return authenticate; }
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.exception;
import org.springframework.http.HttpStatus;
public final class ApiExceptions {
private ApiExceptions() {}
public static ApiException invalid(String m) { return new ApiException("invalid_request", HttpStatus.BAD_REQUEST, m); }
public static ApiException unauthorized(String m) { return unauthorizedBearer(m); }
public static ApiException unauthorizedBasic(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Basic realm=\"messenger\", charset=\"UTF-8\""); }
public static ApiException unauthorizedBearer(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Bearer realm=\"messenger\""); }
public static ApiException notFound(String m) { return new ApiException("not_found", HttpStatus.NOT_FOUND, m); }
public static ApiException conflict(String m) { return new ApiException("conflict", HttpStatus.CONFLICT, m); }
public static ApiException unavailable(String m) { return new ApiException("unavailable", HttpStatus.SERVICE_UNAVAILABLE, m); }
}
@@ -0,0 +1,11 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public record Chat(UUID id, String title, List<UUID> memberIds, Instant createdAt) {
public Chat {
memberIds = List.copyOf(memberIds);
}
}
@@ -0,0 +1,6 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.UUID;
public record Message(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt) {}
@@ -0,0 +1,35 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.UUID;
public record MessageKey(Instant createdAt, UUID id)
implements Comparable<MessageKey> {
private static int compareUuidV7(UUID a, UUID b) {
int result = Long.compareUnsigned(
a.getMostSignificantBits(),
b.getMostSignificantBits()
);
if (result != 0) {
return result;
}
return Long.compareUnsigned(
a.getLeastSignificantBits(),
b.getLeastSignificantBits()
);
}
@Override
public int compareTo(MessageKey other) {
int result = createdAt.compareTo(other.createdAt);
if (result != 0) {
return result;
}
return compareUuidV7(id, other.id);
}
}
@@ -0,0 +1,15 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.UUID;
public record Session(UUID id, UUID userId, byte[] tokenHash, Instant createdAt, Instant expiresAt) {
public Session {
tokenHash = tokenHash.clone();
}
@Override
public byte[] tokenHash() {
return tokenHash.clone();
}
}
@@ -0,0 +1,6 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.UUID;
public record User(UUID id, String username, String displayName, Instant createdAt) {}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Chat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface ChatRepository {
Chat save(Chat chat);
Optional<Chat> findById(UUID id);
boolean isMember(UUID chatId, UUID userId);
List<Chat> findAllForUser(UUID userId);
List<Chat> findPageForUser(UUID userId, UUID afterId, java.time.Instant afterCreatedAt, int limitPlusOne);
}
@@ -0,0 +1,11 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Message;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public interface MessageRepository {
Message save(Message message);
List<Message> findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne);
}
@@ -0,0 +1,106 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Chat;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public class PostgresChatRepository implements ChatRepository {
private final JdbcTemplate jdbc;
public PostgresChatRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
@Transactional(timeout = 5)
public Chat save(Chat chat) {
jdbc.update("""
INSERT INTO chats (id, title, created_at)
VALUES (?, ?, ?)
""", chat.id(), chat.title(), Timestamp.from(chat.createdAt()));
for (UUID memberId : chat.memberIds()) {
jdbc.update("""
INSERT INTO chat_members (chat_id, user_id)
VALUES (?, ?)
""", chat.id(), memberId);
}
return chat;
}
@Override
public Optional<Chat> findById(UUID id) {
return jdbc.query("""
SELECT id, title, created_at
FROM chats
WHERE id = ?
""", (rs, rowNum) -> new ChatRow(
rs.getObject("id", UUID.class),
rs.getString("title"),
rs.getTimestamp("created_at").toInstant()), id)
.stream().findFirst()
.map(this::toChat);
}
@Override
public boolean isMember(UUID chatId, UUID userId) {
return Boolean.TRUE.equals(jdbc.queryForObject("""
SELECT EXISTS (
SELECT 1 FROM chat_members
WHERE chat_id = ? AND user_id = ?
)
""", Boolean.class, chatId, userId));
}
@Override
public List<Chat> findAllForUser(UUID userId) {
return findPageForUser(userId, null, null, Integer.MAX_VALUE);
}
@Override
public List<Chat> findPageForUser(UUID userId, UUID afterId, Instant afterCreatedAt, int limitPlusOne) {
StringBuilder sql = new StringBuilder("""
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE cm.user_id = ?
""");
List<Object> parameters = new ArrayList<>();
parameters.add(userId);
if (afterCreatedAt != null) {
sql.append(" AND (c.created_at, c.id) > (?, ?) ");
parameters.add(Timestamp.from(afterCreatedAt));
parameters.add(afterId);
}
sql.append(" ORDER BY c.created_at, c.id LIMIT ? ");
parameters.add(limitPlusOne);
return jdbc.query(sql.toString(), (rs, rowNum) -> new ChatRow(
rs.getObject("id", UUID.class),
rs.getString("title"),
rs.getTimestamp("created_at").toInstant()), parameters.toArray())
.stream().map(this::toChat).toList();
}
private Chat toChat(ChatRow row) {
List<UUID> members = jdbc.queryForList("""
SELECT user_id
FROM chat_members
WHERE chat_id = ?
ORDER BY joined_at, user_id
""", UUID.class, row.id());
return new Chat(row.id(), row.title(), members, row.createdAt());
}
private record ChatRow(UUID id, String title, Instant createdAt) {}
}
@@ -0,0 +1,56 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Message;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Repository
public class PostgresMessageRepository implements MessageRepository {
private final JdbcTemplate jdbc;
public PostgresMessageRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
public Message save(Message message) {
jdbc.update("""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES (?, ?, ?, ?, ?)
""", message.id(), message.chatId(), message.senderId(), message.text(),
Timestamp.from(message.createdAt()));
return message;
}
@Override
public List<Message> findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne) {
StringBuilder sql = new StringBuilder("""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = ?
""");
List<Object> parameters = new ArrayList<>();
parameters.add(chatId);
if (afterCreatedAt != null) {
sql.append(" AND (created_at, id) > (?, ?) ");
parameters.add(Timestamp.from(afterCreatedAt));
parameters.add(afterId);
}
sql.append(" ORDER BY created_at, id LIMIT ? ");
parameters.add(limitPlusOne);
return jdbc.query(sql.toString(), (rs, rowNum) -> new Message(
rs.getObject("id", UUID.class),
rs.getObject("chat_id", UUID.class),
rs.getObject("sender_id", UUID.class),
rs.getString("text"),
rs.getTimestamp("created_at").toInstant()), parameters.toArray());
}
}
@@ -0,0 +1,51 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Session;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.Optional;
import java.util.UUID;
@Repository
public class PostgresSessionRepository implements SessionRepository {
private final JdbcTemplate jdbc;
public PostgresSessionRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
public Session save(Session session) {
jdbc.update("""
INSERT INTO sessions (id, user_id, token_hash, created_at, expires_at)
VALUES (?, ?, ?, ?, ?)
""", session.id(), session.userId(), session.tokenHash(),
Timestamp.from(session.createdAt()), Timestamp.from(session.expiresAt()));
return session;
}
@Override
public Optional<UUID> findActiveUserId(byte[] tokenHash) {
return jdbc.query("""
SELECT user_id
FROM sessions
WHERE token_hash = ?
AND revoked_at IS NULL
AND expires_at > CURRENT_TIMESTAMP
""", (rs, rowNum) -> rs.getObject("user_id", UUID.class), tokenHash)
.stream().findFirst();
}
@Override
public boolean revoke(byte[] tokenHash) {
return jdbc.update("""
UPDATE sessions
SET revoked_at = CURRENT_TIMESTAMP
WHERE token_hash = ?
AND revoked_at IS NULL
AND expires_at > CURRENT_TIMESTAMP
""", tokenHash) == 1;
}
}
@@ -0,0 +1,72 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.Optional;
import java.util.UUID;
@Repository
public class PostgresUserRepository implements UserRepository {
private final JdbcTemplate jdbc;
public PostgresUserRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
public User save(User user, String passwordHash) {
jdbc.update("""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (?, ?, ?, ?, ?)
""", user.id(), user.username(), user.displayName(), passwordHash,
Timestamp.from(user.createdAt()));
return user;
}
@Override
public Optional<User> findById(UUID id) {
return jdbc.query("""
SELECT id, username, display_name, created_at
FROM users
WHERE id = ?
""", (rs, rowNum) -> new User(
rs.getObject("id", UUID.class),
rs.getString("username"),
rs.getString("display_name"),
rs.getTimestamp("created_at").toInstant()), id)
.stream().findFirst();
}
@Override
public Optional<User> findByUsername(String username) {
return jdbc.query("""
SELECT id, username, display_name, created_at
FROM users
WHERE username = ?
""", (rs, rowNum) -> new User(
rs.getObject("id", UUID.class),
rs.getString("username"),
rs.getString("display_name"),
rs.getTimestamp("created_at").toInstant()), username)
.stream().findFirst();
}
@Override
public Optional<UserCredentials> findCredentialsByUsername(String username) {
return jdbc.query("""
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = ?
""", (rs, rowNum) -> new UserCredentials(
new User(
rs.getObject("id", UUID.class),
rs.getString("username"),
rs.getString("display_name"),
rs.getTimestamp("created_at").toInstant()),
rs.getString("password_hash")), username)
.stream().findFirst();
}
}
@@ -0,0 +1,12 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Session;
import java.util.Optional;
import java.util.UUID;
public interface SessionRepository {
Session save(Session session);
Optional<UUID> findActiveUserId(byte[] tokenHash);
boolean revoke(byte[] tokenHash);
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.User;
import java.util.Optional;
import java.util.UUID;
public interface UserRepository {
User save(User user, String passwordHash);
Optional<User> findById(UUID id);
Optional<User> findByUsername(String username);
Optional<UserCredentials> findCredentialsByUsername(String username);
record UserCredentials(User user, String passwordHash) {}
}
@@ -0,0 +1,130 @@
package com.example.mtusi_messenger.security;
import com.example.mtusi_messenger.service.AuthenticationService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Enumeration;
import java.util.List;
public class ApiAuthenticationFilter extends OncePerRequestFilter {
private static final String AUTHORIZATION = "Authorization";
private static final String SESSION_PATH = "/api/v1/auth/sessions";
private final AuthenticationManager authenticationManager;
private final AuthenticationService sessions;
private final RestAuthenticationEntryPoint basicEntryPoint;
private final RestAuthenticationEntryPoint bearerEntryPoint;
public ApiAuthenticationFilter(
AuthenticationManager authenticationManager,
AuthenticationService sessions,
RestAuthenticationEntryPoint basicEntryPoint,
RestAuthenticationEntryPoint bearerEntryPoint
) {
this.authenticationManager = authenticationManager;
this.sessions = sessions;
this.basicEntryPoint = basicEntryPoint;
this.bearerEntryPoint = bearerEntryPoint;
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
boolean basicLogin = HttpMethod.POST.matches(request.getMethod())
&& SESSION_PATH.equals(request.getRequestURI());
if (isPublicRequest(request) && !basicLogin) {
filterChain.doFilter(request, response);
return;
}
try {
Authentication authentication = basicLogin
? authenticateBasic(request)
: authenticateBearer(request);
var context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
filterChain.doFilter(request, response);
} catch (AuthenticationException e) {
SecurityContextHolder.clearContext();
(basicLogin ? basicEntryPoint : bearerEntryPoint)
.commence(request, response, e);
} finally {
SecurityContextHolder.clearContext();
}
}
private Authentication authenticateBasic(HttpServletRequest request) {
String header = singleAuthorizationHeader(request);
if (!header.startsWith("Basic ") || header.length() == 6) {
throw new BadCredentialsException("Invalid Basic credentials");
}
try {
byte[] decoded = Base64.getDecoder().decode(header.substring(6));
String credentials = new String(decoded, StandardCharsets.UTF_8);
int separator = credentials.indexOf(':');
if (separator <= 0) {
throw new BadCredentialsException("Invalid Basic credentials");
}
return authenticationManager.authenticate(
UsernamePasswordAuthenticationToken.unauthenticated(
credentials.substring(0, separator),
credentials.substring(separator + 1)));
} catch (IllegalArgumentException e) {
throw new BadCredentialsException("Invalid Basic credentials", e);
}
}
private Authentication authenticateBearer(HttpServletRequest request) {
String header = singleAuthorizationHeader(request);
if (!header.startsWith("Bearer ") || header.length() == 7) {
throw new BadCredentialsException("Invalid Bearer token");
}
String token = header.substring(7);
if (!token.matches("[A-Za-z0-9_-]{43}")) {
throw new BadCredentialsException("Invalid Bearer token");
}
SessionPrincipal principal = sessions.authenticateBearer(token);
return UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of());
}
private String singleAuthorizationHeader(HttpServletRequest request) {
Enumeration<String> values = request.getHeaders(AUTHORIZATION);
if (values == null || !values.hasMoreElements()) {
throw new BadCredentialsException("Authentication required");
}
String value = values.nextElement();
if (values.hasMoreElements()) {
throw new BadCredentialsException("Multiple Authorization headers");
}
return value;
}
private boolean isPublicRequest(HttpServletRequest request) {
String path = request.getRequestURI();
return path.startsWith("/health/")
|| path.equals("/swagger-ui.html")
|| path.startsWith("/swagger-ui/")
|| path.equals("/v3/api-docs")
|| path.startsWith("/v3/api-docs/")
|| (HttpMethod.POST.matches(request.getMethod())
&& "/api/v1/users".equals(path));
}
}
@@ -0,0 +1,63 @@
package com.example.mtusi_messenger.security;
import com.example.mtusi_messenger.repository.UserRepository;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.dao.DataAccessException;
import java.util.List;
@Component
public class DatabaseAuthenticationProvider implements AuthenticationProvider {
private final UserRepository users;
private final PasswordEncoder passwordEncoder;
private final String dummyPasswordHash;
public DatabaseAuthenticationProvider(UserRepository users, PasswordEncoder passwordEncoder) {
this.users = users;
this.passwordEncoder = passwordEncoder;
this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing");
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = String.valueOf(authentication.getCredentials());
final java.util.Optional<UserRepository.UserCredentials> stored;
try {
stored = users.findCredentialsByUsername(username);
} catch (DataAccessException e) {
throw new AuthenticationServiceException("Authentication database is unavailable", e);
}
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
.filter(hash -> hash.startsWith("$argon2"))
.orElse(dummyPasswordHash);
boolean matches;
try {
matches = passwordEncoder.matches(password, passwordHash);
} catch (IllegalArgumentException e) {
matches = false;
}
if (stored.isEmpty() || !matches) {
throw new BadCredentialsException("Invalid credentials");
}
return UsernamePasswordAuthenticationToken.authenticated(
stored.get().user(),
null,
List.of());
}
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
@@ -0,0 +1,46 @@
package com.example.mtusi_messenger.security;
import com.example.mtusi_messenger.dto.ErrorResponse;
import com.example.mtusi_messenger.web.RequestIdFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.web.AuthenticationEntryPoint;
import java.io.IOException;
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final ObjectMapper mapper;
private final String challenge;
public RestAuthenticationEntryPoint(ObjectMapper mapper, String challenge) {
this.mapper = mapper;
this.challenge = challenge;
}
@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception
) throws IOException {
String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE);
boolean unavailable = exception instanceof AuthenticationServiceException;
response.setStatus(unavailable
? HttpServletResponse.SC_SERVICE_UNAVAILABLE
: HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
if (!unavailable) {
response.setHeader("WWW-Authenticate", challenge);
}
mapper.writeValue(response.getOutputStream(), new ErrorResponse(
new ErrorResponse.ErrorBody(
unavailable ? "unavailable" : "unauthorized",
unavailable ? "Authentication service temporarily unavailable" : "Authentication required",
requestId)));
}
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.security;
import com.example.mtusi_messenger.model.User;
public record SessionPrincipal(User user, byte[] tokenHash) {
public SessionPrincipal {
tokenHash = tokenHash.clone();
}
@Override
public byte[] tokenHash() {
return tokenHash.clone();
}
}
@@ -0,0 +1,104 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.cache.UserCache;
import com.example.mtusi_messenger.model.Session;
import com.example.mtusi_messenger.model.User;
import com.example.mtusi_messenger.repository.SessionRepository;
import com.example.mtusi_messenger.repository.UserRepository;
import com.example.mtusi_messenger.security.SessionPrincipal;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.UUID;
@Service
public class AuthenticationService {
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private final UserRepository users;
private final SessionRepository sessions;
private final UserCache userCache;
private final long ttlSeconds;
public AuthenticationService(
UserRepository users,
SessionRepository sessions,
UserCache userCache,
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
) {
if (ttlSeconds <= 0) {
throw new IllegalArgumentException("Session TTL must be positive");
}
this.users = users;
this.sessions = sessions;
this.userCache = userCache;
this.ttlSeconds = ttlSeconds;
}
public IssuedSession issueSession(User user) {
String token = newToken();
Instant createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
Instant expiresAt = createdAt.plusSeconds(ttlSeconds);
sessions.save(new Session(
UUID.randomUUID(),
user.id(),
hashToken(token),
createdAt,
expiresAt));
return new IssuedSession(token, expiresAt, user);
}
public SessionPrincipal authenticateBearer(String token) {
byte[] tokenHash = hashToken(token);
try {
UUID userId = sessions.findActiveUserId(tokenHash)
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
User user = userCache.find(userId).orElseGet(() -> {
User loaded = users.findById(userId)
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
userCache.put(loaded);
return loaded;
});
return new SessionPrincipal(user, tokenHash);
} catch (DataAccessException e) {
throw new AuthenticationServiceException("Authentication database is unavailable", e);
}
}
public void revoke(SessionPrincipal principal) {
try {
if (!sessions.revoke(principal.tokenHash())) {
throw new BadCredentialsException("Invalid or expired session");
}
} catch (DataAccessException e) {
throw new AuthenticationServiceException("Authentication database is unavailable", e);
}
}
private String newToken() {
byte[] bytes = new byte[32];
SECURE_RANDOM.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
private byte[] hashToken(String token) {
try {
return MessageDigest.getInstance("SHA-256")
.digest(token.getBytes(StandardCharsets.US_ASCII));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 is unavailable", e);
}
}
public record IssuedSession(String token, Instant expiresAt, User user) {}
}
@@ -0,0 +1,38 @@
package com.example.mtusi_messenger.service;
import org.springframework.stereotype.Service;
import com.example.mtusi_messenger.dto.CreateChatRequest;
import com.example.mtusi_messenger.exception.ApiExceptions;
import com.example.mtusi_messenger.model.Chat;
import com.example.mtusi_messenger.repository.ChatRepository;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
@Service
public class ChatService {
private final ChatRepository chats; private final UserService users; private final CursorService cursors;
public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; }
public Chat create(CreateChatRequest r, UUID caller) {
Set<UUID> ids = new LinkedHashSet<>(r.member_ids());
if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids");
for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids");
return chats.save(new Chat(UUID.randomUUID(), r.title(), List.copyOf(ids),
Instant.now().truncatedTo(ChronoUnit.MICROS)));
}
public Chat getAccessible(UUID chatId, UUID userId) {
users.get(userId);
if (!chats.isMember(chatId, userId)) throw ApiExceptions.notFound("Chat not found");
return chats.findById(chatId).orElseThrow(() -> ApiExceptions.notFound("Chat not found"));
}
public List<Chat> page(UUID userId, int limit, String cursor) {
CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "chats", userId);
return chats.findPageForUser(userId, c == null ? null : c.id(), c == null ? null : c.createdAt(), limit + 1);
}
public String nextCursor(UUID userId,
Chat last,
boolean hasNext
) {
return hasNext ? cursors.encode("chats", userId, last.createdAt(), last.id()) : null;
}
}
@@ -0,0 +1,40 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.exception.ApiException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import com.example.mtusi_messenger.exception.ApiExceptions;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;
@Service
public class CursorService {
private final ObjectMapper mapper;
public CursorService(ObjectMapper mapper) { this.mapper = mapper; }
public String encode(String resource, UUID resourceId, Instant createdAt, UUID id) {
try {
byte[] json = mapper.writeValueAsBytes(new CursorPayload(1, resource, resourceId, createdAt.toString(), id));
return Base64.getUrlEncoder().withoutPadding().encodeToString(json);
} catch (Exception e) { throw new IllegalStateException(e); }
}
public Cursor decode(String raw, String resource, UUID resourceId) {
if (raw == null || raw.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
try {
CursorPayload p = mapper.readValue(Base64.getUrlDecoder().decode(raw), CursorPayload.class);
if (p.v != 1
|| !resource.equals(p.resource)
|| !Objects.equals(resourceId, p.resourceId)
|| p.createdAt() == null
|| p.createdAt().isBlank()
|| p.id() == null
) throw ApiExceptions.invalid("Invalid cursor");
return new Cursor(Instant.parse(p.createdAt), p.id);
} catch (ApiException e) { throw e; }
catch (Exception e) { throw ApiExceptions.invalid("Invalid cursor"); }
}
public record Cursor(Instant createdAt, UUID id) {}
private record CursorPayload(int v, String resource, UUID resourceId, String createdAt, UUID id) {}
private static final class Objects { static boolean equals(Object a, Object b) { return java.util.Objects.equals(a,b); } }
}
@@ -0,0 +1,29 @@
package com.example.mtusi_messenger.service;
import com.github.f4b6a3.uuid.UuidCreator;
import org.springframework.stereotype.Service;
import com.example.mtusi_messenger.dto.CreateMessageRequest;
import com.example.mtusi_messenger.model.Message;
import com.example.mtusi_messenger.repository.MessageRepository;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;
@Service
public class MessageService {
private final MessageRepository messages; private final ChatService chats; private final CursorService cursors;
public MessageService(MessageRepository messages, ChatService chats, CursorService cursors) { this.messages=messages; this.chats=chats; this.cursors=cursors; }
public Message create(UUID chatId, UUID senderId, CreateMessageRequest r) {
chats.getAccessible(chatId, senderId);
String text = r.text();
return messages.save(new Message(UuidCreator.getTimeOrderedEpochPlus1(), chatId, senderId, text,
Instant.now().truncatedTo(ChronoUnit.MICROS)));
}
public List<Message> page(UUID chatId, UUID userId, int limit, String cursor) {
chats.getAccessible(chatId, userId);
CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "messages", chatId);
return messages.findPage(chatId, c == null ? null : c.createdAt(), c == null ? null : c.id(), limit + 1);
}
public String nextCursor(UUID chatId, Message last, boolean hasNext) { return hasNext ? cursors.encode("messages", chatId, last.createdAt(), last.id()) : null; }
}
@@ -0,0 +1,35 @@
package com.example.mtusi_messenger.service;
import org.springframework.stereotype.Service;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.example.mtusi_messenger.dto.CreateUserRequest;
import com.example.mtusi_messenger.exception.ApiExceptions;
import com.example.mtusi_messenger.model.User;
import com.example.mtusi_messenger.repository.UserRepository;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
@Service
public class UserService {
private final UserRepository users;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository users, PasswordEncoder passwordEncoder) {
this.users = users;
this.passwordEncoder = passwordEncoder;
}
public User create(CreateUserRequest r) {
String username = r.username(); String display = r.display_name();
if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken");
String passwordHash = passwordEncoder.encode(r.password());
try {
return users.save(new User(UUID.randomUUID(), username, display,
Instant.now().truncatedTo(ChronoUnit.MICROS)), passwordHash);
} catch (DuplicateKeyException e) {
throw ApiExceptions.conflict("Username is already taken");
}
}
public User get(UUID id) { return users.findById(id).orElseThrow(() -> ApiExceptions.unauthorized("Unknown user identity")); }
public boolean exists(UUID id) { return users.findById(id).isPresent(); }
}
@@ -0,0 +1,27 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.exception.ApiExceptions;
import java.util.UUID;
import java.util.regex.Pattern;
public final class UuidValidator {
private static final Pattern UUID_PATTERN = Pattern.compile(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
);
private UuidValidator() {}
public static UUID parse(String value) {
if (value == null || !UUID_PATTERN.matcher(value).matches()) {
throw ApiExceptions.invalid("Invalid UUID");
}
try {
return UUID.fromString(value);
} catch (IllegalArgumentException e) {
throw ApiExceptions.invalid("Invalid UUID");
}
}
}
@@ -0,0 +1,48 @@
package com.example.mtusi_messenger.web;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.dao.DataAccessException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import com.example.mtusi_messenger.dto.ErrorResponse;
import com.example.mtusi_messenger.exception.ApiException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ApiException.class)
ResponseEntity<ErrorResponse> api(ApiException e, HttpServletRequest req) {
var body = body(e.code(), e.getMessage(), req);
var builder = ResponseEntity.status(e.status());
if (e.status() == HttpStatus.UNAUTHORIZED && e.authenticate() != null) {
builder.header("WWW-Authenticate", e.authenticate());
}
return builder.body(body);
}
@ExceptionHandler({MethodArgumentNotValidException.class, MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class})
ResponseEntity<ErrorResponse> bad(Exception e, HttpServletRequest req) { return ResponseEntity.badRequest().body(body("invalid_request", "Invalid request", req)); }
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
ResponseEntity<ErrorResponse> unsupported(HttpServletRequest req) { return ResponseEntity.status(415).body(body("unsupported_media_type", "Unsupported media type", req)); }
@ExceptionHandler(DataAccessException.class)
ResponseEntity<ErrorResponse> unavailable(DataAccessException e, HttpServletRequest req) {
return ResponseEntity.status(503).body(body("unavailable", "Storage temporarily unavailable", req));
}
@ExceptionHandler(Exception.class)
ResponseEntity<ErrorResponse> internal(Exception e, HttpServletRequest req) { return ResponseEntity.status(500).body(body("internal_error", "Internal server error", req)); }
private ErrorResponse body(
String code,
String message,
HttpServletRequest req
) {
String id = (String) req.getAttribute(RequestIdFilter.ATTRIBUTE);
return new ErrorResponse(
new ErrorResponse.ErrorBody(code, message, id)
);
}
}
@@ -0,0 +1,21 @@
package com.example.mtusi_messenger.web;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Constraint(validatedBy = UnicodeBlankValidator.class)
@Target({ FIELD, PARAMETER, RECORD_COMPONENT, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface NotUnicodeBlank {
String message() default "must not be blank";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@@ -0,0 +1,40 @@
package com.example.mtusi_messenger.web;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.UUID;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestIdFilter extends OncePerRequestFilter {
public static final String HEADER = "X-Request-Id";
public static final String ATTRIBUTE = "request_id";
@Override
protected void doFilterInternal(
HttpServletRequest req,
HttpServletResponse res,
FilterChain chain
) throws ServletException, IOException {
String id = UUID.randomUUID().toString();
req.setAttribute(ATTRIBUTE, id);
res.setHeader(HEADER, id);
try {
chain.doFilter(req, res);
} finally {
MDC.remove(ATTRIBUTE);
}
}
}
@@ -0,0 +1,23 @@
package com.example.mtusi_messenger.web;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class UnicodeBlankValidator
implements ConstraintValidator<NotUnicodeBlank, String> {
@Override
public boolean isValid(
String value,
ConstraintValidatorContext context) {
if (value == null || value.isEmpty()) {
return false;
}
return value.codePoints().anyMatch(codePoint ->
!Character.isWhitespace(codePoint)
&& !Character.isSpaceChar(codePoint)
);
}
}
@@ -0,0 +1,35 @@
package com.example.mtusi_messenger.web;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Constraint(validatedBy = UnicodeSizeValidator.class)
@Target({
FIELD,
METHOD,
PARAMETER,
ANNOTATION_TYPE
})
@Retention(RUNTIME)
public @interface UnicodeSize {
String message() default "size must be between {min} and {max} Unicode code points";
int min() default 0;
int max() default Integer.MAX_VALUE;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@@ -0,0 +1,32 @@
package com.example.mtusi_messenger.web;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class UnicodeSizeValidator
implements ConstraintValidator<UnicodeSize, String> {
private int min;
private int max;
@Override
public void initialize(UnicodeSize annotation) {
this.min = annotation.min();
this.max = annotation.max();
}
@Override
public boolean isValid(
String value,
ConstraintValidatorContext context
) {
if (value == null) {
return true;
}
int codePointCount = value.codePointCount(0, value.length());
return codePointCount >= min
&& codePointCount <= max;
}
}
+58
View File
@@ -0,0 +1,58 @@
spring:
application:
name: mtusi-messenger
datasource:
url: ${DATABASE_URL:jdbc:postgresql://localhost:5432/messenger}
username: ${DATABASE_USER:messenger}
password: ${DATABASE_PASSWORD:messenger}
hikari:
maximum-pool-size: ${DATABASE_POOL_SIZE:10}
minimum-idle: ${DATABASE_MIN_IDLE:2}
connection-timeout: 5000
validation-timeout: 2000
idle-timeout: 600000
max-lifetime: 1800000
data:
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
connect-timeout: ${REDIS_CONNECT_TIMEOUT:1s}
timeout: ${REDIS_COMMAND_TIMEOUT:500ms}
lettuce:
pool:
max-active: ${REDIS_POOL_MAX_ACTIVE:8}
max-idle: ${REDIS_POOL_MAX_IDLE:8}
min-idle: ${REDIS_POOL_MIN_IDLE:0}
max-wait: ${REDIS_POOL_MAX_WAIT:500ms}
jdbc:
template:
query-timeout: ${DATABASE_QUERY_TIMEOUT_SECONDS:5}
transaction:
default-timeout: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:5}
flyway:
enabled: true
locations: classpath:db/migration
jackson:
deserialization:
fail-on-unknown-properties: true
lifecycle:
timeout-per-shutdown-phase: 10s
server:
address: ${APP_HOST:0.0.0.0}
port: ${APP_PORT:8080}
shutdown: graceful
messenger:
storage: postgres
session:
ttl-seconds: ${SESSION_TTL_SECONDS:3600}
cache:
user-ttl-seconds: ${USER_CACHE_TTL_SECONDS:300}
@@ -0,0 +1,60 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username varchar(32) NOT NULL,
display_name text NOT NULL,
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT users_username_uk UNIQUE (username),
CONSTRAINT users_username_format_chk
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_length_chk
CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT chats_title_length_chk
CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL,
user_id uuid NOT NULL,
joined_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT chat_members_pk PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_chat_fk
FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE,
CONSTRAINT chat_members_user_fk
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE RESTRICT
);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT messages_text_length_chk
CHECK (char_length(text) BETWEEN 1 AND 4000),
CONSTRAINT messages_sender_membership_fk
FOREIGN KEY (chat_id, sender_id)
REFERENCES chat_members(chat_id, user_id)
ON DELETE RESTRICT
);
CREATE INDEX chat_members_user_chat_idx
ON chat_members (user_id, chat_id);
CREATE INDEX chats_created_id_idx
ON chats (created_at, id);
CREATE INDEX messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
CREATE INDEX messages_sender_created_idx
ON messages (sender_id, created_at);
@@ -0,0 +1,28 @@
ALTER TABLE users
ADD COLUMN password_hash text;
ALTER TABLE users
ALTER COLUMN password_hash SET NOT NULL;
CREATE TABLE sessions (
id uuid PRIMARY KEY,
user_id uuid NOT NULL,
token_hash bytea NOT NULL,
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
CONSTRAINT sessions_user_fk
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT sessions_token_hash_uk UNIQUE (token_hash),
CONSTRAINT sessions_token_hash_length_chk
CHECK (octet_length(token_hash) = 32),
CONSTRAINT sessions_expiry_chk
CHECK (expires_at > created_at),
CONSTRAINT sessions_revocation_chk
CHECK (revoked_at IS NULL OR revoked_at >= created_at)
);
CREATE INDEX sessions_active_expiry_idx
ON sessions (expires_at)
WHERE revoked_at IS NULL;
@@ -0,0 +1,364 @@
package com.example.mtusi_messenger;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest
@AutoConfigureMockMvc
class MtusiMessengerApplicationTests {
private static final String USERS_URL = "/api/v1/users";
private static final String CHATS_URL = "/api/v1/chats";
private static final String SESSIONS_URL = "/api/v1/auth/sessions";
private static final String TEST_PASSWORD = "correct horse battery staple";
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
private User alice;
private User bob;
private User eve;
@BeforeEach
void setUp() throws Exception {
String suffix = UUID.randomUUID()
.toString()
.replace("-", "")
.substring(0, 12);
alice = registerUser("alice_" + suffix, "Alice");
bob = registerUser("bob_" + suffix, "Bob");
eve = registerUser("eve_" + suffix, "Eve");
}
@Test
void shouldReturn400WhenJsonIsMalformed() throws Exception {
mockMvc.perform(post(USERS_URL)
.contentType(MediaType.APPLICATION_JSON)
.content("{ \"username\": "))
.andExpect(status().isBadRequest())
.andExpect(header().exists("X-Request-Id"))
.andExpect(jsonPath("$.error.code")
.value("invalid_request"));
}
@Test
void shouldReturn400WhenPasswordContainsOnlyWhitespace() throws Exception {
String requestBody = objectMapper.writeValueAsString(
Map.of(
"username", "blank_password_" + UUID.randomUUID().toString().substring(0, 8),
"display_name", "Blank password probe",
"password", " "
)
);
mockMvc.perform(post(USERS_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isBadRequest())
.andExpect(header().exists("X-Request-Id"))
.andExpect(jsonPath("$.error.code")
.value("invalid_request"));
}
@Test
void shouldNotAllowNonMemberToReadChatMessages() throws Exception {
String chatId = createChat(alice, bob);
mockMvc.perform(get(CHATS_URL + "/" + chatId + "/messages")
.header("Authorization", bearer(eve))
.param("limit", "10"))
.andExpect(status().isNotFound())
.andExpect(header().exists("X-Request-Id"))
.andExpect(jsonPath("$.error.code")
.value("not_found"));
}
@Test
void shouldNotAllowNonMemberToSendMessage() throws Exception {
String chatId = createChat(alice, bob);
String requestBody = """
{
"text": "Hello from Eve"
}
""";
mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages")
.header("Authorization", bearer(eve))
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isNotFound())
.andExpect(header().exists("X-Request-Id"))
.andExpect(jsonPath("$.error.code")
.value("not_found"));
}
@Test
void shouldReturn400WhenMessageTextIsEmpty() throws Exception {
String chatId = createChat(alice, bob);
String requestBody = """
{
"text": ""
}
""";
mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages")
.header("Authorization", bearer(alice))
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isBadRequest())
.andExpect(header().exists("X-Request-Id"))
.andExpect(jsonPath("$.error.code")
.value("invalid_request"));
}
@Test
void shouldReturn400WhenMessageTextIsMissing() throws Exception {
String chatId = createChat(alice, bob);
mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages")
.header("Authorization", bearer(alice))
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest())
.andExpect(header().exists("X-Request-Id"))
.andExpect(jsonPath("$.error.code")
.value("invalid_request"));
}
@Test
void shouldReturn409WhenUsernameAlreadyExists() throws Exception {
String requestBody = """
{
"username": "%s",
"display_name": "Another Alice",
"password": "correct horse battery staple"
}
""".formatted(alice.username());
mockMvc.perform(post(USERS_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isConflict())
.andExpect(header().exists("X-Request-Id"))
.andExpect(jsonPath("$.error.code")
.value("conflict"));
}
@Test
void shouldReturnAllMessagesAcrossMultiplePagesWithoutDuplicates()
throws Exception {
String chatId = createChat(alice, bob);
int messageCount = 5;
int pageSize = 2;
int expectedPageCount = 3;
List<String> expectedTexts = new ArrayList<>();
for (int i = 1; i <= messageCount; i++) {
String text = "Message " + i;
sendMessage(chatId, alice, text);
expectedTexts.add(text);
}
List<String> actualIds = new ArrayList<>();
List<String> actualTexts = new ArrayList<>();
String cursor = null;
int pageCount = 0;
while (true) {
var request = get(CHATS_URL + "/" + chatId + "/messages")
.header("Authorization", bearer(alice))
.param("limit", String.valueOf(pageSize));
if (cursor != null) {
request.param("cursor", cursor);
}
MvcResult result = mockMvc.perform(request)
.andExpect(status().isOk())
.andExpect(header().exists("X-Request-Id"))
.andExpect(jsonPath("$.items").isArray())
.andReturn();
JsonNode response = objectMapper.readTree(
result.getResponse().getContentAsString()
);
JsonNode items = response.get("items");
assertNotNull(items);
assertTrue(items.size() <= pageSize);
for (JsonNode item : items) {
actualIds.add(item.get("id").asText());
actualTexts.add(item.get("text").asText());
}
pageCount++;
JsonNode nextCursor = response.get("next_cursor");
if (nextCursor.isNull()) {
break;
}
cursor = nextCursor.asText();
assertFalse(cursor.isBlank(),
"next_cursor must not be blank when more pages exist");
assertTrue(pageCount <= messageCount,
"Pagination did not terminate");
}
assertEquals(expectedPageCount, pageCount);
assertEquals(messageCount, actualIds.size());
assertEquals(messageCount, actualTexts.size());
assertEquals(actualIds.size(), new HashSet<>(actualIds).size());
assertEquals(expectedTexts, actualTexts);
}
@Test
void shouldIgnoreXUserIdForProtectedEndpoints() throws Exception {
mockMvc.perform(get(USERS_URL + "/me")
.header("X-User-Id", alice.id()))
.andExpect(status().isUnauthorized())
.andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\""));
}
@Test
void shouldRevokeCurrentSession() throws Exception {
mockMvc.perform(delete(SESSIONS_URL + "/current")
.header("Authorization", bearer(alice)))
.andExpect(status().isNoContent());
mockMvc.perform(get(USERS_URL + "/me")
.header("Authorization", bearer(alice)))
.andExpect(status().isUnauthorized())
.andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\""));
}
@Test
void shouldRejectWrongPasswordWithBasicChallenge() throws Exception {
String basic = Base64.getEncoder().encodeToString(
(alice.username() + ":definitely-wrong-password")
.getBytes(java.nio.charset.StandardCharsets.UTF_8));
mockMvc.perform(post(SESSIONS_URL)
.header("Authorization", "Basic " + basic))
.andExpect(status().isUnauthorized())
.andExpect(header().string(
"WWW-Authenticate",
"Basic realm=\"messenger\", charset=\"UTF-8\""));
}
private User registerUser(String username, String displayName)
throws Exception {
String requestBody = objectMapper.writeValueAsString(
Map.of(
"username", username,
"display_name", displayName,
"password", TEST_PASSWORD
)
);
MvcResult result = mockMvc.perform(post(USERS_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isCreated())
.andExpect(header().exists("X-Request-Id"))
.andReturn();
JsonNode response = objectMapper.readTree(
result.getResponse().getContentAsString()
);
String basic = Base64.getEncoder().encodeToString(
(username + ":" + TEST_PASSWORD).getBytes(java.nio.charset.StandardCharsets.UTF_8));
MvcResult loginResult = mockMvc.perform(post(SESSIONS_URL)
.header("Authorization", "Basic " + basic))
.andExpect(status().isCreated())
.andReturn();
JsonNode session = objectMapper.readTree(loginResult.getResponse().getContentAsString());
return new User(
response.get("id").asText(),
response.get("username").asText(),
session.get("token").asText()
);
}
private String createChat(User owner, User member)
throws Exception {
String requestBody = objectMapper.writeValueAsString(
java.util.Map.of(
"title", "Test chat " + UUID.randomUUID(),
"member_ids", List.of(owner.id(), member.id())
)
);
MvcResult result = mockMvc.perform(post(CHATS_URL)
.header("Authorization", bearer(owner))
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isCreated())
.andExpect(header().exists("X-Request-Id"))
.andReturn();
JsonNode response = objectMapper.readTree(
result.getResponse().getContentAsString()
);
return response.get("id").asText();
}
private void sendMessage(String chatId, User sender, String text)
throws Exception {
String requestBody = objectMapper.writeValueAsString(
java.util.Map.of("text", text)
);
mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages")
.header("Authorization", bearer(sender))
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isCreated())
.andExpect(header().exists("X-Request-Id"));
}
private static String bearer(User user) {
return "Bearer " + user.token();
}
private record User(String id, String username, String token) {
}
}
@@ -0,0 +1,31 @@
package com.example.mtusi_messenger.cache;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class UserCacheTest {
@Test
void shouldEvictJsonNullAndReturnCacheMiss() {
UUID userId = UUID.randomUUID();
String key = "messenger:user:" + userId;
StringRedisTemplate redis = mock(StringRedisTemplate.class);
@SuppressWarnings("unchecked")
ValueOperations<String, String> values = mock(ValueOperations.class);
when(redis.opsForValue()).thenReturn(values);
when(values.get(key)).thenReturn("null");
UserCache cache = new UserCache(redis, new ObjectMapper(), 300);
assertTrue(cache.find(userId).isEmpty());
verify(redis).delete(key);
}
}
+197
View File
@@ -0,0 +1,197 @@
#!/usr/bin/env python3
"""Destructive local Compose checks for cache, outages, races, and rollback."""
import base64
import json
import os
from pathlib import Path
import subprocess
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from client import Client, Failure, check, run
ROOT = Path(__file__).resolve().parents[1]
def compose(*args, env=None, capture=False):
result = subprocess.run(
['docker', 'compose', '--env-file', '.env', *args],
cwd=ROOT,
env=env,
check=False,
text=True,
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
stderr=subprocess.PIPE if capture else subprocess.DEVNULL,
)
check(result.returncode == 0, 'docker compose command failed: ' + ' '.join(args))
return result.stdout.strip() if capture else ''
def psql(sql, capture=False):
result = subprocess.run(
[
'docker', 'compose', '--env-file', '.env', 'exec', '-T', 'postgres',
'sh', '-lc', 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -At'
],
cwd=ROOT,
input=sql,
text=True,
check=False,
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
stderr=subprocess.PIPE,
)
check(result.returncode == 0, 'PostgreSQL probe failed')
return result.stdout.strip() if capture else ''
def wait_ready(client, seconds=90):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
client.call('GET', '/health/ready', schema='Health')
return
except Failure:
time.sleep(0.5)
raise Failure('API did not become ready')
def basic(username, password):
value = base64.b64encode((username + ':' + password).encode()).decode()
return {'Authorization': 'Basic ' + value}
def main():
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default='http://localhost:8080')
args = parser.parse_args()
client = Client(args.base_url)
normal_env = dict(os.environ)
normal_env.pop('SESSION_TTL_SECONDS', None)
short_env = dict(normal_env)
short_env['SESSION_TTL_SECONDS'] = '2'
trigger_installed = False
try:
compose('up', '-d', '--force-recreate', '--no-deps', '--wait', 'api', env=short_env)
expiring = client.user('expiry')
client.call('GET', '/api/v1/users/me', actor=expiring, schema='User')
time.sleep(2.5)
client.call('GET', '/api/v1/users/me', 401, actor=expiring)
compose('up', '-d', '--force-recreate', '--no-deps', '--wait', 'api', env=normal_env)
wait_ready(client)
actor = client.user('operational')
password = actor['registration']['password']
client.call(
'POST', '/api/v1/users', 400,
body={
'username': 'blank_password_' + uuid.uuid4().hex[:12],
'display_name': 'Blank password probe',
'password': ' ',
})
client.call(
'POST', '/api/v1/auth/sessions', 401,
headers=basic(actor['registration']['username'], password + '-wrong'))
client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
cache_key = 'messenger:user:' + actor['id']
ttl = compose('exec', '-T', 'redis', 'redis-cli', 'TTL', cache_key, capture=True)
check(ttl.isdigit() and 0 < int(ttl) <= 300, 'Redis cache key has no bounded TTL')
compose('exec', '-T', 'redis', 'redis-cli', 'SET', cache_key, 'null')
client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
cached_user = compose(
'exec', '-T', 'redis', 'redis-cli', '--raw', 'GET', cache_key, capture=True)
try:
cached_payload = json.loads(cached_user)
except json.JSONDecodeError as error:
raise Failure('JSON null cache entry was not replaced with valid JSON') from error
check(
isinstance(cached_payload, dict) and cached_payload.get('id') == actor['id'],
'JSON null cache entry was not replaced from PostgreSQL')
appendonly = compose(
'exec', '-T', 'redis', 'redis-cli', '--raw', 'CONFIG', 'GET', 'appendonly',
capture=True)
check(appendonly.splitlines()[-1:] == ['yes'], 'Redis AOF persistence is disabled')
compose('stop', 'redis')
client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
compose('start', 'redis')
compose('up', '-d', '--wait', 'redis')
logout_actor = client.user('logout')
client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=logout_actor)
client.call('GET', '/api/v1/users/me', 401, actor=logout_actor)
compose('stop', 'postgres')
client.call('GET', '/api/v1/users/me', 401)
client.call('GET', '/api/v1/users/me', 503, actor=actor)
compose('start', 'postgres')
compose('up', '-d', '--wait', 'postgres')
wait_ready(client)
race_name = 'race_' + uuid.uuid4().hex[:12]
race_body = {
'username': race_name,
'display_name': 'Race probe',
'password': 'correct horse battery staple',
}
def register_once(_):
local = Client(args.base_url)
return local.call('POST', '/api/v1/users', [201, 409], body=race_body)['status']
with ThreadPoolExecutor(max_workers=12) as executor:
statuses = list(executor.map(register_once, range(12)))
check(statuses.count(201) == 1, 'username race created more or less than one user')
check(statuses.count(409) == 11, 'username race did not return conflict to every loser')
owner = client.user('rollback_owner')
probe = client.user('rollback_member')
function_name = 'fail_rollback_probe'
title = 'rollback-probe-' + uuid.uuid4().hex
psql(f"""
DROP TRIGGER IF EXISTS {function_name}_trigger ON chat_members;
DROP FUNCTION IF EXISTS {function_name}();
CREATE OR REPLACE FUNCTION {function_name}() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.user_id = '{probe['id']}'::uuid THEN
RAISE EXCEPTION 'intentional rollback probe';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER {function_name}_trigger
BEFORE INSERT ON chat_members
FOR EACH ROW EXECUTE FUNCTION {function_name}();
""")
trigger_installed = True
client.call(
'POST', '/api/v1/chats', 503, actor=owner,
body={'title': title, 'member_ids': [owner['id'], probe['id']]})
count = psql(
"SELECT count(*) FROM chats WHERE title = '" + title + "';",
capture=True)
check(count == '0', 'failed composite chat operation was not rolled back')
print('PASS: blank password, JSON null cache recovery, expiry, logout, wrong password, '
'Redis fallback, DB failure, username race, and chat rollback verified.')
finally:
compose('up', '-d', '--wait', 'postgres', 'redis')
if trigger_installed:
try:
psql(f"""
DROP TRIGGER IF EXISTS {function_name}_trigger ON chat_members;
DROP FUNCTION IF EXISTS {function_name}();
""")
except Failure:
pass
compose('up', '-d', '--force-recreate', '--wait', 'api', env=normal_env)
if __name__ == '__main__':
run(main)
+13 -1
View File
@@ -3,6 +3,7 @@
import json
import os
from pathlib import Path
import shutil
import subprocess
import time
import uuid
@@ -55,7 +56,18 @@ def main():
check(len(observed)>=2,'less than two API instances observed before failure; verify LB/session affinity')
print('Executing explicit '+args.mode+' hook; hook output suppressed to avoid leaking secrets.')
# No shell interpolation and no Docker commands in this test.
proc = subprocess.Popen([str(script)],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
command = [str(script)]
if os.name == 'nt' and script.suffix.lower() == '.sh':
interpreter = shutil.which('sh')
if interpreter is None:
git = shutil.which('git')
if git is not None:
candidate = Path(git).resolve().parents[1] / 'bin' / 'bash.exe'
if candidate.is_file():
interpreter = str(candidate)
check(interpreter is not None,'sh interpreter is required to run the action script on Windows')
command = [interpreter,str(script)]
proc = subprocess.Popen(command,env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
started = time.monotonic()
successes,failures,after_instances = [],0,[]
try: