This commit is contained in:
a.ilin
2026-10-05 14:40:04 +03:00
parent 31a430e2ce
commit a8dd98c70e
43 changed files with 1818 additions and 215 deletions
+81 -21
View File
@@ -10,46 +10,106 @@ description: Схемные изменения БД проекта gorodar back
## Порядок работы
1. Новый файл `src/main/resources/db/changelog/changelogs/NNN-имя.sql` (нумерация сквозная, следующий свободный номер).
1. Новый файл `src/main/resources/db/changelog/changelogs/NNN-имя.yaml` (нумерация сквозная, следующий свободный номер).
2. Зарегистрировать его в `src/main/resources/db/changelog/db.changelog-master.yaml` (порядок include = порядок применения).
3. Синхронно поправить entity в `ru.gorodar.dao.entity` (см. скилл jpa-entity).
4. Прогнать `./gradlew build` — validate поймает расхождение.
## Формат changelog
SQL-формат Liquibase:
Только YAML-ченджсеты с нативными change-типами Liquibase (`createTable`, `createIndex`, `addColumn`,
`addUniqueConstraint` и т.д.) — не SQL-файлы и не `sql`-change. Автор ченджсетов — `gorodar`.
```sql
--liquibase formatted sql
```yaml
databaseChangeLog:
- changeSet:
id: 006-example
author: gorodar
changes:
- createTable:
tableName: example
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: parent_id
type: uuid
constraints:
foreignKeyName: fk_example_parent_id
references: example(id)
- column:
name: name
type: varchar(255)
constraints:
nullable: false
- column:
name: created_at
type: timestamp
defaultValueComputed: "now() at time zone 'utc'"
constraints:
nullable: false
- changeSet:
id: 006-example-index-parent
author: gorodar
changes:
- createIndex:
indexName: idx_example_parent_id
tableName: example
columns:
- column:
name: parent_id
```
--changeset gorodar:NNN-таблица
create table example (
id uuid primary key,
created_at timestamp not null default (now() at time zone 'utc')
);
**Единственное исключение** — то, что OSS-Liquibase не умеет нативно, оформляется `sql`-change внутри
YAML-ченджсета (с `dbms: postgresql`, комментарием-обоснованием и явным `rollback`):
--changeset gorodar:NNN-индексы
create index idx_example_parent on example (parent_id);
- CHECK-констрейнты (`addCheckConstraint` — платный Liquibase Secure);
- partial index (`createIndex` без WHERE).
```yaml
- changeSet:
id: 006-example-check-status
author: gorodar
comment: CHECK нельзя нативно — осознанное sql-исключение
changes:
- sql:
dbms: postgresql
sql: alter table example add constraint ck_example_status check (status in ('DRAFT', 'ACTIVE'))
rollback:
- sql:
dbms: postgresql
sql: alter table example drop constraint ck_example_status
```
## Конвенции схемы
- PK — `uuid`, генерируется приложением (не БД).
- Время — только `timestamp` **без** `timestamptz`, дефолт `(now() at time zone 'utc')`. Вся система в UTC.
- Имена snake_case; FK-колонки `<сущность>_id`; индексы `idx_…`, уникальные `uq_…`.
- Время — только `timestamp` **без** `timestamptz`, дефолт `defaultValueComputed: "now() at time zone 'utc'"`. Вся система в UTC.
- Имена snake_case; FK-колонки `<сущность>_id`; FK-констрейнты `fk_<таблица>_<колонка>`; индексы `idx_…`, уникальные `uq_…`, CHECK'и `ck_…`.
- Составная уникальность — `addUniqueConstraint` (`constraintName: uq_…`) в том же ченджсете, что и `createTable`.
- Бизнес-инварианты — на стороне БД:
- «не более одного активного набора на зону» — partial unique index:
`create unique index uq_attraction_sets_active_area on attraction_sets (area_id) where status = 'ACTIVE';`
- составная уникальность — `constraint uq_… unique (a, b)`;
- enum-статусы — `constraint ck_… check (status in ('DRAFT', 'ACTIVE', 'ARCHIVED'))`.
- «не более одного активного набора на зону» — partial unique index (sql-исключение, см. `003-attraction-sets-unique-active`);
- enum-статусы — CHECK (sql-исключение, см. `003-attraction-sets-check-status`).
- Удаления данных нет (кроме эталонных фото) — DELETE-констрейнты не нужны.
## Пример: добавить колонку
```sql
--changeset gorodar:005-add-example-column
alter table attractions
add column example_field varchar(64);
```yaml
databaseChangeLog:
- changeSet:
id: 006-add-example-field
author: gorodar
changes:
- addColumn:
tableName: attractions
columns:
- column:
name: example_field
type: varchar(64)
```
И тут же `@Column(name = "example_field") private String exampleField;` в entity.
+39 -15
View File
@@ -1,18 +1,42 @@
---
name: security-rules
description: Авторизация gorodar back — Keycloak JWT, client roles клиента gorodar (manage_area/manage_attraction), разграничение public/user/admin эндпоинтов, CurrentUser с claim sub. Использовать при добавлении защищённых или публичных путей, смене ролей, работе с токеном/subject пользователя. Use for endpoint authorization, Keycloak roles, JWT validation, CurrentUser.
description: Авторизация gorodar back — собственная (email-код → JWT RS256, OIDC-совместимые эндпоинты), роли manage_area/manage_attraction, разграничение public/user/admin эндпоинтов, CurrentUser с claim sub. Использовать при добавлении защищённых или публичных путей, смене ролей, работе с токенами/авторизацией/refresh. Use for endpoint authorization, roles, JWT issuing/validation, email-code auth flow, CurrentUser.
---
# Security gorodar back
Resource-server only: бэкенд только валидирует входящие JWT (oauth2-client отсутствует).
Стартер Boot 4: `spring-boot-starter-security-oauth2-resource-server` (+`-test`).
Keycloak отсутствует: сервис сам авторизует пользователей и выпускает токены.
Стек: resource server (валидация своих же JWT) + собственные OIDC-совместимые эндпоинты
авторизации в пакете `ru.gorodar.auth`. Стартер Boot 4:
`spring-boot-starter-security-oauth2-resource-server` (+`-test`), `spring-boot-starter-mail`.
## Флоу входа (FR-A0)
1. `POST /oauth2/authorize` JSON `{email}` — пользователь создаётся при отсутствии;
6-значный код → SHA-256-хэш в `auth_codes` (TTL 10 мин, повторная отправка ≥ 60 c →
429 `AUTH_CODE_RATE_LIMITED`, максимум 5 попыток) и на почту (без SMTP — log-only).
2. `POST /oauth2/token` — **form-urlencoded (RFC 6749)**, два grant'а:
`urn:gorodar:params:oauth:grant-type:email-code` (`email`+`code`) и `refresh_token`
(ротация: старый отзывается). Успех: `{access_token, token_type, expires_in,
refresh_token, scope}`; ошибки: `{error: "invalid_grant", error_description}` —
это отдельный формат для данного эндпоинта, не наш ApiError.
3. Discovery: `GET /.well-known/openid-configuration`, `GET /oauth2/jwks`.
## Токены
- Access — JWT RS256, TTL 24 ч (`gorodar.auth.access-token-ttl`). Claims: `iss`
(`gorodar.auth.issuer`, env `GORODAR_AUTH_ISSUER`), `sub` = `users.id`, `aud` = `gorodar`,
`email`, роли в `resource_access.gorodar.roles` (OAuth2-формат, клиент `gorodar.auth.client-id`).
- Refresh — opaque, в БД только SHA-256-хэш, TTL 30 дней, одноразовый (ротация).
- Подписные ключи — `gorodar.auth.keys-dir` (в докере volume), генерируются при первом
старте. Пакет `ru.gorodar.auth`: `AuthService`, `TokenService`, `JwkKeys`, `MailCodeSender`,
`AuthController`, `DiscoveryController`.
## Роли
Client roles клиента **`gorodar`** (настройка `gorodar.keycloak.client-id`), извлекаются из
`resource_access.gorodar.roles` конвертером `KeycloakJwtAuthenticationConverter` и становятся
authorities с точным совпадением имён:
Хранятся в `user_roles` (назначение — SQL, API управления нет), попадают в claim
`resource_access.gorodar.roles`, конвертер `ClientRolesJwtAuthenticationConverter` делает
из них authorities с точным совпадением имён:
- `manage_area` — зоны, наборы, статистика посещений;
- `manage_attraction` — достопримечательности, иконки, эталонные фото, пересчёт признаков;
@@ -21,6 +45,7 @@ authorities с точным совпадением имён:
## Матчеры в SecurityConfig (порядок важен)
```java
.requestMatchers("/oauth2/**", "/.well-known/**").permitAll()
.requestMatchers("/api/admin/attractions/**").hasAuthority("manage_attraction")
.requestMatchers("/api/admin/areas/**", "/api/admin/sets/**", "/api/admin/visits/**")
.hasAuthority("manage_area")
@@ -32,23 +57,22 @@ authorities с точным совпадением имён:
.anyRequest().denyAll()
```
Новый админский эндпоинт должен попасть под существующий префикс роли; новый префикс — добавить
матчер ДО `/api/admin/**`. Публичные GET каталога — permitAll с опциональной аутентификацией:
ответ обогащается персональными данными, если токен пришёл и валиден.
Новый админский эндпоинт должен попасть под существующий префикс роли; новый префикс —
матчер ДО `/api/admin/**`. Публичные GET каталога — permitAll с опциональной аутентификацией.
## Валидация токена
## Валидация входящих токенов
`issuer-uri` из `spring.security.oauth2.resourceserver.jwt.*` (подпись/JWKS/срок/issuer — стандартные
валидаторы) + audience-проверка в `SecurityConfig.jwtDecoder`: пропускаем, если `aud` содержит `gorodar`
**или** `azp == gorodar` (Keycloak по умолчанию кладёт клиента только в azp). CSRF выключен, сессии stateless.
`JwtDecoder` в SecurityConfig — по локальному `JWKSource` (без HTTP): подпись + срок +
issuer + audience `gorodar`. CSRF выключен, сессии stateless.
## Текущий пользователь
Claim `sub` — идентификатор пользователя (ключ визитов). Доступ — `CurrentUserProvider`:
```java
Optional<CurrentUser> user = currentUserProvider.getCurrentUser(); // публичные эндпоинты
Optional<CurrentUser> user = currentUserProvider.getCurrentUser(); // публичные места
CurrentUser user = currentUserProvider.requireUser(); // защищённые (401 гарантирует security)
```
Прямо `Authentication`/`Jwt` в контроллеры не таскать.
Прямо `Authentication`/`Jwt` в контроллеры не таскать; параметры `Optional` в методы
сервисов не передавать — сервис, которому нужен пользователь, инжектит провайдер сам.
+11
View File
@@ -0,0 +1,11 @@
.idea
.gradle
build
.git
.agents
docs
.env
.env.example
AGENTS.md
README.md
docker-compose.yml
+33
View File
@@ -0,0 +1,33 @@
# Скопируйте в .env и заполните значения: cp .env.example .env
# docker compose подхватывает .env из корня автоматически.
# PostgreSQL (используются и контейнером db, и приложением)
GORODAR_DB_HOST=
GORODAR_DB_PORT=
GORODAR_DB_NAME=
GORODAR_DB_USER=
GORODAR_DB_PASSWORD=
# Собственная авторизация: issuer для access-токенов (снаружи — адрес сервиса),
# каталог подписных ключей (в докере — volume), режим «код в лог вместо почты»
GORODAR_AUTH_ISSUER=
GORODAR_AUTH_KEYS_DIR=
GORODAR_AUTH_MAIL_LOG_ONLY=
# SMTP для кодов подтверждения (если не заполнен GORODAR_MAIL_HOST — код пишется в лог)
GORODAR_MAIL_HOST=
GORODAR_MAIL_PORT=
GORODAR_MAIL_USERNAME=
GORODAR_MAIL_PASSWORD=
GORODAR_MAIL_FROM=
# Сервис распознавания open_cv
GORODAR_OPENCV_URL=
GORODAR_OPENCV_API_KEY=
# S3/MinIO
GORODAR_S3_ENDPOINT=
GORODAR_S3_REGION=
GORODAR_S3_ACCESS_KEY=
GORODAR_S3_SECRET_KEY=
GORODAR_S3_BUCKET=
+1
View File
@@ -30,3 +30,4 @@ replay_pid*
/build/
/.zcode/plans/
/.zcodeignore
/.env
+1 -1
View File
@@ -23,7 +23,7 @@ On Windows, `gradlew.bat` is equivalent (it is git-ignored but present locally).
## Conventions and gotchas
- **Spring Boot 4 starter names**: `spring-boot-starter-webmvc`, `spring-boot-starter-security-oauth2-resource-server`, and matching `*-test` starters. Do not "fix" them to Boot 3 names (`spring-boot-starter-web`, `spring-boot-starter-oauth2-resource-server`) — those do not exist in Boot 4. Auth is resource-server only (JWT from Keycloak, client `gorodar`); there is no oauth2-client.
- **Spring Boot 4 starter names**: `spring-boot-starter-webmvc`, `spring-boot-starter-security-oauth2-resource-server`, and matching `*-test` starters. Do not "fix" them to Boot 3 names (`spring-boot-starter-web`, `spring-boot-starter-oauth2-resource-server`) — those do not exist in Boot 4. Auth is self-issued (email-code flow in `ru.gorodar.auth`, OIDC-shaped endpoints); the service validates its own JWTs (RS256, local JWKS) as a resource server; there is no Keycloak and no oauth2-client.
- **Lombok**: declared as `compileOnly` + `annotationProcessor` (plus test variants). Keep this pattern when adding modules; plain `implementation` breaks annotation processing.
- **MapStruct** (entity↔DTO mappers in `ru.gorodar.mapper`, `componentModel = "spring"`, `unmappedTargetPolicy = ERROR`): `mapstruct` is an `implementation` dep, `mapstruct-processor` and `lombok-mapstruct-binding` are `annotationProcessor` entries — keep all three together, order matters for Lombok interop.
- **Criteria queries use the generated JPA metamodel**: `hibernate-jpamodelgen` runs as an annotation processor and generates `X_` classes next to entities; Specifications (`ru.gorodar.dao.spec`) must reference attributes via `Entity_.field`, never string paths like `root.get("name")`.
+16
View File
@@ -0,0 +1,16 @@
FROM eclipse-temurin:25-jdk AS build
WORKDIR /workspace
COPY gradlew build.gradle ./
COPY gradle gradle
RUN chmod +x gradlew
COPY src src
# Тесты в образе не гоняем: интеграционные проверки выполняются в CI/локально
RUN ./gradlew --no-daemon bootJar -x test
FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=build /workspace/build/libs/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
+1
View File
@@ -21,6 +21,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-liquibase'
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-security-oauth2-resource-server'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
+50
View File
@@ -0,0 +1,50 @@
services:
db:
image: postgres:17
environment:
POSTGRES_DB: ${GORODAR_DB_NAME:-}
POSTGRES_USER: ${GORODAR_DB_USER:-}
POSTGRES_PASSWORD: ${GORODAR_DB_PASSWORD:-}
ports:
- "5432:5432"
#volumes:
# - ./postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 5s
timeout: 3s
retries: 10
app:
build: .
depends_on:
db:
condition: service_healthy
ports:
- "8080:8080"
environment:
GORODAR_DB_HOST: ${GORODAR_DB_HOST:-db}
GORODAR_DB_PORT: ${GORODAR_DB_PORT:-5432}
GORODAR_DB_NAME: ${GORODAR_DB_NAME:-}
GORODAR_DB_USER: ${GORODAR_DB_USER:-}
GORODAR_DB_PASSWORD: ${GORODAR_DB_PASSWORD:-}
GORODAR_AUTH_ISSUER: ${GORODAR_AUTH_ISSUER:-}
GORODAR_AUTH_KEYS_DIR: ${GORODAR_AUTH_KEYS_DIR:-/app/keys}
GORODAR_AUTH_MAIL_LOG_ONLY: ${GORODAR_AUTH_MAIL_LOG_ONLY:-}
GORODAR_MAIL_HOST: ${GORODAR_MAIL_HOST:-}
GORODAR_MAIL_PORT: ${GORODAR_MAIL_PORT:-}
GORODAR_MAIL_USERNAME: ${GORODAR_MAIL_USERNAME:-}
GORODAR_MAIL_PASSWORD: ${GORODAR_MAIL_PASSWORD:-}
GORODAR_MAIL_FROM: ${GORODAR_MAIL_FROM:-}
GORODAR_OPENCV_URL: ${GORODAR_OPENCV_URL:-}
GORODAR_OPENCV_API_KEY: ${GORODAR_OPENCV_API_KEY:-}
GORODAR_S3_ENDPOINT: ${GORODAR_S3_ENDPOINT:-}
GORODAR_S3_REGION: ${GORODAR_S3_REGION:-}
GORODAR_S3_ACCESS_KEY: ${GORODAR_S3_ACCESS_KEY:-}
GORODAR_S3_SECRET_KEY: ${GORODAR_S3_SECRET_KEY:-}
GORODAR_S3_BUCKET: ${GORODAR_S3_BUCKET:-}
volumes:
- auth-keys:/app/keys
volumes:
auth-keys:
+67 -44
View File
@@ -1,6 +1,6 @@
# Системный анализ бэкенда «Городар»
Версия: 0.10
Версия: 0.11
Дата: 2026-09-29
| Версия | Что изменилось |
@@ -15,6 +15,7 @@
| 0.8 | Публичные `GET /api/areas` и `GET /api/areas/{id}` обогащены: в каждой зоне — `attractions` активного набора (id, name, iconUrl, visited) и `progress {visited, total}`; анониму — все unvisited, прогресс 0 |
| 0.9 | Карточка `GET /api/attractions/{id}` получила признак `visited` (по визиту текущего пользователя; анониму — false) |
| 0.10 | Хранение enum'ов унифицировано: везде `@Enumerated(EnumType.STRING)` (в БД — верхний регистр), `AttributeConverter` для enum'ов убраны; API-контракт не изменился (нижний регистр на границе дают мапперы) |
| 0.11 | Keycloak убран: собственная авторизация по email-коду с OIDC-совместимыми эндпоинтами (`/oauth2/authorize`, `/oauth2/token`, discovery, jwks), access JWT RS256 24 ч + refresh 30 дней с ротацией, таблицы users/user_roles/auth_codes/refresh_tokens (FR-A0, §7.1) |
## 1. Назначение документа
@@ -23,15 +24,16 @@
## 2. Контекст системы
Бэкенд «Городара» — центральный сервис, вокруг которого четыре внешних зависимости:
Бэкенд «Городара» — центральный сервис; авторизация встроена в него самого
(email-код + собственные JWT), внешние зависимости — open_cv, S3, PostgreSQL и SMTP:
```
┌────────────┐ Bearer JWT ┌──────────┐
Мобильное ────────►│ │◄──────────────│ Keycloak │
приложение │ Городар │ (токен с └──────────┘
(фронтенд) │ back API │ фронта)
│ │── image / probe+reference(.npz) ──► ┌─────────┐
│ │◄── .npz / verdict+confidence ────── │ open_cv │
┌────────────┐ email + код ┌───────┐
Мобильное ────────►│ │◄──────────────►│ SMTP │
приложение │ Городар │ (код login) └───────┘
(фронтенд) │ back API │
│ + auth │── image / probe+reference(.npz) ──► ┌─────────┐
│ (iss JWT) │◄── .npz / verdict+confidence ────── │ open_cv │
│ │ (X-API-Key) └─────────┘
│ │── эталонные фото, блобы признаков, ──► S3
│ │ иконки PostgreSQL
@@ -39,36 +41,48 @@
```
Границы системы:
- **входит**: REST API (публичная, пользовательская и админская части), валидация JWT
и извлечение идентификатора пользователя, доменная логика (зоны, достопримечательности,
- **входит**: REST API (публичная, пользовательская и админская части), собственная
авторизация (email-код → access/refresh токены, OIDC-совместимые эндпоинты), валидация
JWT и извлечение идентификатора пользователя, доменная логика (зоны, достопримечательности,
наборы, посещения), оркестрация: эталон → `/features` → S3; фото пользователя →
`/verify` (напрямую, без хранения) → отметка посещения;
- **не входит**: выдача токенов (Keycloak), само извлечение/сравнение признаков
(open_cv — stateless, ничего не хранит), UI мобильного приложения.
- **не входит**: само извлечение/сравнение признаков (open_cv — stateless, ничего не
хранит), UI мобильного приложения, доставка почты (SMTP-сервер внешний).
## 3. Акторы и роли
| Актор | Роли (Keycloak client roles клиента `gorodar`) | Что делает |
| Актор | Роли (в `user_roles`) | Что делает |
|---|---|---|
| Гость (без токена) | — | Смотрит зоны, достопримечательности, активные наборы |
| Пользователь | любой аутентифицированный | Как гость + отправляет фото для отметки посещения, смотрит свой прогресс и историю |
| Менеджер зон | `manage_area` | Управляет зонами и наборами (создание, состав, активация); смотрит статистику |
| Менеджер контента | `manage_attraction` | Управляет достопримечательностями (карточки, иконки, эталонные фото, пересчёт признаков) |
| open_cv | внутренний сервис-интеграция | Извлекает SIFT-признаки эталона (/features), верифицирует фото пользователя (/verify) |
| Keycloak | внешний IdP | Выдаёт и подписывает JWT; источник `sub` и client roles |
| SMTP | внешний сервис | Доставка кодов подтверждения (без настройки — log-only) |
## 4. Функциональные требования
### 4.1 Авторизация и идентификация
- **FR-A1.** Публичные (без токена) эндпоинты: чтение зон, достопримечательностей и
активного набора (FR-U1…U3). Всё остальное требует `Authorization: Bearer <JWT>`
(посещения, прогресс, история — персональны; админка — отдельные роли).
- **FR-A2.** Бэкенд валидирует токен: подпись (JWKS по `issuer-uri`), срок действия,
издателя, audience. Невалидный — 401.
- **FR-A3.** Из валидного токена извлекается claim `sub` — идентификатор пользователя,
он же ключ в таблице посещений.
- **FR-A4.** Гранулярный доступ в админке (client roles из claim
- **FR-A0.** Собственная авторизация по email-коду (OIDC-совместимые эндпоинты):
`POST /oauth2/authorize {email}` — пользователь создаётся при отсутствии, на почту
уходит одноразовый код (6 цифр, TTL 10 мин, повторная отправка не чаще раза в минуту);
`POST /oauth2/token` (form-urlencoded, RFC 6749) — обмен `email+code`
(grant `urn:gorodar:params:oauth:grant-type:email-code`) или `refresh_token` на
`{access_token, token_type, refresh_token, expires_in, scope}`; ошибки —
`{error, error_description}`. Discovery: `GET /.well-known/openid-configuration`,
`GET /oauth2/jwks`. Access JWT (RS256, TTL 24 ч): iss, sub = id пользователя,
aud = `gorodar`, email, роли в `resource_access.gorodar.roles`; refresh (opaque,
SHA-256-хэш в БД, TTL 30 дней, ротация при использовании).
- **FR-A1.** Публичные (без токена) эндпоинты: `/oauth2/**`, `/.well-known/**`,
чтение зон, достопримечательностей и активного набора (FR-U1…U3). Всё остальное
требует `Authorization: Bearer <JWT>` (посещения, прогресс, история — персональны;
админка — отдельные роли).
- **FR-A2.** Бэкенд валидирует собственные access-токены по локальным ключам (RS256):
подпись, срок действия, issuer, audience = `gorodar`. Невалидный — 401.
- **FR-A3.** Из валидного токена извлекается claim `sub` — идентификатор пользователя
(`users.id`), он же ключ в таблице посещений.
- **FR-A4.** Гранулярный доступ в админке (роли из `user_roles`, в токене — claim
`resource_access.gorodar.roles`):
- `manage_area` — зоны (`/api/admin/areas/**`), наборы (`/api/admin/sets/**`, `.../sets`),
статистика посещений (`/api/admin/visits`);
@@ -78,6 +92,9 @@
(sub + роли), чтобы не таскать `Authentication` вручную.
- **FR-A6.** На публичных эндпоинтах токен опционален: если передан и валиден — ответ
обогащается персональными данными (флаг `visited`), иначе отдаётся нейтральный каталог.
- **FR-A7.** Роли назначаются администратором БД (таблица `user_roles`), API управления
пользователями на старте не предусмотрено. Коды и refresh-токены хранятся хэшами
SHA-256; код одноразовый, максимум 5 попыток подбора.
### 4.2 Пользовательская часть
@@ -155,7 +172,7 @@ algo_id, keypoints_count) и `sort_order` — порядковый номер д
`DRAFT` → `ACTIVE` → `ARCHIVED` (см. 5.4). Связь с достопримечательностями many-to-many
через `attraction_set_items` (суррогатный `id`, уникальность пары — констрейнтом).
**attraction_users_visits — посещения.** Связка «пользователь (Keycloak `sub`) ×
**attraction_users_visits — посещения.** Связка «пользователь (users.id, он же `sub` access-токена) ×
достопримечательность» (только из активного набора). Хранит время и результат
верификации: verdict, confidence, probe_sha256 (фото пользователя не сохраняется —
SHA-256 приходит в ответе `/verify`).
@@ -212,7 +229,7 @@ erDiagram
}
attraction_users_visits {
uuid id PK
varchar user_id "Keycloak sub"
varchar user_id "users.id (sub токена)"
uuid attraction_id FK
timestamp visited_at "UTC"
varchar verdict "MATCH (EnumType.STRING)"
@@ -277,29 +294,35 @@ DRAFT ──activate──► ACTIVE ──archive──► ARCHIVED
## 7. Интеграции
### 7.1 Keycloak
### 7.1 Собственная авторизация (email-код, OIDC-совместимая)
- Spring Security OAuth2 **Resource Server** (не oauth2-client!): валидация JWT по
`issuer-uri` (JWKS подтягивается автоматически), проверка audience.
- Требуется заменить/дополнить зависимость: в Boot 4 стартер называется
`spring-boot-starter-security-oauth2-resource-server` (в build.gradle сейчас только
`...-security-oauth2-client` — он про инициирование логина, не про приём токенов).
- Роли — client roles клиента **`gorodar`**: `manage_area`, `manage_attraction` из claim
`resource_access.gorodar.roles`; маппятся в одноимённые authorities и проверяются на
путях по FR-A4.
- Request-scoped бин:
Внешнего IdP нет: сервис сам выпускает и валидирует токены. Пакет `ru.gorodar.auth`,
таблицы `users` / `user_roles` / `auth_codes` / `refresh_tokens` (миграция 005).
```java
public record CurrentUser(String id /* sub */, Set<String> roles) {}
**Флоу входа.** `POST /oauth2/authorize {email}` (JSON) — пользователь создаётся при
первом обращении; 6-значный код хэшируется SHA-256 и ложится в `auth_codes`
(TTL 10 мин, повторная отправка ≥ 60 с, максимум 5 попыток). Отправка кода — SMTP
(`spring.mail.*`); без настроенного хоста или при `gorodar.auth.mail-log-only=true` —
код пишется в лог. `POST /oauth2/token` (form-urlencoded, RFC 6749):
grant `urn:gorodar:params:oauth:grant-type:email-code` (`email`+`code`) или
`refresh_token` (ротация: старый отзывается, выдаётся новая пара). Успех —
`{access_token, token_type: "Bearer", expires_in, refresh_token, scope}`,
ошибки — `{error: "invalid_grant", error_description}`.
@Component
@RequestScope
public class CurrentUserProvider { /* читает SecurityContext, отдаёт CurrentUser */ }
```
**Токены.** Access — JWT RS256 (ключи в `gorodar.auth.keys-dir`, генерируются при первом
старте; в докере — volume), TTL 24 ч; claims: `iss` = `gorodar.auth.issuer`, `sub` =
`users.id`, `aud` = `gorodar`, `email`, роли в `resource_access.gorodar.roles` (формат
OAuth2 — конвертер ролей не зависит от источника токена). Refresh — 32 случайных байта
(base64url), в БД только SHA-256-хэш, TTL 30 дней, одноразовый (ротация при обмене).
- Конфиг в `application.yml`: `spring.security.oauth2.resourceserver.jwt.issuer-uri`
(audience — клиент `gorodar`).
- Публичные GET-эндпоинты каталога — `permitAll` с опциональной аутентификацией (FR-A6).
**OIDC discovery.** `GET /.well-known/openid-configuration` (issuer, endpoints,
поддерживаемые grant'ы), `GET /oauth2/jwks` (публичный RSA-ключ).
**Валидация входящих токенов.** Resource server c `JwtDecoder` по локальному `JWKSource`:
подпись + срок + issuer + audience `gorodar` (без HTTP-петли). Роли из claim —
`ClientRolesJwtAuthenticationConverter` (`gorodar.auth.client-id` = `gorodar`).
`CurrentUserProvider` отдаёт `sub` + роли. Публичные пути: `/oauth2/**`, `/.well-known/**`,
GET каталога (FR-A1). Роли назначаются в `user_roles` вручную (SQL).
### 7.2 open_cv (контракт зафиксирован: OpenAPI 1.0.0)
@@ -549,7 +572,7 @@ ru.gorodar
| Роли | Client roles клиента `gorodar`: `manage_area` (зоны, наборы, статистика) и `manage_attraction` (достопримечательности, иконки, фото, пересчёт) |
| Иконка (R1) | Файл в S3 (`attractions/{id}/icon/{fileId}.{ext}`); в БД ключ, в API presigned-ссылка |
| cv_profile (R2) | Хранится на достопримечательности; при загрузке/пересчёте фото берётся оттуда; смена не пересчитывает существующие блобы |
| Keycloak-клиент (R3) | `gorodar` (роли из `resource_access.gorodar.roles`, audience — он же) |
| Клиент токенов | `gorodar` (audience и ключ claim `resource_access.gorodar.roles`) |
| Визиты вне набора | Запрещены: 409 `ATTRACTION_NOT_IN_ACTIVE_SET` |
| Тип зоны | Поля нет; вложенность сама задаёт иерархию |
| Заливка файлов | Только через бэкенд (multipart), presigned upload не используем |
@@ -0,0 +1,25 @@
package ru.gorodar.api.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
public final class AuthDtos {
private AuthDtos() {
}
public record AuthorizeRequest(@NotBlank @Email String email) {
}
public record TokenResponse(@JsonProperty("access_token") String accessToken,
@JsonProperty("token_type") String tokenType,
@JsonProperty("expires_in") long expiresInSeconds,
@JsonProperty("refresh_token") String refreshToken,
String scope) {
}
public record TokenErrorResponse(@JsonProperty("error") String error,
@JsonProperty("error_description") String errorDescription) {
}
}
@@ -0,0 +1,67 @@
package ru.gorodar.auth;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import ru.gorodar.api.dto.AuthDtos.AuthorizeRequest;
import ru.gorodar.api.dto.AuthDtos.TokenErrorResponse;
import ru.gorodar.api.dto.AuthDtos.TokenResponse;
import ru.gorodar.exception.ApiException;
import ru.gorodar.exception.ErrorCode;
import java.util.Map;
@RestController
@RequiredArgsConstructor
@Tag(name = "auth")
public class AuthController {
public static final String EMAIL_CODE_GRANT = "urn:gorodar:params:oauth:grant-type:email-code";
public static final String REFRESH_TOKEN_GRANT = "refresh_token";
private final AuthService authService;
@PostMapping("/oauth2/authorize")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void authorize(@Valid @RequestBody AuthorizeRequest request) {
authService.requestCode(request.email());
}
/**
* Контракт — RFC 6749: form-urlencoded на входе, {error, error_description} на выходе.
*/
@PostMapping(value = "/oauth2/token", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<?> token(@RequestParam Map<String, String> form) {
try {
AuthService.IssuedTokens tokens = switch (form.getOrDefault("grant_type", "")) {
case EMAIL_CODE_GRANT -> authService.tokenByEmailCode(
required(form, "email"), required(form, "code"));
case REFRESH_TOKEN_GRANT -> authService.tokenByRefresh(required(form, "refresh_token"));
default -> throw new ApiException(ErrorCode.VALIDATION_ERROR, "unsupported_grant_type");
};
return ResponseEntity.ok(new TokenResponse(
tokens.accessToken(), "Bearer", tokens.expiresInSeconds(), tokens.refreshToken(), "gorodar"));
} catch (ApiException e) {
boolean unsupported = "unsupported_grant_type".equals(e.getMessage());
String error = unsupported ? "unsupported_grant_type" : "invalid_grant";
HttpStatus status = unsupported ? HttpStatus.BAD_REQUEST : HttpStatus.valueOf(e.getCode().getStatus());
return ResponseEntity.status(status).body(new TokenErrorResponse(error, e.getMessage()));
}
}
private String required(Map<String, String> form, String name) {
String value = form.get(name);
if (value == null || value.isBlank()) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Отсутствует обязательный параметр " + name);
}
return value;
}
}
@@ -0,0 +1,147 @@
package ru.gorodar.auth;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.gorodar.auth.TokenService.IssuedAccessToken;
import ru.gorodar.dao.AuthCodeRepository;
import ru.gorodar.dao.RefreshTokenRepository;
import ru.gorodar.dao.UserRepository;
import ru.gorodar.dao.UserRoleRepository;
import ru.gorodar.dao.entity.AuthCode;
import ru.gorodar.dao.entity.RefreshToken;
import ru.gorodar.dao.entity.User;
import ru.gorodar.dao.entity.UserRole;
import ru.gorodar.config.AuthProperties;
import ru.gorodar.exception.ApiException;
import ru.gorodar.exception.ErrorCode;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.UUID;
@Service
@RequiredArgsConstructor
@Slf4j
public class AuthService {
private static final int CODE_LENGTH = 6;
private static final int MAX_ATTEMPTS = 5;
private final UserRepository userRepository;
private final UserRoleRepository userRoleRepository;
private final AuthCodeRepository authCodeRepository;
private final RefreshTokenRepository refreshTokenRepository;
private final TokenService tokenService;
private final MailCodeSender mailCodeSender;
private final AuthProperties properties;
private final SecureRandom secureRandom = new SecureRandom();
@Transactional
public void requestCode(String rawEmail) {
String email = rawEmail.trim().toLowerCase();
User user = userRepository.findByEmail(email).orElseGet(() -> createUser(email));
LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(user.getId())
.filter(last -> last.getCreatedAt().plus(properties.resendInterval()).isAfter(now))
.ifPresent(last -> {
throw new ApiException(ErrorCode.AUTH_CODE_RATE_LIMITED);
});
String code = generateCode();
AuthCode authCode = new AuthCode();
authCode.setId(UUID.randomUUID());
authCode.setUser(user);
authCode.setCodeHash(sha256Hex(code));
authCode.setExpiresAt(now.plus(properties.codeTtl()));
authCode.setAttempts(0);
authCodeRepository.save(authCode);
mailCodeSender.sendCode(email, code);
}
@Transactional
public IssuedTokens tokenByEmailCode(String rawEmail, String code) {
String email = rawEmail.trim().toLowerCase();
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new ApiException(ErrorCode.INVALID_GRANT));
AuthCode authCode = authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(user.getId())
.orElseThrow(() -> new ApiException(ErrorCode.INVALID_GRANT));
if (authCode.getUsedAt() != null
|| authCode.getExpiresAt().isBefore(LocalDateTime.now(ZoneOffset.UTC))
|| authCode.getAttempts() >= MAX_ATTEMPTS) {
throw new ApiException(ErrorCode.INVALID_GRANT);
}
if (!MessageDigest.isEqual(sha256Hex(code).getBytes(StandardCharsets.UTF_8),
authCode.getCodeHash().getBytes(StandardCharsets.UTF_8))) {
authCode.setAttempts(authCode.getAttempts() + 1);
authCodeRepository.save(authCode);
throw new ApiException(ErrorCode.INVALID_GRANT);
}
authCode.setUsedAt(LocalDateTime.now(ZoneOffset.UTC));
authCodeRepository.save(authCode);
return issueTokens(user);
}
@Transactional
public IssuedTokens tokenByRefresh(String rawRefreshToken) {
RefreshToken refresh = refreshTokenRepository.findByTokenHash(sha256Hex(rawRefreshToken))
.orElseThrow(() -> new ApiException(ErrorCode.INVALID_GRANT));
if (refresh.getRevokedAt() != null
|| refresh.getExpiresAt().isBefore(LocalDateTime.now(ZoneOffset.UTC))) {
throw new ApiException(ErrorCode.INVALID_GRANT);
}
refresh.setRevokedAt(LocalDateTime.now(ZoneOffset.UTC));
refreshTokenRepository.save(refresh);
return issueTokens(refresh.getUser());
}
private IssuedTokens issueTokens(User user) {
List<String> roles = userRoleRepository.findByUserId(user.getId()).stream()
.map(UserRole::getRole)
.toList();
IssuedAccessToken access = tokenService.issueAccessToken(user, roles);
String refreshValue = new String(Base64.getUrlEncoder().withoutPadding()
.encode(secureRandom.generateSeed(32)), StandardCharsets.UTF_8);
RefreshToken refresh = new RefreshToken();
refresh.setId(UUID.randomUUID());
refresh.setUser(user);
refresh.setTokenHash(sha256Hex(refreshValue));
refresh.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).plus(properties.refreshTokenTtl()));
refreshTokenRepository.save(refresh);
return new IssuedTokens(access.token(), access.expiresInSeconds(), refreshValue);
}
private User createUser(String email) {
User user = new User();
user.setId(UUID.randomUUID());
user.setEmail(email);
return userRepository.save(user);
}
private String generateCode() {
StringBuilder code = new StringBuilder(CODE_LENGTH);
for (int i = 0; i < CODE_LENGTH; i++) {
code.append(secureRandom.nextInt(10));
}
return code.toString();
}
private String sha256Hex(String value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 недоступен", e);
}
}
public record IssuedTokens(String accessToken, long expiresInSeconds, String refreshToken) {
}
}
@@ -0,0 +1,40 @@
package ru.gorodar.auth;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.gorodar.config.AuthProperties;
import java.util.List;
import java.util.Map;
@RestController
@RequiredArgsConstructor
public class DiscoveryController {
private final AuthProperties properties;
private final JwkKeys jwkKeys;
@GetMapping("/.well-known/openid-configuration")
public Map<String, Object> openidConfiguration() {
String issuer = trimTrailingSlash(properties.issuer());
return Map.of(
"issuer", issuer,
"authorization_endpoint", issuer + "/oauth2/authorize",
"token_endpoint", issuer + "/oauth2/token",
"jwks_uri", issuer + "/oauth2/jwks",
"response_modes_supported", List.of("form_post", "query"),
"grant_types_supported", List.of(AuthController.EMAIL_CODE_GRANT, AuthController.REFRESH_TOKEN_GRANT),
"token_endpoint_auth_methods_supported", List.of("none"),
"scopes_supported", List.of("gorodar"));
}
@GetMapping("/oauth2/jwks")
public Map<String, Object> jwks() {
return jwkKeys.publicKeySet().toJSONObject();
}
private String trimTrailingSlash(String value) {
return value.endsWith("/") ? value.substring(0, value.length() - 1) : value;
}
}
@@ -0,0 +1,65 @@
package ru.gorodar.auth;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import ru.gorodar.config.AuthProperties;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.ParseException;
import java.util.UUID;
/**
* Подписные ключи RS256 для access-токенов. Хранятся как JWK-JSON в keysDir;
* при первом старте генерируются и сохраняются, чтобы токены переживали рестарты.
*/
@Component
@Slf4j
public class JwkKeys {
private static final String KEY_FILE = "access-token-rs256.json";
@Getter
private final RSAKey key;
public JwkKeys(AuthProperties properties) {
this.key = loadOrGenerate(properties.keysDir().resolve(KEY_FILE));
}
public JWKSet publicKeySet() {
return new JWKSet(key.toPublicJWK());
}
public JWKSet fullKeySet() {
return new JWKSet(key);
}
private RSAKey loadOrGenerate(Path file) {
try {
if (Files.exists(file)) {
RSAKey loaded = (RSAKey) JWKSet.parse(Files.readString(file)).getKeys().getFirst();
log.info("Загружен подписной ключ access-токенов из {}", file);
return loaded;
}
RSAKey generated = new RSAKeyGenerator(2048)
.algorithm(JWSAlgorithm.RS256)
.keyUse(KeyUse.SIGNATURE)
.keyID(UUID.randomUUID().toString())
.generate();
Files.createDirectories(file.getParent());
Files.writeString(file, new JWKSet(generated).toJSONObject(false).toString());
log.info("Сгенерирован новый подписной ключ access-токенов: {}", file);
return generated;
} catch (IOException | ParseException | JOSEException e) {
throw new IllegalStateException("Не удалось загрузить/сгенерировать подписной ключ " + file, e);
}
}
}
@@ -0,0 +1,40 @@
package ru.gorodar.auth;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import ru.gorodar.config.AuthProperties;
/**
* Отправка кода подтверждения. Без настроенного SMTP-хоста переходит в log-only режим —
* код пишется в лог, чтобы dev/docker поднимались без почты.
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class MailCodeSender {
private final JavaMailSender mailSender;
private final AuthProperties properties;
@Value("${spring.mail.host:}")
private String mailHost;
public void sendCode(String email, String code) {
boolean logOnly = properties.mailLogOnly() || !StringUtils.hasText(mailHost);
if (logOnly) {
log.warn("SMTP не настроен (log-only): код подтверждения для {} = {}", email, code);
return;
}
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(properties.mailFrom());
message.setTo(email);
message.setSubject("Городар: код подтверждения");
message.setText("Ваш код подтверждения: %s\nКод действителен 10 минут.".formatted(code));
mailSender.send(message);
}
}
@@ -0,0 +1,55 @@
package ru.gorodar.auth;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.stereotype.Component;
import ru.gorodar.config.AuthProperties;
import ru.gorodar.dao.entity.User;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@Component
public class TokenService {
public static final String AUDIENCE = "gorodar";
private final JwtEncoder encoder;
private final AuthProperties properties;
public TokenService(JwkKeys jwkKeys, AuthProperties properties) {
JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwkKeys.getKey()));
this.encoder = new NimbusJwtEncoder(jwkSource);
this.properties = properties;
}
public IssuedAccessToken issueAccessToken(User user, List<String> roles) {
Instant now = Instant.now();
Instant expiresAt = now.plus(properties.accessTokenTtl());
Map<String, Object> resourceAccess = Map.of(AUDIENCE, Map.of("roles", roles));
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer(properties.issuer())
.subject(user.getId().toString())
.audience(List.of(AUDIENCE))
.issuedAt(now)
.expiresAt(expiresAt)
.claim("email", user.getEmail())
.claim("resource_access", resourceAccess)
.build();
String token = encoder.encode(JwtEncoderParameters.from(
JwsHeader.with(SignatureAlgorithm.RS256).build(), claims)).getTokenValue();
return new IssuedAccessToken(token, properties.accessTokenTtl().toSeconds());
}
public record IssuedAccessToken(String token, long expiresInSeconds) {
}
}
@@ -0,0 +1,18 @@
package ru.gorodar.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.time.Duration;
import java.nio.file.Path;
@ConfigurationProperties(prefix = "gorodar.auth")
public record AuthProperties(
String issuer,
Duration accessTokenTtl,
Duration refreshTokenTtl,
Duration codeTtl,
Duration resendInterval,
Path keysDir,
boolean mailLogOnly,
String mailFrom) {
}
@@ -0,0 +1,12 @@
package ru.gorodar.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.gorodar.dao.entity.AuthCode;
import java.util.Optional;
import java.util.UUID;
public interface AuthCodeRepository extends JpaRepository<AuthCode, UUID> {
Optional<AuthCode> findFirstByUserIdOrderByCreatedAtDesc(UUID userId);
}
@@ -0,0 +1,12 @@
package ru.gorodar.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.gorodar.dao.entity.RefreshToken;
import java.util.Optional;
import java.util.UUID;
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, UUID> {
Optional<RefreshToken> findByTokenHash(String tokenHash);
}
@@ -0,0 +1,12 @@
package ru.gorodar.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.gorodar.dao.entity.User;
import java.util.Optional;
import java.util.UUID;
public interface UserRepository extends JpaRepository<User, UUID> {
Optional<User> findByEmail(String email);
}
@@ -0,0 +1,12 @@
package ru.gorodar.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.gorodar.dao.entity.UserRole;
import java.util.List;
import java.util.UUID;
public interface UserRoleRepository extends JpaRepository<UserRole, UUID> {
List<UserRole> findByUserId(UUID userId);
}
@@ -0,0 +1,39 @@
package ru.gorodar.dao.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "auth_codes")
@Getter
@Setter
public class AuthCode {
@Id
@Column(name = "id")
private UUID id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(name = "code_hash", nullable = false)
private String codeHash;
@Column(name = "expires_at", nullable = false)
private LocalDateTime expiresAt;
@Column(name = "attempts", nullable = false)
private int attempts;
@Column(name = "used_at")
private LocalDateTime usedAt;
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
}
@@ -0,0 +1,37 @@
package ru.gorodar.dao.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "refresh_tokens")
@Getter
@Setter
public class RefreshToken {
@Id
@Column(name = "id")
private UUID id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(name = "token_hash", nullable = false)
private String tokenHash;
@Column(name = "expires_at", nullable = false)
private LocalDateTime expiresAt;
@Column(name = "revoked_at")
private LocalDateTime revokedAt;
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
}
@@ -0,0 +1,31 @@
package ru.gorodar.dao.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "users")
@Getter
@Setter
public class User {
@Id
@Column(name = "id")
private UUID id;
@Column(name = "email", nullable = false)
private String email;
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
}
@@ -0,0 +1,33 @@
package ru.gorodar.dao.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "user_roles")
@Getter
@Setter
public class UserRole {
@Id
@Column(name = "id")
private UUID id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(name = "role", nullable = false)
private String role;
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
}
@@ -6,6 +6,8 @@ import lombok.Getter;
public enum ErrorCode {
VALIDATION_ERROR(400, "Некорректный запрос"),
INVALID_GRANT(400, "Неверные учётные данные или код подтверждения"),
INVALID_EMAIL(400, "Некорректный email"),
INVALID_PHOTO(400, "Некорректный файл фотографии"),
AREA_CYCLE(400, "Зона не может быть вложена в саму себя или своего потомка"),
SET_NOT_READY(400, "Набор не готов к активации"),
@@ -26,6 +28,7 @@ public enum ErrorCode {
PAYLOAD_TOO_LARGE(413, "Файл превышает допустимый размер"),
UNSUPPORTED_MEDIA_TYPE(415, "Неподдерживаемый тип файла"),
AUTH_CODE_RATE_LIMITED(429, "Код уже отправлен, повторите через минуту"),
NO_REFERENCE_PHOTO(503, "У достопримечательности нет эталонного фото с признаками"),
REFERENCE_UNAVAILABLE(503, "Эталон недоступен или устарел, требуется пересчёт признаков"),
@@ -13,15 +13,15 @@ import java.util.List;
import java.util.Map;
/**
* Извлекает client roles токена Keycloak из claim resource_access.<client_id>.roles.
* Извлекает роли из claim resource_access.<client_id>.roles собственных access-токенов.
* Роли используются как authorities с точным совпадением имён (manage_area, manage_attraction).
*/
@Component
public class KeycloakJwtAuthenticationConverter implements Converter<Jwt, JwtAuthenticationToken> {
public class ClientRolesJwtAuthenticationConverter implements Converter<Jwt, JwtAuthenticationToken> {
private final String clientId;
public KeycloakJwtAuthenticationConverter(@Value("${gorodar.keycloak.client-id}") String clientId) {
public ClientRolesJwtAuthenticationConverter(@Value("${gorodar.auth.client-id}") String clientId) {
this.clientId = clientId;
}
@@ -1,6 +1,7 @@
package ru.gorodar.security;
import org.springframework.beans.factory.annotation.Value;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
@@ -9,15 +10,17 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.web.SecurityFilterChain;
import ru.gorodar.auth.JwkKeys;
import ru.gorodar.auth.TokenService;
import ru.gorodar.config.AuthProperties;
import java.util.List;
@@ -27,11 +30,14 @@ public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http,
Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter) throws Exception {
Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter,
JwtDecoder jwtDecoder) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
// собственная авторизация (email-код) и OIDC discovery — публичны
.requestMatchers("/oauth2/**", "/.well-known/**").permitAll()
// manage_area: зоны, наборы, статистика; manage_attraction: достопримечательности и эталоны
.requestMatchers("/api/admin/attractions/**").hasAuthority("manage_attraction")
.requestMatchers("/api/admin/areas/**", "/api/admin/sets/**", "/api/admin/visits/**")
@@ -51,24 +57,18 @@ public class SecurityConfig {
}
/**
* Валидация по умолчанию (подпись/срок/issuer) плюс проверка, что токен выдан
* нашему клиенту: audience содержит client_id либо azp равен ему.
* Валидация собственных access-токенов по локальным ключам (без HTTP): подпись,
* срок, issuer и audience = gorodar.
*/
@Bean
JwtDecoder jwtDecoder(@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") String issuerUri,
@Value("${gorodar.keycloak.client-id}") String clientId) {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withIssuerLocation(issuerUri).build();
OAuth2TokenValidator<Jwt> defaultValidators = JwtValidators.createDefaultWithIssuer(issuerUri);
OAuth2TokenValidator<Jwt> audienceValidator = jwt -> {
List<String> audience = jwt.getAudience();
String authorizedParty = jwt.getClaimAsString("azp");
if ((audience != null && audience.contains(clientId)) || clientId.equals(authorizedParty)) {
return OAuth2TokenValidatorResult.success();
}
return OAuth2TokenValidatorResult.failure(new OAuth2Error(
"invalid_token", "Токен выдан не для клиента " + clientId, null));
};
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(defaultValidators, audienceValidator));
JwtDecoder jwtDecoder(JwkKeys jwkKeys, AuthProperties properties) {
NimbusJwtDecoder decoder = NimbusJwtDecoder
.withJwkSource(new ImmutableJWKSet<>(new JWKSet(jwkKeys.getKey())))
.build();
OAuth2TokenValidator<Jwt> issuerAndExpiry = JwtValidators.createDefaultWithIssuer(properties.issuer());
OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>("aud",
aud -> aud != null && aud.contains(TokenService.AUDIENCE));
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(issuerAndExpiry, audience));
return decoder;
}
}
+14 -6
View File
@@ -18,11 +18,11 @@ spring:
liquibase:
change-log: classpath:db/changelog/db.changelog-master.yaml
security:
oauth2:
resourceserver:
jwt:
issuer-uri: ${GORODAR_KEYCLOAK_ISSUER:http://localhost:8081/realms/gorodar}
mail:
host: ${GORODAR_MAIL_HOST:}
port: ${GORODAR_MAIL_PORT:587}
username: ${GORODAR_MAIL_USERNAME:}
password: ${GORODAR_MAIL_PASSWORD:}
servlet:
multipart:
@@ -30,8 +30,16 @@ spring:
max-request-size: 22MB
gorodar:
keycloak:
auth:
client-id: gorodar
issuer: ${GORODAR_AUTH_ISSUER:http://localhost:8080}
access-token-ttl: 24h
refresh-token-ttl: 30d
code-ttl: 10m
resend-interval: 60s
keys-dir: ${GORODAR_AUTH_KEYS_DIR:./keys}
mail-log-only: ${GORODAR_AUTH_MAIL_LOG_ONLY:false}
mail-from: ${GORODAR_MAIL_FROM:}
opencv:
base-url: ${GORODAR_OPENCV_URL:http://localhost:8000}
api-key: ${GORODAR_OPENCV_API_KEY:dev-key}
@@ -1,13 +0,0 @@
--liquibase formatted sql
--changeset gorodar:001-areas
create table areas (
id uuid primary key,
parent_id uuid references areas (id),
name varchar(255) not null,
created_at timestamp not null default (now() at time zone 'utc'),
updated_at timestamp not null default (now() at time zone 'utc')
);
--changeset gorodar:001-areas-index-parent
create index idx_areas_parent_id on areas (parent_id);
@@ -0,0 +1,47 @@
databaseChangeLog:
- changeSet:
id: 001-areas
author: gorodar
changes:
- createTable:
tableName: areas
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: parent_id
type: uuid
constraints:
foreignKeyName: fk_areas_parent_id
references: areas(id)
- column:
name: name
type: varchar(255)
constraints:
nullable: false
- column:
name: created_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- column:
name: updated_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- changeSet:
id: 001-areas-index-parent
author: gorodar
changes:
- createIndex:
indexName: idx_areas_parent_id
tableName: areas
columns:
- column:
name: parent_id
@@ -1,37 +0,0 @@
--liquibase formatted sql
--changeset gorodar:002-attractions
create table attractions (
id uuid primary key,
area_id uuid not null references areas (id),
name varchar(255) not null,
icon_key varchar(512),
about text,
latitude numeric(9, 6),
longitude numeric(9, 6),
address varchar(512),
facts jsonb,
cv_profile varchar(32) not null,
created_at timestamp not null default (now() at time zone 'utc'),
updated_at timestamp not null default (now() at time zone 'utc')
);
--changeset gorodar:002-attractions-index-area
create index idx_attractions_area_id on attractions (area_id);
--changeset gorodar:002-attraction-photos
create table attraction_photos (
id uuid primary key,
attraction_id uuid not null references attractions (id),
s3_photo_key varchar(512) not null,
s3_features_key varchar(512) not null,
feature_format_version integer not null,
algo_id varchar(64) not null,
keypoints_count integer not null,
sort_order integer not null,
created_at timestamp not null default (now() at time zone 'utc'),
constraint uq_attraction_photos_sort_order unique (attraction_id, sort_order)
);
--changeset gorodar:002-attraction-photos-index-attraction
create index idx_attraction_photos_attraction_id on attraction_photos (attraction_id);
@@ -0,0 +1,141 @@
databaseChangeLog:
- changeSet:
id: 002-attractions
author: gorodar
changes:
- createTable:
tableName: attractions
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: area_id
type: uuid
constraints:
foreignKeyName: fk_attractions_area_id
references: areas(id)
nullable: false
- column:
name: name
type: varchar(255)
constraints:
nullable: false
- column:
name: icon_key
type: varchar(512)
- column:
name: about
type: text
- column:
name: latitude
type: numeric(9,6)
- column:
name: longitude
type: numeric(9,6)
- column:
name: address
type: varchar(512)
- column:
name: facts
type: jsonb
- column:
name: cv_profile
type: varchar(32)
constraints:
nullable: false
- column:
name: created_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- column:
name: updated_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- changeSet:
id: 002-attractions-index-area
author: gorodar
changes:
- createIndex:
indexName: idx_attractions_area_id
tableName: attractions
columns:
- column:
name: area_id
- changeSet:
id: 002-attraction-photos
author: gorodar
changes:
- createTable:
tableName: attraction_photos
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: attraction_id
type: uuid
constraints:
foreignKeyName: fk_attraction_photos_attraction_id
references: attractions(id)
nullable: false
- column:
name: s3_photo_key
type: varchar(512)
constraints:
nullable: false
- column:
name: s3_features_key
type: varchar(512)
constraints:
nullable: false
- column:
name: feature_format_version
type: integer
constraints:
nullable: false
- column:
name: algo_id
type: varchar(64)
constraints:
nullable: false
- column:
name: keypoints_count
type: integer
constraints:
nullable: false
- column:
name: sort_order
type: integer
constraints:
nullable: false
- column:
name: created_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- addUniqueConstraint:
tableName: attraction_photos
columnNames: attraction_id, sort_order
constraintName: uq_attraction_photos_sort_order
- changeSet:
id: 002-attraction-photos-index-attraction
author: gorodar
changes:
- createIndex:
indexName: idx_attraction_photos_attraction_id
tableName: attraction_photos
columns:
- column:
name: attraction_id
@@ -1,31 +0,0 @@
--liquibase formatted sql
--changeset gorodar:003-attraction-sets
create table attraction_sets (
id uuid primary key,
area_id uuid not null references areas (id),
name varchar(255) not null,
status varchar(16) not null,
created_at timestamp not null default (now() at time zone 'utc'),
updated_at timestamp not null default (now() at time zone 'utc'),
constraint ck_attraction_sets_status check (status in ('DRAFT', 'ACTIVE', 'ARCHIVED'))
);
--changeset gorodar:003-attraction-sets-unique-active
create unique index uq_attraction_sets_active_area on attraction_sets (area_id) where status = 'ACTIVE';
--changeset gorodar:003-attraction-sets-index-area
create index idx_attraction_sets_area_id on attraction_sets (area_id);
--changeset gorodar:003-attraction-set-items
create table attraction_set_items (
id uuid primary key,
set_id uuid not null references attraction_sets (id),
attraction_id uuid not null references attractions (id),
created_at timestamp not null default (now() at time zone 'utc'),
constraint uq_attraction_set_items unique (set_id, attraction_id)
);
--changeset gorodar:003-attraction-set-items-indexes
create index idx_attraction_set_items_set_id on attraction_set_items (set_id);
create index idx_attraction_set_items_attraction_id on attraction_set_items (attraction_id);
@@ -0,0 +1,130 @@
databaseChangeLog:
- changeSet:
id: 003-attraction-sets
author: gorodar
changes:
- createTable:
tableName: attraction_sets
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: area_id
type: uuid
constraints:
foreignKeyName: fk_attraction_sets_area_id
references: areas(id)
nullable: false
- column:
name: name
type: varchar(255)
constraints:
nullable: false
- column:
name: status
type: varchar(16)
constraints:
nullable: false
- column:
name: created_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- column:
name: updated_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- changeSet:
id: 003-attraction-sets-check-status
author: gorodar
comment: CHECK-констрейнт нельзя выразить нативным change-типом Liquibase (addCheckConstraint — платный) — осознанное sql-исключение
changes:
- sql:
dbms: postgresql
sql: alter table attraction_sets add constraint ck_attraction_sets_status check (status in ('DRAFT', 'ACTIVE', 'ARCHIVED'))
rollback:
- sql:
dbms: postgresql
sql: alter table attraction_sets drop constraint ck_attraction_sets_status
- changeSet:
id: 003-attraction-sets-unique-active
author: gorodar
comment: Partial unique index (WHERE) не поддержан createIndex — осознанное sql-исключение
changes:
- sql:
dbms: postgresql
sql: create unique index uq_attraction_sets_active_area on attraction_sets (area_id) where status = 'ACTIVE'
rollback:
- sql:
dbms: postgresql
sql: drop index uq_attraction_sets_active_area
- changeSet:
id: 003-attraction-sets-index-area
author: gorodar
changes:
- createIndex:
indexName: idx_attraction_sets_area_id
tableName: attraction_sets
columns:
- column:
name: area_id
- changeSet:
id: 003-attraction-set-items
author: gorodar
changes:
- createTable:
tableName: attraction_set_items
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: set_id
type: uuid
constraints:
foreignKeyName: fk_attraction_set_items_set_id
references: attraction_sets(id)
nullable: false
- column:
name: attraction_id
type: uuid
constraints:
foreignKeyName: fk_attraction_set_items_attraction_id
references: attractions(id)
nullable: false
- column:
name: created_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- addUniqueConstraint:
tableName: attraction_set_items
columnNames: set_id, attraction_id
constraintName: uq_attraction_set_items
- changeSet:
id: 003-attraction-set-items-indexes
author: gorodar
changes:
- createIndex:
indexName: idx_attraction_set_items_set_id
tableName: attraction_set_items
columns:
- column:
name: set_id
- createIndex:
indexName: idx_attraction_set_items_attraction_id
tableName: attraction_set_items
columns:
- column:
name: attraction_id
@@ -1,17 +0,0 @@
--liquibase formatted sql
--changeset gorodar:004-attraction-users-visits
create table attraction_users_visits (
id uuid primary key,
user_id varchar(64) not null,
attraction_id uuid not null references attractions (id),
visited_at timestamp not null default (now() at time zone 'utc'),
verdict varchar(16) not null,
confidence numeric(5, 4),
probe_sha256 varchar(64),
constraint uq_visits_user_attraction unique (user_id, attraction_id)
);
--changeset gorodar:004-visits-indexes
create index idx_visits_user_id on attraction_users_visits (user_id);
create index idx_visits_attraction_id on attraction_users_visits (attraction_id);
@@ -0,0 +1,63 @@
databaseChangeLog:
- changeSet:
id: 004-attraction-users-visits
author: gorodar
changes:
- createTable:
tableName: attraction_users_visits
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: user_id
type: varchar(64)
constraints:
nullable: false
- column:
name: attraction_id
type: uuid
constraints:
foreignKeyName: fk_attraction_users_visits_attraction_id
references: attractions(id)
nullable: false
- column:
name: visited_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- column:
name: verdict
type: varchar(16)
constraints:
nullable: false
- column:
name: confidence
type: numeric(5,4)
- column:
name: probe_sha256
type: varchar(64)
- addUniqueConstraint:
tableName: attraction_users_visits
columnNames: user_id, attraction_id
constraintName: uq_visits_user_attraction
- changeSet:
id: 004-visits-indexes
author: gorodar
changes:
- createIndex:
indexName: idx_visits_user_id
tableName: attraction_users_visits
columns:
- column:
name: user_id
- createIndex:
indexName: idx_visits_attraction_id
tableName: attraction_users_visits
columns:
- column:
name: attraction_id
@@ -0,0 +1,176 @@
databaseChangeLog:
- changeSet:
id: 005-users
author: gorodar
changes:
- createTable:
tableName: users
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: email
type: varchar(255)
constraints:
nullable: false
- column:
name: created_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- column:
name: updated_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- addUniqueConstraint:
tableName: users
columnNames: email
constraintName: uq_users_email
- changeSet:
id: 005-user-roles
author: gorodar
changes:
- createTable:
tableName: user_roles
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: user_id
type: uuid
constraints:
foreignKeyName: fk_user_roles_user_id
references: users(id)
nullable: false
- column:
name: role
type: varchar(64)
constraints:
nullable: false
- column:
name: created_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- addUniqueConstraint:
tableName: user_roles
columnNames: user_id, role
constraintName: uq_user_roles
- createIndex:
indexName: idx_user_roles_user_id
tableName: user_roles
columns:
- column:
name: user_id
- changeSet:
id: 005-auth-codes
author: gorodar
changes:
- createTable:
tableName: auth_codes
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: user_id
type: uuid
constraints:
foreignKeyName: fk_auth_codes_user_id
references: users(id)
nullable: false
- column:
name: code_hash
type: varchar(64)
constraints:
nullable: false
- column:
name: expires_at
type: timestamp
constraints:
nullable: false
- column:
name: attempts
type: integer
defaultValueNumeric: 0
constraints:
nullable: false
- column:
name: used_at
type: timestamp
- column:
name: created_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- createIndex:
indexName: idx_auth_codes_user_id
tableName: auth_codes
columns:
- column:
name: user_id
- changeSet:
id: 005-refresh-tokens
author: gorodar
changes:
- createTable:
tableName: refresh_tokens
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
- column:
name: user_id
type: uuid
constraints:
foreignKeyName: fk_refresh_tokens_user_id
references: users(id)
nullable: false
- column:
name: token_hash
type: varchar(64)
constraints:
nullable: false
- column:
name: expires_at
type: timestamp
constraints:
nullable: false
- column:
name: revoked_at
type: timestamp
- column:
name: created_at
type: timestamp
defaultValueComputed: "(now() at time zone 'utc')"
constraints:
nullable: false
- addUniqueConstraint:
tableName: refresh_tokens
columnNames: token_hash
constraintName: uq_refresh_tokens_hash
- createIndex:
indexName: idx_refresh_tokens_user_id
tableName: refresh_tokens
columns:
- column:
name: user_id
@@ -1,9 +1,11 @@
databaseChangeLog:
- include:
file: db/changelog/changelogs/001-create-areas.sql
file: db/changelog/changelogs/001-create-areas.yaml
- include:
file: db/changelog/changelogs/002-create-attractions.sql
file: db/changelog/changelogs/002-create-attractions.yaml
- include:
file: db/changelog/changelogs/003-create-attraction-sets.sql
file: db/changelog/changelogs/003-create-attraction-sets.yaml
- include:
file: db/changelog/changelogs/004-create-attraction-users-visits.sql
file: db/changelog/changelogs/004-create-attraction-users-visits.yaml
- include:
file: db/changelog/changelogs/005-create-auth.yaml
@@ -0,0 +1,219 @@
package ru.gorodar.auth;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import ru.gorodar.auth.TokenService.IssuedAccessToken;
import ru.gorodar.config.AuthProperties;
import ru.gorodar.dao.AuthCodeRepository;
import ru.gorodar.dao.RefreshTokenRepository;
import ru.gorodar.dao.UserRepository;
import ru.gorodar.dao.UserRoleRepository;
import ru.gorodar.dao.entity.AuthCode;
import ru.gorodar.dao.entity.RefreshToken;
import ru.gorodar.dao.entity.User;
import ru.gorodar.dao.entity.UserRole;
import ru.gorodar.exception.ApiException;
import ru.gorodar.exception.ErrorCode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AuthServiceTest {
private static final String EMAIL = "user@example.com";
private static final String CODE = "123456";
private final UUID userId = UUID.randomUUID();
@Mock
private UserRepository userRepository;
@Mock
private UserRoleRepository userRoleRepository;
@Mock
private AuthCodeRepository authCodeRepository;
@Mock
private RefreshTokenRepository refreshTokenRepository;
@Mock
private TokenService tokenService;
@Mock
private MailCodeSender mailCodeSender;
private AuthProperties properties;
@InjectMocks
private AuthService service;
@BeforeEach
void setUp() {
properties = new AuthProperties("http://localhost:8080", Duration.ofHours(24), Duration.ofDays(30),
Duration.ofMinutes(10), Duration.ofSeconds(60), Path.of("keys"), false, "noreply");
service = new AuthService(userRepository, userRoleRepository, authCodeRepository,
refreshTokenRepository, tokenService, mailCodeSender, properties);
}
@Test
void requestCodeCreatesMissingUserAndStoresHashedCode() {
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.empty());
User created = user();
when(userRepository.save(any(User.class))).thenReturn(created);
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.empty());
service.requestCode(EMAIL);
verify(userRepository).save(any(User.class));
verify(mailCodeSender).sendCode(eq(EMAIL), anyString());
ArgumentCaptor<AuthCode> codeCaptor = ArgumentCaptor.forClass(AuthCode.class);
verify(authCodeRepository).save(codeCaptor.capture());
assertThat(codeCaptor.getValue().getCodeHash()).hasSize(64);
assertThat(codeCaptor.getValue().getExpiresAt())
.isAfter(LocalDateTime.now(ZoneOffset.UTC).plus(Duration.ofMinutes(9)));
}
@Test
void requestCodeThrottledWithinResendInterval() {
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.of(user()));
AuthCode recent = new AuthCode();
recent.setCreatedAt(LocalDateTime.now(ZoneOffset.UTC).minusSeconds(10));
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.of(recent));
ApiException error = assertThrows(ApiException.class, () -> service.requestCode(EMAIL));
assertThat(error.getCode()).isEqualTo(ErrorCode.AUTH_CODE_RATE_LIMITED);
verify(authCodeRepository, never()).save(any(AuthCode.class));
verify(mailCodeSender, never()).sendCode(anyString(), anyString());
}
@Test
void tokenByEmailCodeIssuesTokensAndMarksCodeUsed() {
User user = user();
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.of(user));
AuthCode authCode = activeCode();
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.of(authCode));
stubIssueTokens(user);
AuthService.IssuedTokens tokens = service.tokenByEmailCode(EMAIL, CODE);
assertThat(tokens.accessToken()).isEqualTo("jwt");
assertThat(tokens.refreshToken()).isNotBlank();
assertThat(authCode.getUsedAt()).isNotNull();
verify(refreshTokenRepository).save(any(RefreshToken.class));
}
@Test
void wrongCodeCountsAttemptAndFails() {
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.of(user()));
AuthCode authCode = activeCode();
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.of(authCode));
ApiException error = assertThrows(ApiException.class,
() -> service.tokenByEmailCode(EMAIL, "000000"));
assertThat(error.getCode()).isEqualTo(ErrorCode.INVALID_GRANT);
assertThat(authCode.getAttempts()).isEqualTo(1);
assertThat(authCode.getUsedAt()).isNull();
}
@Test
void expiredCodeRejected() {
when(userRepository.findByEmail(EMAIL)).thenReturn(Optional.of(user()));
AuthCode expired = activeCode();
expired.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).minusMinutes(1));
when(authCodeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId)).thenReturn(Optional.of(expired));
ApiException error = assertThrows(ApiException.class,
() -> service.tokenByEmailCode(EMAIL, CODE));
assertThat(error.getCode()).isEqualTo(ErrorCode.INVALID_GRANT);
}
@Test
void tokenByRefreshRotatesOldToken() {
User user = user();
RefreshToken refresh = new RefreshToken();
refresh.setId(UUID.randomUUID());
refresh.setUser(user);
refresh.setTokenHash(sha256Hex("refresh-value"));
refresh.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).plusDays(1));
when(refreshTokenRepository.findByTokenHash(sha256Hex("refresh-value"))).thenReturn(Optional.of(refresh));
stubIssueTokens(user);
AuthService.IssuedTokens tokens = service.tokenByRefresh("refresh-value");
assertThat(tokens.accessToken()).isEqualTo("jwt");
assertThat(refresh.getRevokedAt()).isNotNull();
// два сохранения: отзыв старого refresh-токена и запись нового
verify(refreshTokenRepository, times(2)).save(any(RefreshToken.class));
}
@Test
void revokedRefreshRejected() {
RefreshToken refresh = new RefreshToken();
refresh.setUser(user());
refresh.setTokenHash(sha256Hex("refresh-value"));
refresh.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).plusDays(1));
refresh.setRevokedAt(LocalDateTime.now(ZoneOffset.UTC).minusMinutes(1));
when(refreshTokenRepository.findByTokenHash(sha256Hex("refresh-value"))).thenReturn(Optional.of(refresh));
ApiException error = assertThrows(ApiException.class, () -> service.tokenByRefresh("refresh-value"));
assertThat(error.getCode()).isEqualTo(ErrorCode.INVALID_GRANT);
}
private void stubIssueTokens(User user) {
when(userRoleRepository.findByUserId(userId)).thenReturn(List.of());
when(tokenService.issueAccessToken(eq(user), any()))
.thenReturn(new IssuedAccessToken("jwt", 86400));
}
private User user() {
User user = new User();
user.setId(userId);
user.setEmail(EMAIL);
return user;
}
private AuthCode activeCode() {
AuthCode authCode = new AuthCode();
authCode.setId(UUID.randomUUID());
authCode.setUser(user());
authCode.setCodeHash(sha256Hex(CODE));
authCode.setExpiresAt(LocalDateTime.now(ZoneOffset.UTC).plusMinutes(10));
authCode.setAttempts(0);
return authCode;
}
private String sha256Hex(String value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,48 @@
package ru.gorodar.auth;
import com.nimbusds.jwt.SignedJWT;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import ru.gorodar.config.AuthProperties;
import ru.gorodar.dao.entity.User;
import java.nio.file.Path;
import java.time.Duration;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
class TokenServiceTest {
@TempDir
Path tempDir;
@Test
void accessTokenCarriesOidcShapedClaims() throws ParseException {
AuthProperties properties = new AuthProperties("http://localhost:8080", Duration.ofHours(24),
Duration.ofDays(30), Duration.ofMinutes(10), Duration.ofSeconds(60), tempDir, false, "noreply");
TokenService tokenService = new TokenService(new JwkKeys(properties), properties);
User user = new User();
user.setId(UUID.randomUUID());
user.setEmail("user@example.com");
TokenService.IssuedAccessToken issued = tokenService.issueAccessToken(user, List.of("manage_area"));
assertThat(issued.expiresInSeconds()).isEqualTo(Duration.ofHours(24).toSeconds());
SignedJWT jwt = SignedJWT.parse(issued.token());
var claims = jwt.getJWTClaimsSet();
assertThat(claims.getIssuer()).isEqualTo("http://localhost:8080");
assertThat(claims.getSubject()).isEqualTo(user.getId().toString());
assertThat(claims.getAudience()).containsExactly("gorodar");
assertThat(claims.getClaim("email")).isEqualTo("user@example.com");
Map<String, Object> resourceAccess = (Map<String, Object>) claims.getClaim("resource_access");
assertThat(resourceAccess).isNotNull();
Map<String, Object> clientAccess = (Map<String, Object>) resourceAccess.get("gorodar");
assertThat((List<String>) clientAccess.get("roles")).containsExactly("manage_area");
assertThat(claims.getExpirationTime().getTime() - claims.getIssueTime().getTime())
.isEqualTo(Duration.ofHours(24).toMillis());
}
}
@@ -10,10 +10,10 @@ import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
class KeycloakJwtAuthenticationConverterTest {
class ClientRolesJwtAuthenticationConverterTest {
private final KeycloakJwtAuthenticationConverter converter =
new KeycloakJwtAuthenticationConverter("gorodar");
private final ClientRolesJwtAuthenticationConverter converter =
new ClientRolesJwtAuthenticationConverter("gorodar");
@Test
void convertsClientRolesToAuthorities() {