ЛР 4 — БВТ2304 — ivanstorozhev — на 3

Байты вложения лежат в общем S3, метаданные — в PostgreSQL, поэтому остановка загрузившей реплики не мешает другой отдать тот же файл. Idempotency-Key не даёт повторной отправке создать второе сообщение.

Автор / группа: ivanstorozhev, БВТ2304
Целевая оценка (3/4/5): 3
Трек 5, если заявлен: не заявлен

Что реализовано и что перенесено: из lab3 перенесены Spring Boot API, PostgreSQL, Redis-кэш сессий, Argon2id, Liquibase через одноразовый сервис migrate, HAProxy без sticky session, две реплики, X-Instance-Id, обязательный Idempotency-Key, scripts/stop-one.sh и scripts/restart.sh. Добавлены приватный SeaweedFS, таблица attachments, связь сообщения с вложениями и скачивание оригинала через API. Ключ объекта назначает сервер, имя файла только отображается.

Команды запуска из чистого clone:
cp .env.example .env
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build
curl -fsS http://127.0.0.1:8080/health/ready
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
docker compose --env-file .env start api

Результаты проверок и ссылка на REPORT.md: подробности и числа в REPORT.md
make check — PASS: offline skeleton structure, local refs and Python syntax.
make test — PASS: lab4 public API scenario.
make test-persistence ACTION_SCRIPT=scripts/restart.sh — PASS: persistence preserved confirmed data and existing session.
make test-failover ACTION_SCRIPT=scripts/stop-one.sh — PASS: две реплики до отказа, восстановление записи за 1.665 с, 119 успешных записей и 1 ошибка перехода.
mvn -q test в backend/ — 16 тестов без ошибок, включая PNG по содержимому, подмену MIME, опасное имя файла и чужое вложение.
Анонимный GET объекта в сети стенда — HTTP 403.

Ограничения / известные ошибки: трек 5 и полный уровень 4 не делались. Один Docker-хост, единственные PostgreSQL, Redis, SeaweedFS и HAProxy остаются точками отказа. Если процесс умер после PUT и до COMMIT, объект может остаться без строки в БД. Ключ S3 один, с правами Admin. Пик памяти при параллельных загрузках не измерялся. Пока HAProxy не снял backend, часть запросов на останавливаемую реплику завершается ошибкой соединения; повтор с тем же Idempotency-Key безопасен для отправки сообщения.

Источники и использование ИИ: контракт contracts/openapi.json и contracts/README.md; код lab3; Spring Boot 4.1.1, Spring Data JPA, spring-security-crypto, Spring Data Redis, Liquibase, Actuator, MapStruct 1.6.3, OpenAPI Generator 7.17.0, AWS SDK for Java 2.31.50, Bouncy Castle, PostgreSQL 16.10, Redis 7.4.6, HAProxy 3.2.6, SeaweedFS 4.52, Testcontainers. Реализация собрана в Cursor.

Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
Контракт и публичные тесты не ослаблены.
make check и make test выполнены; приложен реальный вывод.
Сценарии отказов своего уровня воспроизведены.
Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
This commit is contained in:
ivanstorozhev
2026-11-05 22:02:47 +03:00
parent ec540a1a72
commit 0450ba42ad
84 changed files with 4789 additions and 22 deletions
@@ -0,0 +1,20 @@
package ru.mtuci.messenger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@SpringBootApplication
public class MessengerApplication {
public static void main(String[] args) {
SpringApplication.run(MessengerApplication.class, args);
}
@Bean
PasswordEncoder passwordEncoder() {
return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
}
}
@@ -0,0 +1,53 @@
package ru.mtuci.messenger.api.attachment;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.mtuci.messenger.api.model.Attachment;
import ru.mtuci.messenger.domain.AttachmentEntity;
import ru.mtuci.messenger.service.AttachmentService;
import ru.mtuci.messenger.web.BearerAuthFilter;
import java.io.IOException;
import java.util.UUID;
@RestController
public class AttachmentController {
private final AttachmentService attachments;
public AttachmentController(AttachmentService attachments) {
this.attachments = attachments;
}
@PostMapping(value = "/api/v1/chats/{chatId}/attachments", consumes = {"image/png", "image/jpeg"})
public ResponseEntity<Attachment> upload(HttpServletRequest request, @PathVariable UUID chatId,
@RequestParam("filename") String filename) throws IOException {
long length = request.getContentLengthLong();
Attachment created = attachments.upload(
BearerAuthFilter.userId(request), chatId, filename, request.getContentType(), length, request.getInputStream());
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
@GetMapping("/api/v1/attachments/{attachmentId}")
public Attachment get(HttpServletRequest request, @PathVariable UUID attachmentId) {
return attachments.get(BearerAuthFilter.userId(request), attachmentId);
}
@GetMapping("/api/v1/attachments/{attachmentId}/content")
public ResponseEntity<InputStreamResource> content(HttpServletRequest request, @PathVariable UUID attachmentId,
@RequestParam(required = false) String variant) {
AttachmentEntity attachment = attachments.content(BearerAuthFilter.userId(request), attachmentId, variant);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(attachment.getContentType()))
.contentLength(attachment.getSizeBytes())
.body(new InputStreamResource(attachments.open(attachment)));
}
}
@@ -0,0 +1,51 @@
package ru.mtuci.messenger.api.chat;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Size;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.mtuci.messenger.api.model.Chat;
import ru.mtuci.messenger.api.model.ChatPage;
import ru.mtuci.messenger.api.model.CreateChat;
import ru.mtuci.messenger.service.ChatService;
import ru.mtuci.messenger.web.BearerAuthFilter;
import java.util.UUID;
@Validated
@RestController
public class ChatController {
private final ChatService chats;
public ChatController(ChatService chats) {
this.chats = chats;
}
@PostMapping("/api/v1/chats")
public ResponseEntity<Chat> create(HttpServletRequest request, @Valid @RequestBody CreateChat body) {
return ResponseEntity.status(HttpStatus.CREATED).body(chats.create(BearerAuthFilter.userId(request), body));
}
@GetMapping("/api/v1/chats")
public ChatPage list(HttpServletRequest request,
@RequestParam(required = false) @Min(1) @Max(100) Integer limit,
@RequestParam(required = false) @Size(min = 1) String cursor) {
return chats.list(BearerAuthFilter.userId(request), limit, cursor);
}
@GetMapping("/api/v1/chats/{chatId}")
public Chat get(HttpServletRequest request, @PathVariable UUID chatId) {
return chats.get(BearerAuthFilter.userId(request), chatId);
}
}
@@ -0,0 +1,44 @@
package ru.mtuci.messenger.api.health;
import org.springframework.boot.health.actuate.endpoint.HealthDescriptor;
import org.springframework.boot.health.actuate.endpoint.HealthEndpoint;
import org.springframework.boot.health.contributor.Status;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.mtuci.messenger.api.model.Health;
import ru.mtuci.messenger.exception.UnavailableException;
@RestController
public class HealthController {
private final HealthEndpoint healthEndpoint;
public HealthController(HealthEndpoint healthEndpoint) {
this.healthEndpoint = healthEndpoint;
}
@GetMapping("/health/live")
public Health live() {
if (!up("liveness")) {
throw new IllegalStateException("liveness");
}
return ok();
}
@GetMapping("/health/ready")
public Health ready() {
if (!up("readiness")) {
throw new UnavailableException("Сервис не готов");
}
return ok();
}
private boolean up(String path) {
HealthDescriptor descriptor = healthEndpoint.healthForPath(path);
return descriptor != null && Status.UP.equals(descriptor.getStatus());
}
private Health ok() {
return new Health(Health.StatusEnum.OK);
}
}
@@ -0,0 +1,50 @@
package ru.mtuci.messenger.api.message;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Size;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.mtuci.messenger.api.model.CreateMessage;
import ru.mtuci.messenger.api.model.Message;
import ru.mtuci.messenger.api.model.MessagePage;
import jakarta.servlet.http.HttpServletRequest;
import ru.mtuci.messenger.service.MessageService;
import ru.mtuci.messenger.web.BearerAuthFilter;
import java.util.UUID;
@Validated
@RestController
public class MessageController {
private final MessageService messageService;
public MessageController(MessageService messageService) {
this.messageService = messageService;
}
@PostMapping("/api/v1/chats/{chatId}/messages")
public ResponseEntity<Message> create(HttpServletRequest request, @PathVariable UUID chatId,
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey,
@Valid @RequestBody CreateMessage body) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(messageService.create(BearerAuthFilter.userId(request), chatId, idempotencyKey, body));
}
@GetMapping("/api/v1/chats/{chatId}/messages")
public MessagePage list(HttpServletRequest request, @PathVariable UUID chatId,
@RequestParam(required = false) @Min(1) @Max(100) Integer limit,
@RequestParam(required = false) @Size(min = 1) String cursor) {
return messageService.list(BearerAuthFilter.userId(request), chatId, limit, cursor);
}
}
@@ -0,0 +1,47 @@
package ru.mtuci.messenger.api.user;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ru.mtuci.messenger.api.model.CreateUser;
import ru.mtuci.messenger.api.model.Session;
import ru.mtuci.messenger.api.model.User;
import ru.mtuci.messenger.service.UserService;
import ru.mtuci.messenger.web.BearerAuthFilter;
@RestController
public class UserController {
private final UserService users;
public UserController(UserService users) {
this.users = users;
}
@PostMapping("/api/v1/users")
public ResponseEntity<User> register(@Valid @RequestBody CreateUser request) {
return ResponseEntity.status(HttpStatus.CREATED).body(users.register(request));
}
@GetMapping("/api/v1/users/me")
public User me(HttpServletRequest request) {
return users.current(BearerAuthFilter.userId(request));
}
@PostMapping("/api/v1/auth/sessions")
public ResponseEntity<Session> login(HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).body(users.login(request.getHeader("Authorization")));
}
@DeleteMapping("/api/v1/auth/sessions/current")
public ResponseEntity<Void> logout(HttpServletRequest request) {
users.revoke((String) request.getAttribute(BearerAuthFilter.TOKEN));
return ResponseEntity.noContent().build();
}
}
@@ -0,0 +1,61 @@
package ru.mtuci.messenger.cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
/**
* Кэш Bearer-сессий: session:{sha256(token)} -> userId, TTL = остаток жизни сессии.
* Источник истины — таблица sessions; при ошибке Redis вызывающий идёт в PostgreSQL.
*/
@Component
public class SessionCache {
private static final Logger log = LoggerFactory.getLogger(SessionCache.class);
private final StringRedisTemplate redis;
public SessionCache(StringRedisTemplate redis) {
this.redis = redis;
}
public Optional<UUID> find(String tokenHash) {
try {
return Optional.ofNullable(redis.opsForValue().get(key(tokenHash))).map(UUID::fromString);
} catch (DataAccessException exception) {
log.warn("session cache bypass: {}", exception.getClass().getSimpleName());
return Optional.empty();
}
}
public void put(String tokenHash, UUID userId, Instant expiresAt) {
Duration ttl = Duration.between(Instant.now(), expiresAt);
if (ttl.isNegative() || ttl.isZero()) {
return;
}
try {
redis.opsForValue().set(key(tokenHash), userId.toString(), ttl);
} catch (DataAccessException exception) {
log.warn("session cache write skipped: {}", exception.getClass().getSimpleName());
}
}
public void evict(String tokenHash) {
try {
redis.delete(key(tokenHash));
} catch (DataAccessException exception) {
log.warn("session cache evict skipped: {}", exception.getClass().getSimpleName());
}
}
private static String key(String tokenHash) {
return "session:" + tokenHash;
}
}
@@ -0,0 +1,111 @@
package ru.mtuci.messenger.domain;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
@Entity
@Table(name = "attachments")
public class AttachmentEntity {
@Id
private UUID id;
@Column(name = "chat_id", nullable = false)
private UUID chatId;
@Column(name = "owner_id", nullable = false)
private UUID ownerId;
@Column(nullable = false, length = 255)
private String filename;
@Column(name = "content_type", nullable = false, length = 32)
private String contentType;
@Column(name = "size_bytes", nullable = false)
private long sizeBytes;
@Column(nullable = false, length = 64)
private String sha256;
@Column(name = "object_key", nullable = false, length = 80)
private String objectKey;
@Column(nullable = false, length = 16)
private String status;
@Column(name = "created_at", nullable = false)
private Instant createdAt;
@Column(name = "updated_at", nullable = false)
private Instant updatedAt;
protected AttachmentEntity() {
}
public AttachmentEntity(UUID id, UUID chatId, UUID ownerId, String filename, String contentType, long sizeBytes,
String sha256, String objectKey) {
Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS);
this.id = id;
this.chatId = chatId;
this.ownerId = ownerId;
this.filename = filename;
this.contentType = contentType;
this.sizeBytes = sizeBytes;
this.sha256 = sha256;
this.objectKey = objectKey;
this.status = "ready";
this.createdAt = now;
this.updatedAt = now;
}
public UUID getId() {
return id;
}
public UUID getChatId() {
return chatId;
}
public UUID getOwnerId() {
return ownerId;
}
public String getFilename() {
return filename;
}
public String getContentType() {
return contentType;
}
public long getSizeBytes() {
return sizeBytes;
}
public String getSha256() {
return sha256;
}
public String getObjectKey() {
return objectKey;
}
public String getStatus() {
return status;
}
public Instant getCreatedAt() {
return createdAt;
}
public Instant getUpdatedAt() {
return updatedAt;
}
}
@@ -0,0 +1,45 @@
package ru.mtuci.messenger.domain;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
@Entity
@Table(name = "chats")
public class ChatEntity {
@Id
private UUID id;
@Column(nullable = false, length = 100)
private String title;
@Column(name = "created_at", nullable = false)
private Instant createdAt;
protected ChatEntity() {
}
public ChatEntity(String title) {
this.id = UUID.randomUUID();
this.title = title;
this.createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
}
public UUID getId() {
return id;
}
public String getTitle() {
return title;
}
public Instant getCreatedAt() {
return createdAt;
}
}
@@ -0,0 +1,47 @@
package ru.mtuci.messenger.domain;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.IdClass;
import jakarta.persistence.Table;
import java.util.UUID;
@Entity
@Table(name = "chat_members")
@IdClass(ChatMemberId.class)
public class ChatMemberEntity {
@Id
@Column(name = "chat_id", nullable = false)
private UUID chatId;
@Id
@Column(name = "user_id", nullable = false)
private UUID userId;
@Column(name = "ordinal", nullable = false)
private int ordinal;
protected ChatMemberEntity() {
}
public ChatMemberEntity(UUID chatId, UUID userId, int ordinal) {
this.chatId = chatId;
this.userId = userId;
this.ordinal = ordinal;
}
public UUID getChatId() {
return chatId;
}
public UUID getUserId() {
return userId;
}
public int getOrdinal() {
return ordinal;
}
}
@@ -0,0 +1,34 @@
package ru.mtuci.messenger.domain;
import java.io.Serializable;
import java.util.UUID;
public class ChatMemberId implements Serializable {
private UUID chatId;
private UUID userId;
public ChatMemberId() {
}
public ChatMemberId(UUID chatId, UUID userId) {
this.chatId = chatId;
this.userId = userId;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ChatMemberId that)) {
return false;
}
return chatId.equals(that.chatId) && userId.equals(that.userId);
}
@Override
public int hashCode() {
return chatId.hashCode() * 31 + userId.hashCode();
}
}
@@ -0,0 +1,69 @@
package ru.mtuci.messenger.domain;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Instant;
import java.util.UUID;
@Entity
@Table(name = "idempotency_records")
public class IdempotencyRecord {
@Id
private UUID id;
@Column(name = "user_id", nullable = false)
private UUID userId;
@Column(name = "http_method", nullable = false, length = 8)
private String httpMethod;
@Column(nullable = false, length = 256)
private String path;
@Column(name = "idempotency_key", nullable = false, length = 128)
private String idempotencyKey;
@Column(name = "request_hash", nullable = false, length = 64)
private String requestHash;
@Column(name = "message_id", nullable = false)
private UUID messageId;
@Column(name = "created_at", nullable = false)
private Instant createdAt;
@Column(name = "expires_at", nullable = false)
private Instant expiresAt;
protected IdempotencyRecord() {
}
public IdempotencyRecord(UUID userId, String httpMethod, String path, String idempotencyKey, String requestHash,
UUID messageId, Instant createdAt, Instant expiresAt) {
this.id = UUID.randomUUID();
this.userId = userId;
this.httpMethod = httpMethod;
this.path = path;
this.idempotencyKey = idempotencyKey;
this.requestHash = requestHash;
this.messageId = messageId;
this.createdAt = createdAt;
this.expiresAt = expiresAt;
}
public UUID getMessageId() {
return messageId;
}
public String getRequestHash() {
return requestHash;
}
public Instant getExpiresAt() {
return expiresAt;
}
}
@@ -0,0 +1,79 @@
package ru.mtuci.messenger.domain;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OrderColumn;
import jakarta.persistence.Table;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Entity
@Table(name = "messages")
public class MessageEntity {
@Id
private UUID id;
@Column(name = "chat_id", nullable = false)
private UUID chatId;
@Column(name = "sender_id", nullable = false)
private UUID senderId;
@Column(nullable = false, length = 4000)
private String text;
@Column(name = "created_at", nullable = false)
private Instant createdAt;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "message_attachments", joinColumns = @JoinColumn(name = "message_id"))
@OrderColumn(name = "sort_order")
@Column(name = "attachment_id", nullable = false)
private List<UUID> attachmentIds = new ArrayList<>();
protected MessageEntity() {
}
public MessageEntity(UUID chatId, UUID senderId, String text, List<UUID> attachmentIds) {
this.id = UUID.randomUUID();
this.chatId = chatId;
this.senderId = senderId;
this.text = text;
this.createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
this.attachmentIds = new ArrayList<>(attachmentIds);
}
public UUID getId() {
return id;
}
public UUID getChatId() {
return chatId;
}
public UUID getSenderId() {
return senderId;
}
public String getText() {
return text;
}
public Instant getCreatedAt() {
return createdAt;
}
public List<UUID> getAttachmentIds() {
return attachmentIds;
}
}
@@ -0,0 +1,53 @@
package ru.mtuci.messenger.domain;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
@Entity
@Table(name = "sessions")
public class SessionEntity {
@Id
private UUID id;
@Column(name = "token_hash", nullable = false, unique = true, length = 64)
private String tokenHash;
@Column(name = "user_id", nullable = false)
private UUID userId;
@Column(name = "expires_at", nullable = false)
private Instant expiresAt;
@Column(name = "revoked_at")
private Instant revokedAt;
@Column(name = "created_at", nullable = false)
private Instant createdAt;
protected SessionEntity() {
}
public SessionEntity(String tokenHash, UUID userId, Duration ttl) {
this.id = UUID.randomUUID();
this.tokenHash = tokenHash;
this.userId = userId;
this.createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
this.expiresAt = createdAt.plus(ttl);
}
public UUID getUserId() {
return userId;
}
public Instant getExpiresAt() {
return expiresAt;
}
}
@@ -0,0 +1,61 @@
package ru.mtuci.messenger.domain;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
@Entity
@Table(name = "users")
public class UserAccount {
@Id
private UUID id;
@Column(nullable = false, unique = true, length = 32)
private String username;
@Column(name = "display_name", nullable = false, length = 100)
private String displayName;
@Column(name = "password_hash", nullable = false, length = 255)
private String passwordHash;
@Column(name = "created_at", nullable = false)
private Instant createdAt;
protected UserAccount() {
}
public UserAccount(String username, String displayName, String passwordHash) {
this.id = UUID.randomUUID();
this.username = username;
this.displayName = displayName;
this.passwordHash = passwordHash;
this.createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
}
public UUID getId() {
return id;
}
public String getUsername() {
return username;
}
public String getDisplayName() {
return displayName;
}
public String getPasswordHash() {
return passwordHash;
}
public Instant getCreatedAt() {
return createdAt;
}
}
@@ -0,0 +1,24 @@
package ru.mtuci.messenger.exception;
import org.springframework.http.HttpStatus;
import ru.mtuci.messenger.api.model.ErrorError;
public class ApiException extends RuntimeException {
private final HttpStatus status;
private final ErrorError.CodeEnum code;
public ApiException(HttpStatus status, ErrorError.CodeEnum code, String message) {
super(message);
this.status = status;
this.code = code;
}
public HttpStatus status() {
return status;
}
public ErrorError.CodeEnum code() {
return code;
}
}
@@ -0,0 +1,11 @@
package ru.mtuci.messenger.exception;
import org.springframework.http.HttpStatus;
import ru.mtuci.messenger.api.model.ErrorError;
public class ConflictException extends ApiException {
public ConflictException(String message) {
super(HttpStatus.CONFLICT, ErrorError.CodeEnum.CONFLICT, message);
}
}
@@ -0,0 +1,11 @@
package ru.mtuci.messenger.exception;
import org.springframework.http.HttpStatus;
import ru.mtuci.messenger.api.model.ErrorError;
public class InvalidRequestException extends ApiException {
public InvalidRequestException(String message) {
super(HttpStatus.BAD_REQUEST, ErrorError.CodeEnum.INVALID_REQUEST, message);
}
}
@@ -0,0 +1,11 @@
package ru.mtuci.messenger.exception;
import org.springframework.http.HttpStatus;
import ru.mtuci.messenger.api.model.ErrorError;
public class NotFoundException extends ApiException {
public NotFoundException() {
super(HttpStatus.NOT_FOUND, ErrorError.CodeEnum.NOT_FOUND, "Объект не найден");
}
}
@@ -0,0 +1,11 @@
package ru.mtuci.messenger.exception;
import org.springframework.http.HttpStatus;
import ru.mtuci.messenger.api.model.ErrorError;
public class PayloadTooLargeException extends ApiException {
public PayloadTooLargeException() {
super(HttpStatus.PAYLOAD_TOO_LARGE, ErrorError.CodeEnum.PAYLOAD_TOO_LARGE, "Файл слишком большой");
}
}
@@ -0,0 +1,26 @@
package ru.mtuci.messenger.exception;
import org.springframework.http.HttpStatus;
import ru.mtuci.messenger.api.model.ErrorError;
public class UnauthorizedException extends ApiException {
private final String challenge;
private UnauthorizedException(String challenge) {
super(HttpStatus.UNAUTHORIZED, ErrorError.CodeEnum.UNAUTHORIZED, "Требуется аутентификация");
this.challenge = challenge;
}
public static UnauthorizedException basic() {
return new UnauthorizedException("Basic realm=\"messenger\", charset=\"UTF-8\"");
}
public static UnauthorizedException bearer() {
return new UnauthorizedException("Bearer realm=\"messenger\"");
}
public String challenge() {
return challenge;
}
}
@@ -0,0 +1,11 @@
package ru.mtuci.messenger.exception;
import org.springframework.http.HttpStatus;
import ru.mtuci.messenger.api.model.ErrorError;
public class UnavailableException extends ApiException {
public UnavailableException(String message) {
super(HttpStatus.SERVICE_UNAVAILABLE, ErrorError.CodeEnum.UNAVAILABLE, message);
}
}
@@ -0,0 +1,11 @@
package ru.mtuci.messenger.exception;
import org.springframework.http.HttpStatus;
import ru.mtuci.messenger.api.model.ErrorError;
public class UnsupportedMediaException extends ApiException {
public UnsupportedMediaException() {
super(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ErrorError.CodeEnum.UNSUPPORTED_MEDIA_TYPE, "Неподдерживаемый тип содержимого");
}
}
@@ -0,0 +1,20 @@
package ru.mtuci.messenger.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.ReportingPolicy;
import ru.mtuci.messenger.api.model.Chat;
import ru.mtuci.messenger.domain.ChatEntity;
import java.util.List;
import java.util.UUID;
@Mapper(componentModel = "spring", uses = TimeMapper.class, unmappedTargetPolicy = ReportingPolicy.ERROR)
public interface ChatMapper {
@Mapping(target = "id", source = "chat.id")
@Mapping(target = "title", source = "chat.title")
@Mapping(target = "createdAt", source = "chat.createdAt")
@Mapping(target = "memberIds", source = "memberIds")
Chat toModel(ChatEntity chat, List<UUID> memberIds);
}
@@ -0,0 +1,12 @@
package ru.mtuci.messenger.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
import ru.mtuci.messenger.api.model.Message;
import ru.mtuci.messenger.domain.MessageEntity;
@Mapper(componentModel = "spring", uses = TimeMapper.class, unmappedTargetPolicy = ReportingPolicy.ERROR)
public interface MessageMapper {
Message toModel(MessageEntity message);
}
@@ -0,0 +1,15 @@
package ru.mtuci.messenger.mapper;
import org.mapstruct.Mapper;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
@Mapper(componentModel = "spring")
public interface TimeMapper {
default OffsetDateTime map(Instant instant) {
return instant == null ? null : instant.atOffset(ZoneOffset.UTC);
}
}
@@ -0,0 +1,19 @@
package ru.mtuci.messenger.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.ReportingPolicy;
import ru.mtuci.messenger.api.model.Session;
import ru.mtuci.messenger.api.model.User;
import ru.mtuci.messenger.domain.UserAccount;
import java.time.Instant;
@Mapper(componentModel = "spring", uses = TimeMapper.class, unmappedTargetPolicy = ReportingPolicy.ERROR)
public interface UserMapper {
User toModel(UserAccount user);
@Mapping(target = "tokenType", expression = "java(ru.mtuci.messenger.api.model.Session.TokenTypeEnum.BEARER)")
Session toSession(String token, Instant expiresAt, UserAccount user);
}
@@ -0,0 +1,34 @@
package ru.mtuci.messenger.migrate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("migrate")
public class MigrateExit implements ApplicationRunner {
private final ConfigurableApplicationContext context;
public MigrateExit(ConfigurableApplicationContext context) {
this.context = context;
}
@Override
public void run(ApplicationArguments args) {
Thread exit = new Thread(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
int code = SpringApplication.exit(context, () -> 0);
System.exit(code);
}, "migrate-exit");
exit.setDaemon(false);
exit.start();
}
}
@@ -0,0 +1,9 @@
package ru.mtuci.messenger.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.mtuci.messenger.domain.AttachmentEntity;
import java.util.UUID;
public interface AttachmentRepository extends JpaRepository<AttachmentEntity, UUID> {
}
@@ -0,0 +1,18 @@
package ru.mtuci.messenger.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.mtuci.messenger.domain.ChatMemberEntity;
import ru.mtuci.messenger.domain.ChatMemberId;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
public interface ChatMemberRepository extends JpaRepository<ChatMemberEntity, ChatMemberId> {
boolean existsByChatIdAndUserId(UUID chatId, UUID userId);
List<ChatMemberEntity> findByChatIdOrderByOrdinalAsc(UUID chatId);
List<ChatMemberEntity> findByChatIdInOrderByOrdinalAsc(Collection<UUID> chatIds);
}
@@ -0,0 +1,30 @@
package ru.mtuci.messenger.repository;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.mtuci.messenger.domain.ChatEntity;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public interface ChatRepository extends JpaRepository<ChatEntity, UUID> {
@Query("""
select c from ChatEntity c
where c.id in (select m.chatId from ChatMemberEntity m where m.userId = :userId)
order by c.createdAt asc, c.id asc
""")
List<ChatEntity> findFirst(UUID userId, Pageable pageable);
@Query(value = """
select c.* from chats c
where c.id in (select m.chat_id from chat_members m where m.user_id = :userId)
and (c.created_at, c.id) > (:createdAt, :id)
order by c.created_at asc, c.id asc
""", nativeQuery = true)
List<ChatEntity> findAfter(UUID userId, Instant createdAt, UUID id, Pageable pageable);
long countByTitle(String title);
}
@@ -0,0 +1,13 @@
package ru.mtuci.messenger.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.mtuci.messenger.domain.IdempotencyRecord;
import java.util.Optional;
import java.util.UUID;
public interface IdempotencyRepository extends JpaRepository<IdempotencyRecord, UUID> {
Optional<IdempotencyRecord> findByUserIdAndHttpMethodAndPathAndIdempotencyKey(
UUID userId, String httpMethod, String path, String idempotencyKey);
}
@@ -0,0 +1,31 @@
package ru.mtuci.messenger.repository;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.mtuci.messenger.domain.MessageEntity;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public interface MessageRepository extends JpaRepository<MessageEntity, UUID> {
long countByChatId(UUID chatId);
@Query("""
select m from MessageEntity m
where m.chatId = :chatId
order by m.createdAt asc, m.id asc
""")
List<MessageEntity> findFirst(UUID chatId, Pageable pageable);
@Query(value = """
select * from messages
where chat_id = :chatId
and (created_at, id) > (:createdAt, :id)
order by created_at asc, id asc
""", nativeQuery = true)
List<MessageEntity> findAfter(UUID chatId, Instant createdAt, UUID id, Pageable pageable);
}
@@ -0,0 +1,28 @@
package ru.mtuci.messenger.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import ru.mtuci.messenger.domain.SessionEntity;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
public interface SessionRepository extends JpaRepository<SessionEntity, UUID> {
@Query("""
select s from SessionEntity s
where s.tokenHash = :tokenHash and s.revokedAt is null and s.expiresAt > :now
""")
Optional<SessionEntity> findActive(String tokenHash, Instant now);
@Transactional
@Modifying
@Query("""
update SessionEntity s set s.revokedAt = :now
where s.tokenHash = :tokenHash and s.revokedAt is null and s.expiresAt > :now
""")
int revoke(String tokenHash, Instant now);
}
@@ -0,0 +1,15 @@
package ru.mtuci.messenger.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.mtuci.messenger.domain.UserAccount;
import java.util.Collection;
import java.util.Optional;
import java.util.UUID;
public interface UserRepository extends JpaRepository<UserAccount, UUID> {
Optional<UserAccount> findByUsername(String username);
long countByIdIn(Collection<UUID> ids);
}
@@ -0,0 +1,173 @@
package ru.mtuci.messenger.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import ru.mtuci.messenger.api.model.Attachment;
import ru.mtuci.messenger.domain.AttachmentEntity;
import ru.mtuci.messenger.exception.InvalidRequestException;
import ru.mtuci.messenger.exception.NotFoundException;
import ru.mtuci.messenger.exception.PayloadTooLargeException;
import ru.mtuci.messenger.exception.UnsupportedMediaException;
import ru.mtuci.messenger.repository.AttachmentRepository;
import ru.mtuci.messenger.repository.ChatMemberRepository;
import ru.mtuci.messenger.storage.ObjectStorage;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.UUID;
@Service
public class AttachmentService {
private final AttachmentRepository attachments;
private final ChatMemberRepository members;
private final ObjectStorage storage;
private final TransactionTemplate transactions;
private final int maxBytes;
private final long maxPixels;
public AttachmentService(AttachmentRepository attachments, ChatMemberRepository members, ObjectStorage storage,
PlatformTransactionManager transactionManager,
@Value("${app.upload.max-bytes:10485760}") int maxBytes,
@Value("${app.upload.max-pixels:40000000}") long maxPixels) {
this.attachments = attachments;
this.members = members;
this.storage = storage;
this.transactions = new TransactionTemplate(transactionManager);
this.maxBytes = maxBytes;
this.maxPixels = maxPixels;
}
public Attachment upload(UUID actorId, UUID chatId, String filename, String contentType, long contentLength,
InputStream body) {
requireMember(chatId, actorId);
String displayName = filename(filename);
String declared = declaredType(contentType);
if (contentLength > maxBytes) {
throw new PayloadTooLargeException();
}
byte[] bytes;
try {
bytes = ImageFiles.readLimited(body, maxBytes);
} catch (PayloadTooLargeException tooLarge) {
throw tooLarge;
} catch (java.io.IOException exception) {
throw new ru.mtuci.messenger.exception.UnavailableException("Хранилище временно недоступно");
}
ImageFiles.Image image = ImageFiles.inspect(bytes, declared, maxPixels);
UUID id = UUID.randomUUID();
String key = "originals/" + id;
storage.ensureBucket();
storage.put(key, bytes, image.contentType());
try {
AttachmentEntity saved = transactions.execute(status -> attachments.saveAndFlush(new AttachmentEntity(
id, chatId, actorId, displayName, image.contentType(), bytes.length, sha256(bytes), key)));
return toModel(saved);
} catch (RuntimeException exception) {
storage.deleteQuietly(key);
throw exception;
}
}
@Transactional(readOnly = true)
public Attachment get(UUID actorId, UUID attachmentId) {
return toModel(visible(actorId, attachmentId));
}
@Transactional(readOnly = true)
public AttachmentEntity content(UUID actorId, UUID attachmentId, String variant) {
if (variant != null && !"original".equals(variant)) {
throw new InvalidRequestException("Некорректный запрос");
}
return visible(actorId, attachmentId);
}
public InputStream open(AttachmentEntity attachment) {
return storage.get(attachment.getObjectKey());
}
private AttachmentEntity visible(UUID actorId, UUID attachmentId) {
AttachmentEntity attachment = attachments.findById(attachmentId).orElseThrow(NotFoundException::new);
if (!members.existsByChatIdAndUserId(attachment.getChatId(), actorId)) {
throw new NotFoundException();
}
return attachment;
}
private void requireMember(UUID chatId, UUID actorId) {
if (!members.existsByChatIdAndUserId(chatId, actorId)) {
throw new NotFoundException();
}
}
private static String filename(String value) {
if (value == null) {
throw new InvalidRequestException("Некорректный запрос");
}
int codePoints = value.codePointCount(0, value.length());
if (codePoints < 1 || codePoints > 255) {
throw new InvalidRequestException("Некорректный запрос");
}
int offset = 0;
while (offset < value.length()) {
int codePoint = value.codePointAt(offset);
if (codePoint == '/' || codePoint == '\\' || Character.isISOControl(codePoint)) {
throw new InvalidRequestException("Некорректный запрос");
}
offset += Character.charCount(codePoint);
}
return value;
}
private static String declaredType(String header) {
if (header == null || header.isBlank()) {
throw new UnsupportedMediaException();
}
MediaType media;
try {
media = MediaType.parseMediaType(header);
} catch (InvalidMediaTypeException exception) {
throw new UnsupportedMediaException();
}
if (media.equalsTypeAndSubtype(MediaType.IMAGE_PNG)) {
return "image/png";
}
if (media.equalsTypeAndSubtype(MediaType.parseMediaType("image/jpeg"))) {
return "image/jpeg";
}
throw new UnsupportedMediaException();
}
private static String sha256(byte[] bytes) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException(exception);
}
}
private static Attachment toModel(AttachmentEntity entity) {
Attachment model = new Attachment();
model.setId(entity.getId());
model.setChatId(entity.getChatId());
model.setOwnerId(entity.getOwnerId());
model.setFilename(entity.getFilename());
model.setContentType(Attachment.ContentTypeEnum.fromValue(entity.getContentType()));
model.setSizeBytes((int) entity.getSizeBytes());
model.setSha256(entity.getSha256());
model.setStatus(Attachment.StatusEnum.READY);
model.setVariants(new ArrayList<>());
model.setErrorCode(null);
model.setCreatedAt(entity.getCreatedAt().atOffset(java.time.ZoneOffset.UTC));
model.setUpdatedAt(entity.getUpdatedAt().atOffset(java.time.ZoneOffset.UTC));
return model;
}
}
@@ -0,0 +1,99 @@
package ru.mtuci.messenger.service;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtuci.messenger.api.model.Chat;
import ru.mtuci.messenger.api.model.ChatPage;
import ru.mtuci.messenger.api.model.CreateChat;
import ru.mtuci.messenger.domain.ChatEntity;
import ru.mtuci.messenger.domain.ChatMemberEntity;
import ru.mtuci.messenger.exception.InvalidRequestException;
import ru.mtuci.messenger.exception.NotFoundException;
import ru.mtuci.messenger.mapper.ChatMapper;
import ru.mtuci.messenger.repository.ChatMemberRepository;
import ru.mtuci.messenger.repository.ChatRepository;
import ru.mtuci.messenger.repository.UserRepository;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Service
public class ChatService {
private final ChatRepository chats;
private final ChatMemberRepository members;
private final UserRepository users;
private final ChatMapper mapper;
public ChatService(ChatRepository chats, ChatMemberRepository members, UserRepository users, ChatMapper mapper) {
this.chats = chats;
this.members = members;
this.users = users;
this.mapper = mapper;
}
@Transactional
public Chat create(UUID actorId, CreateChat request) {
TextRules.title(request.getTitle());
List<UUID> memberIds = request.getMemberIds();
if (memberIds == null || new HashSet<>(memberIds).size() != memberIds.size() || !memberIds.contains(actorId)) {
throw new InvalidRequestException("Некорректный запрос");
}
ChatEntity chat = chats.save(new ChatEntity(request.getTitle()));
if (users.countByIdIn(memberIds) != memberIds.size()) {
throw new InvalidRequestException("Некорректный запрос");
}
for (int index = 0; index < memberIds.size(); index++) {
members.save(new ChatMemberEntity(chat.getId(), memberIds.get(index), index));
}
return mapper.toModel(chat, memberIds);
}
@Transactional(readOnly = true)
public ChatPage list(UUID actorId, Integer limit, String cursor) {
int pageSize = limit == null ? 50 : limit;
CursorCodec.Position position = cursor == null ? null : CursorCodec.decode(cursor, null);
List<ChatEntity> rows = position == null
? chats.findFirst(actorId, PageRequest.of(0, pageSize + 1))
: chats.findAfter(actorId, position.createdAt(), position.id(), PageRequest.of(0, pageSize + 1));
boolean more = rows.size() > pageSize;
List<ChatEntity> visible = more ? rows.subList(0, pageSize) : rows;
Map<UUID, List<UUID>> byChat = memberIds(visible);
List<Chat> items = visible.stream()
.map(chat -> mapper.toModel(chat, byChat.getOrDefault(chat.getId(), List.of())))
.toList();
String next = null;
if (more) {
ChatEntity last = visible.get(visible.size() - 1);
next = CursorCodec.encode(null, last.getCreatedAt(), last.getId());
}
return new ChatPage(items, next);
}
@Transactional(readOnly = true)
public Chat get(UUID actorId, UUID chatId) {
if (!members.existsByChatIdAndUserId(chatId, actorId)) {
throw new NotFoundException();
}
ChatEntity chat = chats.findById(chatId).orElseThrow(NotFoundException::new);
List<UUID> memberIds = members.findByChatIdOrderByOrdinalAsc(chatId).stream().map(ChatMemberEntity::getUserId).toList();
return mapper.toModel(chat, memberIds);
}
private Map<UUID, List<UUID>> memberIds(List<ChatEntity> chats) {
Map<UUID, List<UUID>> result = new LinkedHashMap<>();
if (chats.isEmpty()) {
return result;
}
List<UUID> ids = chats.stream().map(ChatEntity::getId).toList();
for (ChatMemberEntity member : members.findByChatIdInOrderByOrdinalAsc(ids)) {
result.computeIfAbsent(member.getChatId(), ignored -> new ArrayList<>()).add(member.getUserId());
}
return result;
}
}
@@ -0,0 +1,48 @@
package ru.mtuci.messenger.service;
import ru.mtuci.messenger.exception.InvalidRequestException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;
/**
* Непрозрачная позиция keyset-страницы: клиент получает её как next_cursor
* и возвращает в ?cursor=, чтобы следующая страница началась после (created_at, id).
* Для истории в курсор входит chatId: курсор другого чата отклоняется.
*/
public final class CursorCodec {
private CursorCodec() {
}
public static String encode(UUID scope, Instant createdAt, UUID id) {
String raw = scope == null ? createdAt + "|" + id : scope + "|" + createdAt + "|" + id;
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}
public static Position decode(String cursor, UUID scope) {
String raw;
try {
raw = new String(Base64.getUrlDecoder().decode(cursor), StandardCharsets.UTF_8);
} catch (IllegalArgumentException exception) {
throw new InvalidRequestException("Некорректный курсор");
}
String[] parts = raw.split("\\|", -1);
try {
if (scope == null && parts.length == 2) {
return new Position(Instant.parse(parts[0]), UUID.fromString(parts[1]));
}
if (scope != null && parts.length == 3 && scope.equals(UUID.fromString(parts[0]))) {
return new Position(Instant.parse(parts[1]), UUID.fromString(parts[2]));
}
} catch (RuntimeException exception) {
throw new InvalidRequestException("Некорректный курсор");
}
throw new InvalidRequestException("Некорректный курсор");
}
public record Position(Instant createdAt, UUID id) {
}
}
@@ -0,0 +1,171 @@
package ru.mtuci.messenger.service;
import ru.mtuci.messenger.exception.PayloadTooLargeException;
import ru.mtuci.messenger.exception.UnsupportedMediaException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public final class ImageFiles {
private static final byte[] PNG_SIGNATURE = new byte[] {(byte) 137, 80, 78, 71, 13, 10, 26, 10};
private ImageFiles() {
}
public record Image(String contentType, long width, long height) {
}
public static byte[] readLimited(InputStream input, int maxBytes) throws IOException {
byte[] buffer = new byte[8192];
ByteArrayOutputStream body = new ByteArrayOutputStream(Math.min(maxBytes, 64 * 1024));
int total = 0;
int read;
while ((read = input.read(buffer)) >= 0) {
if (read == 0) {
continue;
}
if (total > maxBytes - read) {
throw new PayloadTooLargeException();
}
body.write(buffer, 0, read);
total += read;
}
return body.toByteArray();
}
public static Image inspect(byte[] data, String declaredType, long maxPixels) {
if (data.length == 0) {
throw new UnsupportedMediaException();
}
Image image = "image/png".equals(declaredType) ? png(data) : jpeg(data);
if (image == null || !declaredType.equals(image.contentType()) || image.width() <= 0 || image.height() <= 0) {
throw new UnsupportedMediaException();
}
if (image.width() > maxPixels || image.height() > maxPixels || image.width() * image.height() > maxPixels) {
throw new PayloadTooLargeException();
}
return image;
}
private static Image png(byte[] data) {
if (data.length < 33 || !startsWith(data, PNG_SIGNATURE)) {
return null;
}
int offset = 8;
Long width = null;
Long height = null;
boolean end = false;
while (offset + 12 <= data.length) {
long length = u32(data, offset);
if (length > data.length || offset + 12L + length > data.length) {
return null;
}
String type = new String(data, offset + 4, 4, StandardCharsets.US_ASCII);
if (!type.chars().allMatch(Character::isLetter)) {
return null;
}
if ("IHDR".equals(type)) {
if (length != 13 || width != null || !validPngHeader(data, offset + 8)) {
return null;
}
width = u32(data, offset + 8);
height = u32(data, offset + 12);
}
offset += 12 + (int) length;
if ("IEND".equals(type)) {
end = length == 0;
break;
}
}
if (!end || width == null || offset != data.length) {
return null;
}
return new Image("image/png", width, height);
}
private static boolean validPngHeader(byte[] data, int offset) {
int bitDepth = data[offset + 8] & 0xff;
int color = data[offset + 9] & 0xff;
int compression = data[offset + 10] & 0xff;
int filter = data[offset + 11] & 0xff;
int interlace = data[offset + 12] & 0xff;
if (compression != 0 || filter != 0 || (interlace != 0 && interlace != 1)) {
return false;
}
return switch (color) {
case 0 -> bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8 || bitDepth == 16;
case 3 -> bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8;
case 2, 4, 6 -> bitDepth == 8 || bitDepth == 16;
default -> false;
};
}
private static Image jpeg(byte[] data) {
if (data.length < 4 || (data[0] & 0xff) != 0xff || (data[1] & 0xff) != 0xd8) {
return null;
}
int offset = 2;
Long width = null;
Long height = null;
while (offset + 1 < data.length) {
if ((data[offset] & 0xff) != 0xff) {
return null;
}
while (offset < data.length && (data[offset] & 0xff) == 0xff) {
offset++;
}
if (offset >= data.length) {
return null;
}
int marker = data[offset++] & 0xff;
if (marker == 0xd9) {
return width == null ? null : new Image("image/jpeg", width, height);
}
if (marker == 0xd8 || marker == 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
continue;
}
if (offset + 1 >= data.length) {
return null;
}
int length = ((data[offset] & 0xff) << 8) | (data[offset + 1] & 0xff);
if (length < 2 || offset + length > data.length) {
return null;
}
if (isStartOfFrame(marker)) {
if (length < 7) {
return null;
}
height = (long) ((data[offset + 3] & 0xff) << 8) | (data[offset + 4] & 0xff);
width = (long) ((data[offset + 5] & 0xff) << 8) | (data[offset + 6] & 0xff);
}
offset += length;
}
return null;
}
private static boolean isStartOfFrame(int marker) {
return marker >= 0xc0 && marker <= 0xcf && marker != 0xc4 && marker != 0xc8 && marker != 0xcc;
}
private static boolean startsWith(byte[] data, byte[] prefix) {
if (data.length < prefix.length) {
return false;
}
for (int i = 0; i < prefix.length; i++) {
if (data[i] != prefix[i]) {
return false;
}
}
return true;
}
private static long u32(byte[] data, int offset) {
return ((data[offset] & 0xffL) << 24)
| ((data[offset + 1] & 0xffL) << 16)
| ((data[offset + 2] & 0xffL) << 8)
| (data[offset + 3] & 0xffL);
}
}
@@ -0,0 +1,199 @@
package ru.mtuci.messenger.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtuci.messenger.api.model.CreateMessage;
import ru.mtuci.messenger.api.model.Message;
import ru.mtuci.messenger.api.model.MessagePage;
import ru.mtuci.messenger.domain.AttachmentEntity;
import ru.mtuci.messenger.domain.IdempotencyRecord;
import ru.mtuci.messenger.domain.MessageEntity;
import ru.mtuci.messenger.exception.ConflictException;
import ru.mtuci.messenger.exception.InvalidRequestException;
import ru.mtuci.messenger.exception.NotFoundException;
import ru.mtuci.messenger.mapper.MessageMapper;
import ru.mtuci.messenger.repository.AttachmentRepository;
import ru.mtuci.messenger.repository.ChatMemberRepository;
import ru.mtuci.messenger.repository.IdempotencyRepository;
import ru.mtuci.messenger.repository.MessageRepository;
import org.springframework.data.domain.PageRequest;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Pattern;
@Service
public class MessageService {
private static final Pattern IDEMPOTENCY_KEY = Pattern.compile("^[A-Za-z0-9._:-]{1,128}$");
private static final String METHOD = "POST";
private final MessageRepository messages;
private final AttachmentRepository attachments;
private final IdempotencyRepository idempotency;
private final ChatMemberRepository members;
private final MessageMapper mapper;
private final JdbcTemplate jdbc;
private final Duration idempotencyTtl;
public MessageService(MessageRepository messages, AttachmentRepository attachments, IdempotencyRepository idempotency,
ChatMemberRepository members, MessageMapper mapper, JdbcTemplate jdbc,
@Value("${app.idempotency-ttl:PT24H}") Duration idempotencyTtl) {
this.messages = messages;
this.attachments = attachments;
this.idempotency = idempotency;
this.members = members;
this.mapper = mapper;
this.jdbc = jdbc;
this.idempotencyTtl = idempotencyTtl;
}
@Transactional
public Message create(UUID actorId, UUID chatId, String idempotencyKey, CreateMessage request) {
requireMember(chatId, actorId);
String key = requireKey(idempotencyKey);
List<UUID> attachmentIds = attachmentIds(request);
requireText(request.getText(), !attachmentIds.isEmpty());
requireAttachments(chatId, attachmentIds);
String path = "/api/v1/chats/" + chatId + "/messages";
lock(actorId + "\n" + METHOD + "\n" + path + "\n" + key);
String hash = requestHash(request.getText(), attachmentIds);
Optional<IdempotencyRecord> existing = idempotency.findByUserIdAndHttpMethodAndPathAndIdempotencyKey(
actorId, METHOD, path, key);
if (existing.isPresent()) {
IdempotencyRecord record = existing.get();
if (record.getExpiresAt().isAfter(Instant.now())) {
if (!record.getRequestHash().equals(hash)) {
throw new ConflictException("Ключ идемпотентности уже использован с другим телом");
}
return mapper.toModel(messages.findById(record.getMessageId()).orElseThrow(NotFoundException::new));
}
idempotency.delete(record);
idempotency.flush();
}
Instant now = Instant.now();
MessageEntity saved = messages.saveAndFlush(new MessageEntity(chatId, actorId, request.getText(), attachmentIds));
idempotency.saveAndFlush(new IdempotencyRecord(
actorId, METHOD, path, key, hash, saved.getId(), now, now.plus(idempotencyTtl)));
return mapper.toModel(messages.findById(saved.getId()).orElseThrow(NotFoundException::new));
}
@Transactional(readOnly = true)
public MessagePage list(UUID actorId, UUID chatId, Integer limit, String cursor) {
requireMember(chatId, actorId);
int pageSize = limit == null ? 50 : limit;
CursorCodec.Position position = cursor == null ? null : CursorCodec.decode(cursor, chatId);
List<MessageEntity> rows = position == null
? messages.findFirst(chatId, PageRequest.of(0, pageSize + 1))
: messages.findAfter(chatId, position.createdAt(), position.id(), PageRequest.of(0, pageSize + 1));
boolean more = rows.size() > pageSize;
List<MessageEntity> visible = more ? rows.subList(0, pageSize) : rows;
String next = null;
if (more) {
MessageEntity last = visible.get(visible.size() - 1);
next = CursorCodec.encode(chatId, last.getCreatedAt(), last.getId());
}
return new MessagePage(visible.stream().map(mapper::toModel).toList(), next);
}
private void lock(String scope) {
byte[] digest = digest(scope);
long key = 0;
for (int i = 0; i < 8; i++) {
key = (key << 8) | (digest[i] & 0xffL);
}
long lockKey = key;
jdbc.execute((Connection connection) -> {
try (var statement = connection.prepareStatement("select pg_advisory_xact_lock(?)")) {
statement.setLong(1, lockKey);
statement.execute();
}
return null;
});
}
private static String requireKey(String key) {
if (key == null || !IDEMPOTENCY_KEY.matcher(key).matches()) {
throw new InvalidRequestException("Некорректный запрос");
}
return key;
}
private void requireAttachments(UUID chatId, List<UUID> attachmentIds) {
if (attachmentIds.isEmpty()) {
return;
}
List<AttachmentEntity> found = attachments.findAllById(attachmentIds);
if (found.size() != attachmentIds.size()) {
throw new NotFoundException();
}
for (AttachmentEntity attachment : found) {
if (!chatId.equals(attachment.getChatId()) || !"ready".equals(attachment.getStatus())) {
throw new NotFoundException();
}
}
}
private static List<UUID> attachmentIds(CreateMessage request) {
List<UUID> ids = request.getAttachmentIds();
if (ids == null || ids.isEmpty()) {
return List.of();
}
if (ids.size() > 10 || ids.stream().anyMatch(Objects::isNull) || new LinkedHashSet<>(ids).size() != ids.size()) {
throw new InvalidRequestException("Некорректный запрос");
}
return new ArrayList<>(ids);
}
private static void requireText(String text, boolean hasAttachments) {
if (text == null) {
throw new InvalidRequestException("Некорректный запрос");
}
int codePoints = text.codePointCount(0, text.length());
if (codePoints > 4000 || (text.isBlank() && !hasAttachments)) {
throw new InvalidRequestException("Некорректный запрос");
}
}
private static String requestHash(String text, List<UUID> attachmentIds) {
StringBuilder canonical = new StringBuilder(text == null ? "" : text).append('\n');
for (int i = 0; i < attachmentIds.size(); i++) {
if (i > 0) {
canonical.append(',');
}
canonical.append(attachmentIds.get(i));
}
return sha256(canonical.toString());
}
private static String sha256(String value) {
return HexFormat.of().formatHex(digest(value));
}
private static byte[] digest(String value) {
try {
return MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException(exception);
}
}
private void requireMember(UUID chatId, UUID actorId) {
if (!members.existsByChatIdAndUserId(chatId, actorId)) {
throw new NotFoundException();
}
}
}
@@ -0,0 +1,35 @@
package ru.mtuci.messenger.service;
import ru.mtuci.messenger.exception.InvalidRequestException;
public final class TextRules {
private TextRules() {
}
public static void displayName(String value) {
text(value, 1, 100);
}
public static void title(String value) {
text(value, 1, 100);
}
public static void message(String value) {
text(value, 1, 4000);
}
public static void password(String value) {
text(value, 12, 128);
}
private static void text(String value, int minCodePoints, int maxCodePoints) {
if (value == null || value.isBlank()) {
throw new InvalidRequestException("Некорректный запрос");
}
int codePoints = value.codePointCount(0, value.length());
if (codePoints < minCodePoints || codePoints > maxCodePoints) {
throw new InvalidRequestException("Некорректный запрос");
}
}
}
@@ -0,0 +1,147 @@
package ru.mtuci.messenger.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import ru.mtuci.messenger.api.model.CreateUser;
import ru.mtuci.messenger.api.model.Session;
import ru.mtuci.messenger.api.model.User;
import ru.mtuci.messenger.cache.SessionCache;
import ru.mtuci.messenger.domain.SessionEntity;
import ru.mtuci.messenger.domain.UserAccount;
import ru.mtuci.messenger.exception.ConflictException;
import ru.mtuci.messenger.exception.NotFoundException;
import ru.mtuci.messenger.exception.UnauthorizedException;
import ru.mtuci.messenger.mapper.UserMapper;
import ru.mtuci.messenger.repository.SessionRepository;
import ru.mtuci.messenger.repository.UserRepository;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.HexFormat;
import java.util.Optional;
import java.util.UUID;
@Service
public class UserService {
private final UserRepository users;
private final SessionRepository sessions;
private final SessionCache cache;
private final UserMapper mapper;
private final PasswordEncoder passwords;
private final TransactionTemplate transactions;
private final Duration sessionTtl;
private final SecureRandom random = new SecureRandom();
private volatile String dummyHash;
public UserService(UserRepository users, SessionRepository sessions, SessionCache cache, UserMapper mapper,
PasswordEncoder passwords, TransactionTemplate transactions,
@Value("${app.session-ttl}") Duration sessionTtl) {
this.users = users;
this.sessions = sessions;
this.cache = cache;
this.mapper = mapper;
this.passwords = passwords;
this.transactions = transactions;
this.sessionTtl = sessionTtl;
}
public User register(CreateUser request) {
TextRules.displayName(request.getDisplayName());
TextRules.password(request.getPassword());
try {
return transactions.execute(status -> mapper.toModel(users.saveAndFlush(new UserAccount(
request.getUsername(),
request.getDisplayName(),
passwords.encode(request.getPassword())
))));
} catch (DataIntegrityViolationException exception) {
throw new ConflictException("Имя пользователя занято");
}
}
public User current(UUID userId) {
return users.findById(userId).map(mapper::toModel).orElseThrow(NotFoundException::new);
}
public Session login(String authorization) {
String[] credentials = basic(authorization);
UserAccount user = users.findByUsername(credentials[0]).orElse(null);
String hash = user == null ? dummyHash() : user.getPasswordHash();
if (user == null || !passwords.matches(credentials[1], hash)) {
throw UnauthorizedException.basic();
}
String token = newToken();
SessionEntity session = sessions.saveAndFlush(new SessionEntity(tokenHash(token), user.getId(), sessionTtl));
cache.put(tokenHash(token), user.getId(), session.getExpiresAt());
return mapper.toSession(token, session.getExpiresAt(), user);
}
public Optional<UUID> authenticate(String token) {
String hash = tokenHash(token);
Optional<UUID> cached = cache.find(hash);
if (cached.isPresent()) {
return cached;
}
return sessions.findActive(hash, Instant.now()).map(session -> {
cache.put(hash, session.getUserId(), session.getExpiresAt());
return session.getUserId();
});
}
public void revoke(String token) {
String hash = tokenHash(token);
if (sessions.revoke(hash, Instant.now()) == 0) {
throw UnauthorizedException.bearer();
}
cache.evict(hash);
}
public static String tokenHash(String token) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException(exception);
}
}
private String newToken() {
byte[] bytes = new byte[32];
random.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
private String dummyHash() {
String current = dummyHash;
if (current == null) {
current = passwords.encode("not-a-real-password");
dummyHash = current;
}
return current;
}
private static String[] basic(String header) {
if (header == null || !header.regionMatches(true, 0, "Basic ", 0, 6)) {
throw UnauthorizedException.basic();
}
String decoded;
try {
decoded = new String(Base64.getDecoder().decode(header.substring(6).trim()), StandardCharsets.UTF_8);
} catch (IllegalArgumentException exception) {
throw UnauthorizedException.basic();
}
int colon = decoded.indexOf(':');
if (colon <= 0) {
throw UnauthorizedException.basic();
}
return new String[]{decoded.substring(0, colon), decoded.substring(colon + 1)};
}
}
@@ -0,0 +1,108 @@
package ru.mtuci.messenger.storage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import ru.mtuci.messenger.exception.NotFoundException;
import ru.mtuci.messenger.exception.UnavailableException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.BucketAlreadyExistsException;
import software.amazon.awssdk.services.s3.model.BucketAlreadyOwnedByYouException;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.io.InputStream;
@Component
public class ObjectStorage {
private static final Logger log = LoggerFactory.getLogger(ObjectStorage.class);
private final S3Client s3;
private final String bucket;
public ObjectStorage(S3Client s3, @Value("${app.s3.bucket}") String bucket) {
this.s3 = s3;
this.bucket = bucket;
}
public void ensureBucket() {
try {
s3.headBucket(HeadBucketRequest.builder().bucket(bucket).build());
} catch (NoSuchBucketException missing) {
createBucket();
} catch (S3Exception exception) {
if (exception.statusCode() == 404) {
createBucket();
return;
}
throw storageFailure(exception);
} catch (RuntimeException exception) {
throw storageFailure(exception);
}
}
public void put(String key, byte[] body, String contentType) {
try {
s3.putObject(PutObjectRequest.builder()
.bucket(bucket)
.key(key)
.contentType(contentType)
.contentLength((long) body.length)
.build(), RequestBody.fromBytes(body));
} catch (RuntimeException exception) {
throw storageFailure(exception);
}
}
public InputStream get(String key) {
try {
return s3.getObject(GetObjectRequest.builder().bucket(bucket).key(key).build());
} catch (NoSuchKeyException missing) {
throw new NotFoundException();
} catch (S3Exception exception) {
if (exception.statusCode() == 404) {
throw new NotFoundException();
}
throw storageFailure(exception);
} catch (RuntimeException exception) {
throw storageFailure(exception);
}
}
public void deleteQuietly(String key) {
try {
s3.deleteObject(DeleteObjectRequest.builder().bucket(bucket).key(key).build());
} catch (RuntimeException exception) {
log.warn("s3 delete failed status={}", exception.getClass().getSimpleName());
}
}
private void createBucket() {
try {
s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build());
} catch (BucketAlreadyExistsException | BucketAlreadyOwnedByYouException ignored) {
// another replica created the bucket
} catch (S3Exception exception) {
if (exception.statusCode() == 409) {
return;
}
throw storageFailure(exception);
} catch (RuntimeException exception) {
throw storageFailure(exception);
}
}
private static UnavailableException storageFailure(RuntimeException exception) {
log.warn("s3 failure type={}", exception.getClass().getSimpleName());
return new UnavailableException("Хранилище временно недоступно");
}
}
@@ -0,0 +1,37 @@
package ru.mtuci.messenger.storage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;
import java.net.URI;
import java.time.Duration;
@Configuration
public class S3Config {
@Bean(destroyMethod = "close")
S3Client s3Client(@Value("${app.s3.endpoint}") String endpoint,
@Value("${app.s3.region}") String region,
@Value("${app.s3.access-key}") String accessKey,
@Value("${app.s3.secret-key}") String secretKey) {
return S3Client.builder()
.endpointOverride(URI.create(endpoint))
.region(Region.of(region))
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)))
.serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build())
.httpClientBuilder(ApacheHttpClient.builder()
.connectionTimeout(Duration.ofSeconds(2))
.socketTimeout(Duration.ofSeconds(8)))
.overrideConfiguration(config -> config
.apiCallTimeout(Duration.ofSeconds(10))
.apiCallAttemptTimeout(Duration.ofSeconds(8)))
.build();
}
}
@@ -0,0 +1,30 @@
package ru.mtuci.messenger.storage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.health.contributor.Health;
import org.springframework.boot.health.contributor.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class S3HealthIndicator implements HealthIndicator {
private static final Logger log = LoggerFactory.getLogger(S3HealthIndicator.class);
private final ObjectStorage storage;
public S3HealthIndicator(ObjectStorage storage) {
this.storage = storage;
}
@Override
public Health health() {
try {
storage.ensureBucket();
return Health.up().build();
} catch (RuntimeException exception) {
log.info("s3 readiness failed type={}", exception.getClass().getSimpleName());
return Health.down().build();
}
}
}
@@ -0,0 +1,97 @@
package ru.mtuci.messenger.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import ru.mtuci.messenger.api.model.Error;
import ru.mtuci.messenger.api.model.ErrorError;
import ru.mtuci.messenger.exception.ApiException;
import ru.mtuci.messenger.exception.UnauthorizedException;
@RestControllerAdvice
public class ApiAdvice {
private static final Logger log = LoggerFactory.getLogger(ApiAdvice.class);
private final InstanceIdentity instanceId;
public ApiAdvice(InstanceIdentity instanceId) {
this.instanceId = instanceId;
}
@ExceptionHandler(ApiException.class)
public ResponseEntity<Error> handleApi(HttpServletRequest request, HttpServletResponse response, ApiException exception) {
log.info("api error code={}", exception.code().getValue());
String challenge = exception instanceof UnauthorizedException unauthorized ? unauthorized.challenge() : null;
return response(request, response, exception.status(), exception.code(), exception.getMessage(), challenge);
}
@ExceptionHandler({
HttpMessageNotReadableException.class,
MethodArgumentNotValidException.class,
ConstraintViolationException.class,
HandlerMethodValidationException.class,
MethodArgumentTypeMismatchException.class,
MissingServletRequestParameterException.class,
HttpRequestMethodNotSupportedException.class
})
public ResponseEntity<Error> handleInvalid(HttpServletRequest request, HttpServletResponse response, Exception exception) {
log.info("invalid request type={}", exception.getClass().getSimpleName());
return response(request, response, HttpStatus.BAD_REQUEST, ErrorError.CodeEnum.INVALID_REQUEST, "Некорректный запрос", null);
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ResponseEntity<Error> handleMedia(HttpServletRequest request, HttpServletResponse response) {
return response(request, response, HttpStatus.UNSUPPORTED_MEDIA_TYPE, ErrorError.CodeEnum.UNSUPPORTED_MEDIA_TYPE,
"Неподдерживаемый тип содержимого", null);
}
@ExceptionHandler({NoResourceFoundException.class, NoHandlerFoundException.class})
public ResponseEntity<Error> handleMissing(HttpServletRequest request, HttpServletResponse response) {
return response(request, response, HttpStatus.NOT_FOUND, ErrorError.CodeEnum.NOT_FOUND, "Объект не найден", null);
}
@ExceptionHandler({DataAccessException.class, CannotCreateTransactionException.class})
public ResponseEntity<Error> handleDataAccess(HttpServletRequest request, HttpServletResponse response, Exception exception) {
log.warn("data access failure type={}", exception.getClass().getSimpleName());
return response(request, response, HttpStatus.SERVICE_UNAVAILABLE, ErrorError.CodeEnum.UNAVAILABLE,
"Сервис временно недоступен", null);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Error> handleUnexpected(HttpServletRequest request, HttpServletResponse response, Exception exception) {
log.error("unexpected failure type={}", exception.getClass().getName(), exception);
return response(request, response, HttpStatus.INTERNAL_SERVER_ERROR, ErrorError.CodeEnum.INTERNAL_ERROR,
"Внутренняя ошибка", null);
}
private ResponseEntity<Error> response(HttpServletRequest request, HttpServletResponse response, HttpStatus status,
ErrorError.CodeEnum code, String message, String challenge) {
String requestId = RequestIdFilter.id(request);
response.setHeader(RequestIdFilter.HEADER, requestId);
response.setHeader(InstanceIdFilter.HEADER, instanceId.value());
HttpHeaders headers = new HttpHeaders();
if (challenge != null) {
headers.set(HttpHeaders.WWW_AUTHENTICATE, challenge);
}
return new ResponseEntity<>(new Error(new ErrorError(code, message, requestId)), headers, status);
}
}
@@ -0,0 +1,70 @@
package ru.mtuci.messenger.web;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import ru.mtuci.messenger.exception.UnauthorizedException;
import ru.mtuci.messenger.service.UserService;
import java.io.IOException;
import java.util.UUID;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
public class BearerAuthFilter extends OncePerRequestFilter {
public static final String TOKEN = "token";
private final UserService users;
private final HandlerExceptionResolver errors;
public BearerAuthFilter(UserService users, @Qualifier("handlerExceptionResolver") HandlerExceptionResolver errors) {
this.users = users;
this.errors = errors;
}
public static UUID userId(HttpServletRequest request) {
return (UUID) request.getAttribute("userId");
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
if (isPublic(request)) {
chain.doFilter(request, response);
return;
}
try {
String header = request.getHeader("Authorization");
if (header == null || !header.regionMatches(true, 0, "Bearer ", 0, 7)) {
throw UnauthorizedException.bearer();
}
String token = header.substring(7).trim();
UUID userId = users.authenticate(token).orElseThrow(UnauthorizedException::bearer);
request.setAttribute("userId", userId);
request.setAttribute(TOKEN, token);
} catch (RuntimeException exception) {
errors.resolveException(request, response, null, exception);
return;
}
chain.doFilter(request, response);
}
private static boolean isPublic(HttpServletRequest request) {
String path = request.getRequestURI();
if (HttpMethod.GET.matches(request.getMethod()) && (path.equals("/health/live") || path.equals("/health/ready")
|| path.startsWith("/actuator/"))) {
return true;
}
return HttpMethod.POST.matches(request.getMethod())
&& (path.equals("/api/v1/users") || path.equals("/api/v1/auth/sessions"));
}
}
@@ -0,0 +1,32 @@
package ru.mtuci.messenger.web;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class InstanceIdFilter extends OncePerRequestFilter {
static final String HEADER = "X-Instance-Id";
private final InstanceIdentity instanceId;
public InstanceIdFilter(InstanceIdentity instanceId) {
this.instanceId = instanceId;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.setHeader(HEADER, instanceId.value());
filterChain.doFilter(request, response);
}
}
@@ -0,0 +1,19 @@
package ru.mtuci.messenger.web;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class InstanceIdentity {
private final String value;
public InstanceIdentity(@Value("${app.instance-id:local}") String configured) {
String trimmed = configured == null ? "" : configured.trim();
this.value = trimmed.isEmpty() ? "local" : trimmed;
}
public String value() {
return value;
}
}
@@ -0,0 +1,45 @@
package ru.mtuci.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.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.UUID;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestIdFilter extends OncePerRequestFilter {
static final String HEADER = "X-Request-Id";
static String id(HttpServletRequest request) {
Object existing = request.getAttribute(HEADER);
if (existing != null) {
return existing.toString();
}
String header = request.getHeader(HEADER);
String id = header == null || header.isBlank() ? UUID.randomUUID().toString() : header;
request.setAttribute(HEADER, id);
return id;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String requestId = id(request);
response.setHeader(HEADER, requestId);
MDC.put("requestId", requestId);
try {
filterChain.doFilter(request, response);
} finally {
MDC.remove("requestId");
}
}
}
@@ -0,0 +1,25 @@
package ru.mtuci.messenger.web;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import java.time.OffsetDateTime;
@Configuration
public class TimeFormatConfig {
/**
* Python 3.9 {@code fromisoformat} принимает только 0, 3 или 6 знаков дробной секунды.
* Jackson по умолчанию отбрасывает хвостовые нули, и время вроде {@code .38078Z} ломает публичные тесты.
*/
@Bean
@Order(Ordered.LOWEST_PRECEDENCE)
JsonMapperBuilderCustomizer utcMicroseconds() {
JsonFormat.Value format = JsonFormat.Value.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX");
return builder -> builder.withConfigOverride(OffsetDateTime.class, override -> override.setFormat(format));
}
}