ЛР 3: масштабирование и отказоустойчивость API
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
package com.example.mtusi_messenger;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
@SpringBootApplication
|
||||
public class MtusiMessengerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
ConfigurableApplicationContext context = SpringApplication.run(
|
||||
MtusiMessengerApplication.class, args);
|
||||
if (Boolean.parseBoolean(System.getenv("MIGRATE_ONLY"))) {
|
||||
System.exit(SpringApplication.exit(context));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.example.mtusi_messenger.cache;
|
||||
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class UserCache {
|
||||
private static final Logger log = LoggerFactory.getLogger(UserCache.class);
|
||||
private static final String KEY_PREFIX = "messenger:user:";
|
||||
|
||||
private final StringRedisTemplate redis;
|
||||
private final ObjectMapper mapper;
|
||||
private final Duration ttl;
|
||||
|
||||
public UserCache(
|
||||
StringRedisTemplate redis,
|
||||
ObjectMapper mapper,
|
||||
@Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds
|
||||
) {
|
||||
if (ttlSeconds <= 0) {
|
||||
throw new IllegalArgumentException("User cache TTL must be positive");
|
||||
}
|
||||
this.redis = redis;
|
||||
this.mapper = mapper;
|
||||
this.ttl = Duration.ofSeconds(ttlSeconds);
|
||||
}
|
||||
|
||||
public Optional<User> find(UUID userId) {
|
||||
try {
|
||||
String value = redis.opsForValue().get(key(userId));
|
||||
if (value == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
User cachedUser = mapper.readValue(value, User.class);
|
||||
if (cachedUser == null) {
|
||||
log.warn("Ignoring null Redis user cache entry for {}", userId);
|
||||
evict(userId);
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(cachedUser);
|
||||
} catch (DataAccessException e) {
|
||||
log.warn("Redis user cache is unavailable; using PostgreSQL fallback");
|
||||
return Optional.empty();
|
||||
} catch (JsonProcessingException e) {
|
||||
log.warn("Ignoring malformed Redis user cache entry for {}", userId);
|
||||
evict(userId);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public void put(User user) {
|
||||
try {
|
||||
redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl);
|
||||
} catch (DataAccessException e) {
|
||||
log.warn("Redis user cache is unavailable; user was not cached");
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Cannot serialize user cache entry", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void evict(UUID userId) {
|
||||
try {
|
||||
redis.delete(key(userId));
|
||||
} catch (DataAccessException e) {
|
||||
log.warn("Redis user cache is unavailable; cache eviction was skipped");
|
||||
}
|
||||
}
|
||||
|
||||
private String key(UUID userId) {
|
||||
return KEY_PREFIX + userId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.example.mtusi_messenger.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
|
||||
|
||||
import tools.jackson.databind.cfg.CoercionAction;
|
||||
import tools.jackson.databind.cfg.CoercionInputShape;
|
||||
import tools.jackson.databind.type.LogicalType;
|
||||
|
||||
@Configuration
|
||||
public class JacksonConfig {
|
||||
|
||||
@Bean
|
||||
JsonMapperBuilderCustomizer strictStringTypes() {
|
||||
return builder -> builder.withCoercionConfig(
|
||||
LogicalType.Textual,
|
||||
config -> {
|
||||
config.setCoercion(
|
||||
CoercionInputShape.Integer, CoercionAction.Fail);
|
||||
config.setCoercion(
|
||||
CoercionInputShape.Float, CoercionAction.Fail);
|
||||
config.setCoercion(
|
||||
CoercionInputShape.Boolean, CoercionAction.Fail);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.example.mtusi_messenger.config;
|
||||
|
||||
|
||||
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityScheme;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@SecurityScheme(
|
||||
name = "basicAuth",
|
||||
type = SecuritySchemeType.HTTP,
|
||||
scheme = "basic"
|
||||
)
|
||||
@SecurityScheme(
|
||||
name = "bearerAuth",
|
||||
type = SecuritySchemeType.HTTP,
|
||||
scheme = "bearer",
|
||||
bearerFormat = "opaque session token"
|
||||
)
|
||||
@Configuration
|
||||
public class OpenApiConfig {
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.example.mtusi_messenger.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class PasswordConfig {
|
||||
@Bean
|
||||
PasswordEncoder passwordEncoder() {
|
||||
return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.example.mtusi_messenger.config;
|
||||
|
||||
import com.example.mtusi_messenger.security.ApiAuthenticationFilter;
|
||||
import com.example.mtusi_messenger.security.DatabaseAuthenticationProvider;
|
||||
import com.example.mtusi_messenger.security.RestAuthenticationEntryPoint;
|
||||
import com.example.mtusi_messenger.service.AuthenticationService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.ProviderManager;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
|
||||
public class SecurityConfig {
|
||||
@Bean
|
||||
AuthenticationManager authenticationManager(DatabaseAuthenticationProvider provider) {
|
||||
return new ProviderManager(provider);
|
||||
}
|
||||
|
||||
@Bean
|
||||
RestAuthenticationEntryPoint basicAuthenticationEntryPoint(ObjectMapper mapper) {
|
||||
return new RestAuthenticationEntryPoint(
|
||||
mapper,
|
||||
"Basic realm=\"messenger\", charset=\"UTF-8\"");
|
||||
}
|
||||
|
||||
@Bean
|
||||
RestAuthenticationEntryPoint bearerAuthenticationEntryPoint(ObjectMapper mapper) {
|
||||
return new RestAuthenticationEntryPoint(mapper, "Bearer realm=\"messenger\"");
|
||||
}
|
||||
|
||||
@Bean
|
||||
ApiAuthenticationFilter apiAuthenticationFilter(
|
||||
AuthenticationManager authenticationManager,
|
||||
AuthenticationService authenticationService,
|
||||
@Qualifier("basicAuthenticationEntryPoint") RestAuthenticationEntryPoint basicAuthenticationEntryPoint,
|
||||
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
|
||||
) {
|
||||
return new ApiAuthenticationFilter(
|
||||
authenticationManager,
|
||||
authenticationService,
|
||||
basicAuthenticationEntryPoint,
|
||||
bearerAuthenticationEntryPoint);
|
||||
}
|
||||
|
||||
@Bean
|
||||
FilterRegistrationBean<ApiAuthenticationFilter> disableServletFilterRegistration(
|
||||
ApiAuthenticationFilter filter
|
||||
) {
|
||||
var registration = new FilterRegistrationBean<>(filter);
|
||||
registration.setEnabled(false);
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain securityFilterChain(
|
||||
HttpSecurity http,
|
||||
ApiAuthenticationFilter apiAuthenticationFilter,
|
||||
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
|
||||
) throws Exception {
|
||||
http
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.formLogin(form -> form.disable())
|
||||
.httpBasic(basic -> basic.disable())
|
||||
.logout(logout -> logout.disable())
|
||||
.requestCache(cache -> cache.disable())
|
||||
.sessionManagement(session -> session
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.exceptionHandling(errors -> errors
|
||||
.authenticationEntryPoint(bearerAuthenticationEntryPoint))
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.requestMatchers(HttpMethod.GET, "/health/**").permitAll()
|
||||
.requestMatchers(
|
||||
"/swagger-ui.html",
|
||||
"/swagger-ui/**",
|
||||
"/v3/api-docs/**"
|
||||
).permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.addFilterBefore(apiAuthenticationFilter, AnonymousAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.example.mtusi_messenger.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.json.JsonMapper;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig {
|
||||
@Bean
|
||||
ObjectMapper objectMapper() {
|
||||
return JsonMapper.builder().findAndAddModules()
|
||||
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.example.mtusi_messenger.controller;
|
||||
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.example.mtusi_messenger.dto.*;
|
||||
import com.example.mtusi_messenger.model.Chat;
|
||||
import com.example.mtusi_messenger.service.ChatService;
|
||||
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.example.mtusi_messenger.service.UuidValidator.parse;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/chats")
|
||||
@SecurityRequirement(name = "bearerAuth")
|
||||
@RequiredArgsConstructor
|
||||
public class ChatController {
|
||||
|
||||
private final ChatService chats;
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<ChatResponse> create(@AuthenticationPrincipal SessionPrincipal principal,
|
||||
@Valid @RequestBody CreateChatRequest body
|
||||
) {
|
||||
UUID userId = principal.user().id();
|
||||
Chat c = chats.create(body, userId);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(ChatResponse.from(c));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ChatPageResponse list(@AuthenticationPrincipal SessionPrincipal principal,
|
||||
@RequestParam(required = false) String limit,
|
||||
@RequestParam(required = false) String cursor
|
||||
) {
|
||||
UUID userId = principal.user().id();
|
||||
int parsedLimit = validateLimit(limit);
|
||||
validateCursorPresence(cursor);
|
||||
List<Chat> page = chats.page(userId, parsedLimit, cursor);
|
||||
boolean hasNext = page.size() > parsedLimit;
|
||||
if (hasNext) page = page.subList(0, parsedLimit);
|
||||
return new ChatPageResponse(page.stream().map(ChatResponse::from).toList(), page.isEmpty() ? null :
|
||||
chats.nextCursor(userId, page.get(page.size() - 1), hasNext));
|
||||
}
|
||||
|
||||
@GetMapping("/{chatId}")
|
||||
public ChatResponse get(@AuthenticationPrincipal SessionPrincipal principal,
|
||||
@PathVariable String chatId
|
||||
) {
|
||||
UUID userId = principal.user().id();
|
||||
return ChatResponse.from(chats.getAccessible(parse(chatId), userId));
|
||||
}
|
||||
|
||||
private static int validateLimit(String limit) {
|
||||
if (limit == null) {
|
||||
return 50;
|
||||
}
|
||||
if (!limit.matches("[0-9]+")) {
|
||||
throw ApiExceptions.invalid("Invalid limit");
|
||||
}
|
||||
try {
|
||||
int value = Integer.parseInt(limit);
|
||||
|
||||
if (value < 1 || value > 100) {
|
||||
throw ApiExceptions.invalid("Invalid limit");
|
||||
}
|
||||
|
||||
return value;
|
||||
} catch (NumberFormatException ex) {
|
||||
throw ApiExceptions.invalid("Invalid limit");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateCursorPresence(String c) {
|
||||
if (c != null && c.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.example.mtusi_messenger.controller;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.RedisCallback;
|
||||
import org.springframework.boot.availability.ApplicationAvailability;
|
||||
import org.springframework.boot.availability.ReadinessState;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import com.example.mtusi_messenger.dto.HealthResponse;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
|
||||
@RestController
|
||||
public class HealthController {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final StringRedisTemplate redis;
|
||||
private final ApplicationAvailability availability;
|
||||
|
||||
public HealthController(
|
||||
JdbcTemplate jdbc,
|
||||
StringRedisTemplate redis,
|
||||
ApplicationAvailability availability
|
||||
) {
|
||||
this.jdbc = jdbc;
|
||||
this.redis = redis;
|
||||
this.availability = availability;
|
||||
}
|
||||
|
||||
@GetMapping("/health/live")
|
||||
public ResponseEntity<HealthResponse> live() {
|
||||
return ResponseEntity.ok(new HealthResponse("ok"));
|
||||
}
|
||||
|
||||
@GetMapping("/health/ready")
|
||||
public ResponseEntity<HealthResponse> ready() {
|
||||
if (availability.getReadinessState() != ReadinessState.ACCEPTING_TRAFFIC) {
|
||||
throw ApiExceptions.unavailable("Application is not accepting traffic");
|
||||
}
|
||||
try {
|
||||
// Warm the lazy Lettuce connection on every replica. Redis remains
|
||||
// an optional cache: failure is ignored and business reads fall
|
||||
// back to PostgreSQL.
|
||||
redis.execute((RedisCallback<String>) connection -> connection.ping());
|
||||
} catch (DataAccessException ignored) {
|
||||
// Optional cache unavailable; PostgreSQL remains authoritative.
|
||||
}
|
||||
try {
|
||||
// A schema-level probe prevents a replica from becoming ready
|
||||
// before the separately executed migration job has completed.
|
||||
jdbc.queryForObject("SELECT count(*) FROM message_idempotency", Long.class);
|
||||
return ResponseEntity.ok(new HealthResponse("ok"));
|
||||
} catch (DataAccessException e) {
|
||||
throw ApiExceptions.unavailable("Database is unavailable");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.example.mtusi_messenger.controller;
|
||||
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.example.mtusi_messenger.dto.*;
|
||||
import com.example.mtusi_messenger.model.Message;
|
||||
import com.example.mtusi_messenger.service.MessageService;
|
||||
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.example.mtusi_messenger.service.UuidValidator.parse;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/chats/{chatId}/messages")
|
||||
@SecurityRequirement(name = "bearerAuth")
|
||||
public class MessageController {
|
||||
private static final String IDEMPOTENCY_KEY_PATTERN = "[A-Za-z0-9._:-]{1,128}";
|
||||
private final MessageService messages;
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<MessageResponse> create(@AuthenticationPrincipal SessionPrincipal principal,
|
||||
@PathVariable String chatId,
|
||||
@RequestHeader(name = "Idempotency-Key", required = false) String idempotencyKey,
|
||||
@Valid @RequestBody CreateMessageRequest body
|
||||
) {
|
||||
if (idempotencyKey == null || !idempotencyKey.matches(IDEMPOTENCY_KEY_PATTERN)) {
|
||||
throw ApiExceptions.invalid("Invalid or missing Idempotency-Key");
|
||||
}
|
||||
UUID userId = principal.user().id();
|
||||
UUID parsedChatId = parse(chatId);
|
||||
Message m = messages.create(parsedChatId, userId, body, idempotencyKey);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(MessageResponse.from(m));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public MessagePageResponse list(@AuthenticationPrincipal SessionPrincipal principal,
|
||||
@PathVariable String chatId,
|
||||
@RequestParam(required = false) String limit,
|
||||
@RequestParam(required=false) String cursor
|
||||
) {
|
||||
UUID userId = principal.user().id();
|
||||
UUID parsedChatId = parse(chatId);
|
||||
int parsedLimit = validateLimit(limit);
|
||||
if (cursor != null && cursor.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
|
||||
List<Message> page = messages.page(parsedChatId, userId, parsedLimit, cursor);
|
||||
boolean hasNext = page.size() > parsedLimit; if (hasNext) page = page.subList(0, parsedLimit);
|
||||
return new MessagePageResponse(page.stream().map(MessageResponse::from).toList(),
|
||||
page.isEmpty() ? null : messages.nextCursor(parsedChatId, page.get(page.size()-1), hasNext));
|
||||
}
|
||||
|
||||
private static int validateLimit(String limit) {
|
||||
if (limit == null) {
|
||||
return 50;
|
||||
}
|
||||
if (!limit.matches("[0-9]+")) {
|
||||
throw ApiExceptions.invalid("Invalid limit");
|
||||
}
|
||||
try {
|
||||
int value = Integer.parseInt(limit);
|
||||
|
||||
if (value < 1 || value > 100) {
|
||||
throw ApiExceptions.invalid("Invalid limit");
|
||||
}
|
||||
|
||||
return value;
|
||||
} catch (NumberFormatException ex) {
|
||||
throw ApiExceptions.invalid("Invalid limit");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.example.mtusi_messenger.controller;
|
||||
|
||||
import com.example.mtusi_messenger.dto.SessionResponse;
|
||||
import com.example.mtusi_messenger.dto.UserResponse;
|
||||
import com.example.mtusi_messenger.service.AuthenticationService;
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth/sessions")
|
||||
@RequiredArgsConstructor
|
||||
public class SessionController {
|
||||
private final AuthenticationService authentication;
|
||||
|
||||
@PostMapping
|
||||
@SecurityRequirement(name = "basicAuth")
|
||||
public ResponseEntity<SessionResponse> create(@AuthenticationPrincipal User user) {
|
||||
var issued = authentication.issueSession(user);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(new SessionResponse(
|
||||
issued.token(),
|
||||
"Bearer",
|
||||
issued.expiresAt(),
|
||||
UserResponse.from(issued.user())));
|
||||
}
|
||||
|
||||
@DeleteMapping("/current")
|
||||
@SecurityRequirement(name = "bearerAuth")
|
||||
public ResponseEntity<Void> revoke(@AuthenticationPrincipal SessionPrincipal principal) {
|
||||
authentication.revoke(principal);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.example.mtusi_messenger.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.example.mtusi_messenger.dto.*;
|
||||
import com.example.mtusi_messenger.service.UserService;
|
||||
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/users")
|
||||
@RequiredArgsConstructor
|
||||
public class UserController {
|
||||
|
||||
private final UserService users;
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
|
||||
var user = users.create(request);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(UserResponse.from(user));
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
@SecurityRequirement(name = "bearerAuth")
|
||||
public UserResponse me(@AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return UserResponse.from(principal.user());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record ChatPageResponse(
|
||||
List<ChatResponse> items,
|
||||
String next_cursor
|
||||
) {}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
import com.example.mtusi_messenger.model.Chat;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record ChatResponse(UUID id,
|
||||
String title,
|
||||
List<UUID> member_ids,
|
||||
Instant created_at) {
|
||||
public static ChatResponse from(Chat c) {
|
||||
return new ChatResponse(
|
||||
c.id(),
|
||||
c.title(),
|
||||
c.memberIds(),
|
||||
c.createdAt()); }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
import com.example.mtusi_messenger.web.NotUnicodeBlank;
|
||||
import com.example.mtusi_messenger.web.UnicodeSize;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record CreateChatRequest(
|
||||
@NotUnicodeBlank
|
||||
@UnicodeSize(min = 1, max = 100)
|
||||
String title,
|
||||
|
||||
@NotEmpty
|
||||
@Size(min = 1, max = 100)
|
||||
List<UUID> member_ids
|
||||
) {}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
import com.example.mtusi_messenger.web.NotUnicodeBlank;
|
||||
import com.example.mtusi_messenger.web.UnicodeSize;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record CreateMessageRequest( @NotUnicodeBlank @UnicodeSize(min = 1, max = 4000) String text) {}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
import com.example.mtusi_messenger.web.NotUnicodeBlank;
|
||||
import com.example.mtusi_messenger.web.UnicodeSize;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
|
||||
public record CreateUserRequest(
|
||||
@NotBlank
|
||||
@Pattern(regexp = "[a-z0-9_]{3,32}")
|
||||
String username,
|
||||
|
||||
@NotUnicodeBlank
|
||||
@UnicodeSize(min = 1, max = 100)
|
||||
String display_name,
|
||||
|
||||
@NotUnicodeBlank
|
||||
@UnicodeSize(min = 12, max = 128)
|
||||
String password
|
||||
) {}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
public record ErrorResponse(ErrorBody error) {
|
||||
public record ErrorBody(String code,
|
||||
String message,
|
||||
String request_id)
|
||||
{}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
public record HealthResponse(String status) {}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record MessagePageResponse(
|
||||
List<MessageResponse> items,
|
||||
String next_cursor
|
||||
) {}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
import com.example.mtusi_messenger.model.Message;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public record MessageResponse(UUID id,
|
||||
UUID chat_id,
|
||||
UUID sender_id,
|
||||
String text,
|
||||
Instant created_at) {
|
||||
public static MessageResponse from(Message m) {
|
||||
return new MessageResponse(m.id(),
|
||||
m.chatId(),
|
||||
m.senderId(),
|
||||
m.text(),
|
||||
m.createdAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record SessionResponse(
|
||||
String token,
|
||||
String token_type,
|
||||
Instant expires_at,
|
||||
UserResponse user
|
||||
) {}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.example.mtusi_messenger.dto;
|
||||
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public record UserResponse(UUID id,
|
||||
String username,
|
||||
String display_name,
|
||||
Instant created_at) {
|
||||
public static UserResponse from(User u) {
|
||||
return new UserResponse(
|
||||
u.id(),
|
||||
u.username(),
|
||||
u.displayName(),
|
||||
u.createdAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.example.mtusi_messenger.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public class ApiException extends RuntimeException {
|
||||
private final String code; private final HttpStatus status; private final String authenticate;
|
||||
public ApiException(String code, HttpStatus status, String message) { this(code, status, message, null); }
|
||||
public ApiException(String code, HttpStatus status, String message, String authenticate) {
|
||||
super(message); this.code = code; this.status = status; this.authenticate = authenticate;
|
||||
}
|
||||
public String code() { return code; }
|
||||
public HttpStatus status() { return status; }
|
||||
public String authenticate() { return authenticate; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.example.mtusi_messenger.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public final class ApiExceptions {
|
||||
private ApiExceptions() {}
|
||||
public static ApiException invalid(String m) { return new ApiException("invalid_request", HttpStatus.BAD_REQUEST, m); }
|
||||
public static ApiException unauthorized(String m) { return unauthorizedBearer(m); }
|
||||
public static ApiException unauthorizedBasic(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Basic realm=\"messenger\", charset=\"UTF-8\""); }
|
||||
public static ApiException unauthorizedBearer(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Bearer realm=\"messenger\""); }
|
||||
public static ApiException notFound(String m) { return new ApiException("not_found", HttpStatus.NOT_FOUND, m); }
|
||||
public static ApiException conflict(String m) { return new ApiException("conflict", HttpStatus.CONFLICT, m); }
|
||||
public static ApiException unavailable(String m) { return new ApiException("unavailable", HttpStatus.SERVICE_UNAVAILABLE, m); }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.example.mtusi_messenger.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record Chat(UUID id, String title, List<UUID> memberIds, Instant createdAt) {
|
||||
public Chat {
|
||||
memberIds = List.copyOf(memberIds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.mtusi_messenger.model;
|
||||
|
||||
public record IdempotentMessage(byte[] requestHash, Message message) {}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.example.mtusi_messenger.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public record Message(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt) {}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.example.mtusi_messenger.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public record MessageKey(Instant createdAt, UUID id)
|
||||
implements Comparable<MessageKey> {
|
||||
|
||||
private static int compareUuidV7(UUID a, UUID b) {
|
||||
int result = Long.compareUnsigned(
|
||||
a.getMostSignificantBits(),
|
||||
b.getMostSignificantBits()
|
||||
);
|
||||
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return Long.compareUnsigned(
|
||||
a.getLeastSignificantBits(),
|
||||
b.getLeastSignificantBits()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(MessageKey other) {
|
||||
int result = createdAt.compareTo(other.createdAt);
|
||||
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return compareUuidV7(id, other.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.example.mtusi_messenger.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public record Session(UUID id, UUID userId, byte[] tokenHash, Instant createdAt, Instant expiresAt) {
|
||||
public Session {
|
||||
tokenHash = tokenHash.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] tokenHash() {
|
||||
return tokenHash.clone();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.example.mtusi_messenger.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public record User(UUID id, String username, String displayName, Instant createdAt) {}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.example.mtusi_messenger.repository;
|
||||
|
||||
import com.example.mtusi_messenger.model.Chat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ChatRepository {
|
||||
Chat save(Chat chat);
|
||||
Optional<Chat> findById(UUID id);
|
||||
boolean isMember(UUID chatId, UUID userId);
|
||||
List<Chat> findAllForUser(UUID userId);
|
||||
List<Chat> findPageForUser(UUID userId, UUID afterId, java.time.Instant afterCreatedAt, int limitPlusOne);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.example.mtusi_messenger.repository;
|
||||
|
||||
import com.example.mtusi_messenger.model.Message;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface MessageRepository {
|
||||
Message save(Message message);
|
||||
void lockIdempotencyScope(UUID userId, String method, String path, String key);
|
||||
void deleteExpiredIdempotency(UUID userId, String method, String path, String key, Instant expiresBefore);
|
||||
Optional<com.example.mtusi_messenger.model.IdempotentMessage> findIdempotent(
|
||||
UUID userId, String method, String path, String key);
|
||||
void saveIdempotency(UUID userId, String method, String path, String key,
|
||||
byte[] requestHash, UUID messageId, Instant createdAt);
|
||||
List<Message> findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.example.mtusi_messenger.repository;
|
||||
|
||||
import com.example.mtusi_messenger.model.Chat;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Repository
|
||||
public class PostgresChatRepository implements ChatRepository {
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
public PostgresChatRepository(JdbcTemplate jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(timeout = 5)
|
||||
public Chat save(Chat chat) {
|
||||
jdbc.update("""
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES (?, ?, ?)
|
||||
""", chat.id(), chat.title(), Timestamp.from(chat.createdAt()));
|
||||
|
||||
for (UUID memberId : chat.memberIds()) {
|
||||
jdbc.update("""
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
VALUES (?, ?)
|
||||
""", chat.id(), memberId);
|
||||
}
|
||||
return chat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Chat> findById(UUID id) {
|
||||
return jdbc.query("""
|
||||
SELECT id, title, created_at
|
||||
FROM chats
|
||||
WHERE id = ?
|
||||
""", (rs, rowNum) -> new ChatRow(
|
||||
rs.getObject("id", UUID.class),
|
||||
rs.getString("title"),
|
||||
rs.getTimestamp("created_at").toInstant()), id)
|
||||
.stream().findFirst()
|
||||
.map(this::toChat);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMember(UUID chatId, UUID userId) {
|
||||
return Boolean.TRUE.equals(jdbc.queryForObject("""
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM chat_members
|
||||
WHERE chat_id = ? AND user_id = ?
|
||||
)
|
||||
""", Boolean.class, chatId, userId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Chat> findAllForUser(UUID userId) {
|
||||
return findPageForUser(userId, null, null, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Chat> findPageForUser(UUID userId, UUID afterId, Instant afterCreatedAt, int limitPlusOne) {
|
||||
StringBuilder sql = new StringBuilder("""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = ?
|
||||
""");
|
||||
List<Object> parameters = new ArrayList<>();
|
||||
parameters.add(userId);
|
||||
|
||||
if (afterCreatedAt != null) {
|
||||
sql.append(" AND (c.created_at, c.id) > (?, ?) ");
|
||||
parameters.add(Timestamp.from(afterCreatedAt));
|
||||
parameters.add(afterId);
|
||||
}
|
||||
sql.append(" ORDER BY c.created_at, c.id LIMIT ? ");
|
||||
parameters.add(limitPlusOne);
|
||||
|
||||
return jdbc.query(sql.toString(), (rs, rowNum) -> new ChatRow(
|
||||
rs.getObject("id", UUID.class),
|
||||
rs.getString("title"),
|
||||
rs.getTimestamp("created_at").toInstant()), parameters.toArray())
|
||||
.stream().map(this::toChat).toList();
|
||||
}
|
||||
|
||||
private Chat toChat(ChatRow row) {
|
||||
List<UUID> members = jdbc.queryForList("""
|
||||
SELECT user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ?
|
||||
ORDER BY joined_at, user_id
|
||||
""", UUID.class, row.id());
|
||||
return new Chat(row.id(), row.title(), members, row.createdAt());
|
||||
}
|
||||
|
||||
private record ChatRow(UUID id, String title, Instant createdAt) {}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.example.mtusi_messenger.repository;
|
||||
|
||||
import com.example.mtusi_messenger.model.Message;
|
||||
import com.example.mtusi_messenger.model.IdempotentMessage;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Repository
|
||||
public class PostgresMessageRepository implements MessageRepository {
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
public PostgresMessageRepository(JdbcTemplate jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Message save(Message message) {
|
||||
jdbc.update("""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""", message.id(), message.chatId(), message.senderId(), message.text(),
|
||||
Timestamp.from(message.createdAt()));
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void lockIdempotencyScope(UUID userId, String method, String path, String key) {
|
||||
String scope = userId + "\n" + method + "\n" + path + "\n" + key;
|
||||
jdbc.query(
|
||||
"SELECT pg_advisory_xact_lock(hashtextextended(?, 0))",
|
||||
rs -> {
|
||||
rs.next();
|
||||
return null;
|
||||
},
|
||||
scope);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteExpiredIdempotency(
|
||||
UUID userId,
|
||||
String method,
|
||||
String path,
|
||||
String key,
|
||||
Instant expiresBefore
|
||||
) {
|
||||
jdbc.update("""
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = ?
|
||||
AND method = ?
|
||||
AND request_path = ?
|
||||
AND idempotency_key = ?
|
||||
AND created_at < ?
|
||||
""", userId, method, path, key, Timestamp.from(expiresBefore));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<IdempotentMessage> findIdempotent(
|
||||
UUID userId,
|
||||
String method,
|
||||
String path,
|
||||
String key
|
||||
) {
|
||||
return jdbc.query("""
|
||||
SELECT i.request_hash,
|
||||
m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM message_idempotency i
|
||||
JOIN messages m ON m.id = i.message_id
|
||||
WHERE i.user_id = ?
|
||||
AND i.method = ?
|
||||
AND i.request_path = ?
|
||||
AND i.idempotency_key = ?
|
||||
""", (rs, rowNum) -> new IdempotentMessage(
|
||||
rs.getBytes("request_hash"),
|
||||
new Message(
|
||||
rs.getObject("id", UUID.class),
|
||||
rs.getObject("chat_id", UUID.class),
|
||||
rs.getObject("sender_id", UUID.class),
|
||||
rs.getString("text"),
|
||||
rs.getTimestamp("created_at").toInstant())),
|
||||
userId, method, path, key).stream().findFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveIdempotency(
|
||||
UUID userId,
|
||||
String method,
|
||||
String path,
|
||||
String key,
|
||||
byte[] requestHash,
|
||||
UUID messageId,
|
||||
Instant createdAt
|
||||
) {
|
||||
jdbc.update("""
|
||||
INSERT INTO message_idempotency
|
||||
(user_id, method, request_path, idempotency_key,
|
||||
request_hash, message_id, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""", userId, method, path, key, requestHash, messageId,
|
||||
Timestamp.from(createdAt));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Message> findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne) {
|
||||
StringBuilder sql = new StringBuilder("""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = ?
|
||||
""");
|
||||
List<Object> parameters = new ArrayList<>();
|
||||
parameters.add(chatId);
|
||||
|
||||
if (afterCreatedAt != null) {
|
||||
sql.append(" AND (created_at, id) > (?, ?) ");
|
||||
parameters.add(Timestamp.from(afterCreatedAt));
|
||||
parameters.add(afterId);
|
||||
}
|
||||
sql.append(" ORDER BY created_at, id LIMIT ? ");
|
||||
parameters.add(limitPlusOne);
|
||||
|
||||
return jdbc.query(sql.toString(), (rs, rowNum) -> new Message(
|
||||
rs.getObject("id", UUID.class),
|
||||
rs.getObject("chat_id", UUID.class),
|
||||
rs.getObject("sender_id", UUID.class),
|
||||
rs.getString("text"),
|
||||
rs.getTimestamp("created_at").toInstant()), parameters.toArray());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.example.mtusi_messenger.repository;
|
||||
|
||||
import com.example.mtusi_messenger.model.Session;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Repository
|
||||
public class PostgresSessionRepository implements SessionRepository {
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
public PostgresSessionRepository(JdbcTemplate jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Session save(Session session) {
|
||||
jdbc.update("""
|
||||
INSERT INTO sessions (id, user_id, token_hash, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""", session.id(), session.userId(), session.tokenHash(),
|
||||
Timestamp.from(session.createdAt()), Timestamp.from(session.expiresAt()));
|
||||
return session;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<UUID> findActiveUserId(byte[] tokenHash) {
|
||||
return jdbc.query("""
|
||||
SELECT user_id
|
||||
FROM sessions
|
||||
WHERE token_hash = ?
|
||||
AND revoked_at IS NULL
|
||||
AND expires_at > CURRENT_TIMESTAMP
|
||||
""", (rs, rowNum) -> rs.getObject("user_id", UUID.class), tokenHash)
|
||||
.stream().findFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean revoke(byte[] tokenHash) {
|
||||
return jdbc.update("""
|
||||
UPDATE sessions
|
||||
SET revoked_at = CURRENT_TIMESTAMP
|
||||
WHERE token_hash = ?
|
||||
AND revoked_at IS NULL
|
||||
AND expires_at > CURRENT_TIMESTAMP
|
||||
""", tokenHash) == 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.example.mtusi_messenger.repository;
|
||||
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Repository
|
||||
public class PostgresUserRepository implements UserRepository {
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
public PostgresUserRepository(JdbcTemplate jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public User save(User user, String passwordHash) {
|
||||
jdbc.update("""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""", user.id(), user.username(), user.displayName(), passwordHash,
|
||||
Timestamp.from(user.createdAt()));
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findById(UUID id) {
|
||||
return jdbc.query("""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = ?
|
||||
""", (rs, rowNum) -> new User(
|
||||
rs.getObject("id", UUID.class),
|
||||
rs.getString("username"),
|
||||
rs.getString("display_name"),
|
||||
rs.getTimestamp("created_at").toInstant()), id)
|
||||
.stream().findFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByUsername(String username) {
|
||||
return jdbc.query("""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE username = ?
|
||||
""", (rs, rowNum) -> new User(
|
||||
rs.getObject("id", UUID.class),
|
||||
rs.getString("username"),
|
||||
rs.getString("display_name"),
|
||||
rs.getTimestamp("created_at").toInstant()), username)
|
||||
.stream().findFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<UserCredentials> findCredentialsByUsername(String username) {
|
||||
return jdbc.query("""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = ?
|
||||
""", (rs, rowNum) -> new UserCredentials(
|
||||
new User(
|
||||
rs.getObject("id", UUID.class),
|
||||
rs.getString("username"),
|
||||
rs.getString("display_name"),
|
||||
rs.getTimestamp("created_at").toInstant()),
|
||||
rs.getString("password_hash")), username)
|
||||
.stream().findFirst();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.example.mtusi_messenger.repository;
|
||||
|
||||
import com.example.mtusi_messenger.model.Session;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface SessionRepository {
|
||||
Session save(Session session);
|
||||
Optional<UUID> findActiveUserId(byte[] tokenHash);
|
||||
boolean revoke(byte[] tokenHash);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.example.mtusi_messenger.repository;
|
||||
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface UserRepository {
|
||||
User save(User user, String passwordHash);
|
||||
Optional<User> findById(UUID id);
|
||||
Optional<User> findByUsername(String username);
|
||||
Optional<UserCredentials> findCredentialsByUsername(String username);
|
||||
|
||||
record UserCredentials(User user, String passwordHash) {}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.example.mtusi_messenger.security;
|
||||
|
||||
import com.example.mtusi_messenger.service.AuthenticationService;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
|
||||
public class ApiAuthenticationFilter extends OncePerRequestFilter {
|
||||
private static final String AUTHORIZATION = "Authorization";
|
||||
private static final String SESSION_PATH = "/api/v1/auth/sessions";
|
||||
|
||||
private final AuthenticationManager authenticationManager;
|
||||
private final AuthenticationService sessions;
|
||||
private final RestAuthenticationEntryPoint basicEntryPoint;
|
||||
private final RestAuthenticationEntryPoint bearerEntryPoint;
|
||||
|
||||
public ApiAuthenticationFilter(
|
||||
AuthenticationManager authenticationManager,
|
||||
AuthenticationService sessions,
|
||||
RestAuthenticationEntryPoint basicEntryPoint,
|
||||
RestAuthenticationEntryPoint bearerEntryPoint
|
||||
) {
|
||||
this.authenticationManager = authenticationManager;
|
||||
this.sessions = sessions;
|
||||
this.basicEntryPoint = basicEntryPoint;
|
||||
this.bearerEntryPoint = bearerEntryPoint;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
boolean basicLogin = HttpMethod.POST.matches(request.getMethod())
|
||||
&& SESSION_PATH.equals(request.getRequestURI());
|
||||
if (isPublicRequest(request) && !basicLogin) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Authentication authentication = basicLogin
|
||||
? authenticateBasic(request)
|
||||
: authenticateBearer(request);
|
||||
var context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(authentication);
|
||||
SecurityContextHolder.setContext(context);
|
||||
filterChain.doFilter(request, response);
|
||||
} catch (AuthenticationException e) {
|
||||
SecurityContextHolder.clearContext();
|
||||
(basicLogin ? basicEntryPoint : bearerEntryPoint)
|
||||
.commence(request, response, e);
|
||||
} finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
|
||||
private Authentication authenticateBasic(HttpServletRequest request) {
|
||||
String header = singleAuthorizationHeader(request);
|
||||
if (!header.startsWith("Basic ") || header.length() == 6) {
|
||||
throw new BadCredentialsException("Invalid Basic credentials");
|
||||
}
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(header.substring(6));
|
||||
String credentials = new String(decoded, StandardCharsets.UTF_8);
|
||||
int separator = credentials.indexOf(':');
|
||||
if (separator <= 0) {
|
||||
throw new BadCredentialsException("Invalid Basic credentials");
|
||||
}
|
||||
return authenticationManager.authenticate(
|
||||
UsernamePasswordAuthenticationToken.unauthenticated(
|
||||
credentials.substring(0, separator),
|
||||
credentials.substring(separator + 1)));
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BadCredentialsException("Invalid Basic credentials", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Authentication authenticateBearer(HttpServletRequest request) {
|
||||
String header = singleAuthorizationHeader(request);
|
||||
if (!header.startsWith("Bearer ") || header.length() == 7) {
|
||||
throw new BadCredentialsException("Invalid Bearer token");
|
||||
}
|
||||
String token = header.substring(7);
|
||||
if (!token.matches("[A-Za-z0-9_-]{43}")) {
|
||||
throw new BadCredentialsException("Invalid Bearer token");
|
||||
}
|
||||
SessionPrincipal principal = sessions.authenticateBearer(token);
|
||||
return UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of());
|
||||
}
|
||||
|
||||
private String singleAuthorizationHeader(HttpServletRequest request) {
|
||||
Enumeration<String> values = request.getHeaders(AUTHORIZATION);
|
||||
if (values == null || !values.hasMoreElements()) {
|
||||
throw new BadCredentialsException("Authentication required");
|
||||
}
|
||||
String value = values.nextElement();
|
||||
if (values.hasMoreElements()) {
|
||||
throw new BadCredentialsException("Multiple Authorization headers");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private boolean isPublicRequest(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return path.startsWith("/health/")
|
||||
|| path.equals("/swagger-ui.html")
|
||||
|| path.startsWith("/swagger-ui/")
|
||||
|| path.equals("/v3/api-docs")
|
||||
|| path.startsWith("/v3/api-docs/")
|
||||
|| (HttpMethod.POST.matches(request.getMethod())
|
||||
&& "/api/v1/users".equals(path));
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.example.mtusi_messenger.security;
|
||||
|
||||
import com.example.mtusi_messenger.repository.UserRepository;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class DatabaseAuthenticationProvider implements AuthenticationProvider {
|
||||
private final UserRepository users;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final String dummyPasswordHash;
|
||||
|
||||
public DatabaseAuthenticationProvider(UserRepository users, PasswordEncoder passwordEncoder) {
|
||||
this.users = users;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||
String username = authentication.getName();
|
||||
String password = String.valueOf(authentication.getCredentials());
|
||||
final java.util.Optional<UserRepository.UserCredentials> stored;
|
||||
try {
|
||||
stored = users.findCredentialsByUsername(username);
|
||||
} catch (DataAccessException e) {
|
||||
throw new AuthenticationServiceException("Authentication database is unavailable", e);
|
||||
}
|
||||
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
|
||||
.filter(hash -> hash.startsWith("$argon2"))
|
||||
.orElse(dummyPasswordHash);
|
||||
|
||||
boolean matches;
|
||||
try {
|
||||
matches = passwordEncoder.matches(password, passwordHash);
|
||||
} catch (IllegalArgumentException e) {
|
||||
matches = false;
|
||||
}
|
||||
|
||||
if (stored.isEmpty() || !matches) {
|
||||
throw new BadCredentialsException("Invalid credentials");
|
||||
}
|
||||
|
||||
return UsernamePasswordAuthenticationToken.authenticated(
|
||||
stored.get().user(),
|
||||
null,
|
||||
List.of());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> authentication) {
|
||||
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.example.mtusi_messenger.security;
|
||||
|
||||
import com.example.mtusi_messenger.dto.ErrorResponse;
|
||||
import com.example.mtusi_messenger.web.RequestIdFilter;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
private final ObjectMapper mapper;
|
||||
private final String challenge;
|
||||
|
||||
public RestAuthenticationEntryPoint(ObjectMapper mapper, String challenge) {
|
||||
this.mapper = mapper;
|
||||
this.challenge = challenge;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commence(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
AuthenticationException exception
|
||||
) throws IOException {
|
||||
String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE);
|
||||
boolean unavailable = exception instanceof AuthenticationServiceException;
|
||||
response.setStatus(unavailable
|
||||
? HttpServletResponse.SC_SERVICE_UNAVAILABLE
|
||||
: HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
if (!unavailable) {
|
||||
response.setHeader("WWW-Authenticate", challenge);
|
||||
}
|
||||
mapper.writeValue(response.getOutputStream(), new ErrorResponse(
|
||||
new ErrorResponse.ErrorBody(
|
||||
unavailable ? "unavailable" : "unauthorized",
|
||||
unavailable ? "Authentication service temporarily unavailable" : "Authentication required",
|
||||
requestId)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.example.mtusi_messenger.security;
|
||||
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
|
||||
public record SessionPrincipal(User user, byte[] tokenHash) {
|
||||
public SessionPrincipal {
|
||||
tokenHash = tokenHash.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] tokenHash() {
|
||||
return tokenHash.clone();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.cache.UserCache;
|
||||
import com.example.mtusi_messenger.model.Session;
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import com.example.mtusi_messenger.repository.SessionRepository;
|
||||
import com.example.mtusi_messenger.repository.UserRepository;
|
||||
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class AuthenticationService {
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
private final UserRepository users;
|
||||
private final SessionRepository sessions;
|
||||
private final UserCache userCache;
|
||||
private final long ttlSeconds;
|
||||
|
||||
public AuthenticationService(
|
||||
UserRepository users,
|
||||
SessionRepository sessions,
|
||||
UserCache userCache,
|
||||
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
|
||||
) {
|
||||
if (ttlSeconds <= 0) {
|
||||
throw new IllegalArgumentException("Session TTL must be positive");
|
||||
}
|
||||
this.users = users;
|
||||
this.sessions = sessions;
|
||||
this.userCache = userCache;
|
||||
this.ttlSeconds = ttlSeconds;
|
||||
}
|
||||
|
||||
public IssuedSession issueSession(User user) {
|
||||
String token = newToken();
|
||||
Instant createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
|
||||
Instant expiresAt = createdAt.plusSeconds(ttlSeconds);
|
||||
sessions.save(new Session(
|
||||
UUID.randomUUID(),
|
||||
user.id(),
|
||||
hashToken(token),
|
||||
createdAt,
|
||||
expiresAt));
|
||||
return new IssuedSession(token, expiresAt, user);
|
||||
}
|
||||
|
||||
public SessionPrincipal authenticateBearer(String token) {
|
||||
byte[] tokenHash = hashToken(token);
|
||||
try {
|
||||
UUID userId = sessions.findActiveUserId(tokenHash)
|
||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||
User user = userCache.find(userId).orElseGet(() -> {
|
||||
User loaded = users.findById(userId)
|
||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||
userCache.put(loaded);
|
||||
return loaded;
|
||||
});
|
||||
return new SessionPrincipal(user, tokenHash);
|
||||
} catch (DataAccessException e) {
|
||||
throw new AuthenticationServiceException("Authentication database is unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void revoke(SessionPrincipal principal) {
|
||||
try {
|
||||
if (!sessions.revoke(principal.tokenHash())) {
|
||||
throw new BadCredentialsException("Invalid or expired session");
|
||||
}
|
||||
} catch (DataAccessException e) {
|
||||
throw new AuthenticationServiceException("Authentication database is unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String newToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
SECURE_RANDOM.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private byte[] hashToken(String token) {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256")
|
||||
.digest(token.getBytes(StandardCharsets.US_ASCII));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
public record IssuedSession(String token, Instant expiresAt, User user) {}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.example.mtusi_messenger.dto.CreateChatRequest;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import com.example.mtusi_messenger.model.Chat;
|
||||
import com.example.mtusi_messenger.repository.ChatRepository;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
public class ChatService {
|
||||
private final ChatRepository chats; private final UserService users; private final CursorService cursors;
|
||||
public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; }
|
||||
public Chat create(CreateChatRequest r, UUID caller) {
|
||||
Set<UUID> ids = new LinkedHashSet<>(r.member_ids());
|
||||
if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids");
|
||||
for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids");
|
||||
return chats.save(new Chat(UUID.randomUUID(), r.title(), List.copyOf(ids),
|
||||
Instant.now().truncatedTo(ChronoUnit.MICROS)));
|
||||
}
|
||||
public Chat getAccessible(UUID chatId, UUID userId) {
|
||||
users.get(userId);
|
||||
if (!chats.isMember(chatId, userId)) throw ApiExceptions.notFound("Chat not found");
|
||||
return chats.findById(chatId).orElseThrow(() -> ApiExceptions.notFound("Chat not found"));
|
||||
}
|
||||
public List<Chat> page(UUID userId, int limit, String cursor) {
|
||||
CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "chats", userId);
|
||||
return chats.findPageForUser(userId, c == null ? null : c.id(), c == null ? null : c.createdAt(), limit + 1);
|
||||
}
|
||||
public String nextCursor(UUID userId,
|
||||
Chat last,
|
||||
boolean hasNext
|
||||
) {
|
||||
return hasNext ? cursors.encode("chats", userId, last.createdAt(), last.id()) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.exception.ApiException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class CursorService {
|
||||
private final ObjectMapper mapper;
|
||||
public CursorService(ObjectMapper mapper) { this.mapper = mapper; }
|
||||
|
||||
public String encode(String resource, UUID resourceId, Instant createdAt, UUID id) {
|
||||
try {
|
||||
byte[] json = mapper.writeValueAsBytes(new CursorPayload(1, resource, resourceId, createdAt.toString(), id));
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(json);
|
||||
} catch (Exception e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
public Cursor decode(String raw, String resource, UUID resourceId) {
|
||||
if (raw == null || raw.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
|
||||
try {
|
||||
CursorPayload p = mapper.readValue(Base64.getUrlDecoder().decode(raw), CursorPayload.class);
|
||||
if (p.v != 1
|
||||
|| !resource.equals(p.resource)
|
||||
|| !Objects.equals(resourceId, p.resourceId)
|
||||
|| p.createdAt() == null
|
||||
|| p.createdAt().isBlank()
|
||||
|| p.id() == null
|
||||
) throw ApiExceptions.invalid("Invalid cursor");
|
||||
return new Cursor(Instant.parse(p.createdAt), p.id);
|
||||
} catch (ApiException e) { throw e; }
|
||||
catch (Exception e) { throw ApiExceptions.invalid("Invalid cursor"); }
|
||||
}
|
||||
public record Cursor(Instant createdAt, UUID id) {}
|
||||
private record CursorPayload(int v, String resource, UUID resourceId, String createdAt, UUID id) {}
|
||||
private static final class Objects { static boolean equals(Object a, Object b) { return java.util.Objects.equals(a,b); } }
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.github.f4b6a3.uuid.UuidCreator;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import com.example.mtusi_messenger.model.IdempotentMessage;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.example.mtusi_messenger.dto.CreateMessageRequest;
|
||||
import com.example.mtusi_messenger.model.Message;
|
||||
import com.example.mtusi_messenger.repository.MessageRepository;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class MessageService {
|
||||
private static final String METHOD = "POST";
|
||||
private final MessageRepository messages;
|
||||
private final ChatService chats;
|
||||
private final CursorService cursors;
|
||||
private final Duration idempotencyTtl;
|
||||
|
||||
public MessageService(
|
||||
MessageRepository messages,
|
||||
ChatService chats,
|
||||
CursorService cursors,
|
||||
@Value("${messenger.idempotency.ttl-seconds:86400}") long idempotencyTtlSeconds
|
||||
) {
|
||||
if (idempotencyTtlSeconds < 86400) {
|
||||
throw new IllegalArgumentException("Idempotency TTL must be at least 24 hours");
|
||||
}
|
||||
this.messages = messages;
|
||||
this.chats = chats;
|
||||
this.cursors = cursors;
|
||||
this.idempotencyTtl = Duration.ofSeconds(idempotencyTtlSeconds);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Message create(UUID chatId, UUID senderId, CreateMessageRequest r, String idempotencyKey) {
|
||||
chats.getAccessible(chatId, senderId);
|
||||
String path = "/api/v1/chats/" + chatId + "/messages";
|
||||
byte[] requestHash = hash(r.text());
|
||||
Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS);
|
||||
|
||||
// The transaction-scoped PostgreSQL advisory lock serializes the same
|
||||
// idempotency scope across every API replica. A hash collision only
|
||||
// causes harmless extra serialization; the full scope is still checked.
|
||||
messages.lockIdempotencyScope(senderId, METHOD, path, idempotencyKey);
|
||||
messages.deleteExpiredIdempotency(
|
||||
senderId, METHOD, path, idempotencyKey, now.minus(idempotencyTtl));
|
||||
|
||||
var existing = messages.findIdempotent(senderId, METHOD, path, idempotencyKey);
|
||||
if (existing.isPresent()) {
|
||||
IdempotentMessage value = existing.get();
|
||||
if (!Arrays.equals(value.requestHash(), requestHash)) {
|
||||
throw ApiExceptions.conflict("Idempotency-Key was already used with another request body");
|
||||
}
|
||||
return value.message();
|
||||
}
|
||||
|
||||
Message message = messages.save(new Message(
|
||||
UuidCreator.getTimeOrderedEpochPlus1(), chatId, senderId, r.text(), now));
|
||||
messages.saveIdempotency(
|
||||
senderId, METHOD, path, idempotencyKey, requestHash, message.id(), now);
|
||||
return message;
|
||||
}
|
||||
|
||||
private static byte[] hash(String text) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return digest.digest(text.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is unavailable", e);
|
||||
}
|
||||
}
|
||||
public List<Message> page(UUID chatId, UUID userId, int limit, String cursor) {
|
||||
chats.getAccessible(chatId, userId);
|
||||
CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "messages", chatId);
|
||||
return messages.findPage(chatId, c == null ? null : c.createdAt(), c == null ? null : c.id(), limit + 1);
|
||||
}
|
||||
public String nextCursor(UUID chatId, Message last, boolean hasNext) { return hasNext ? cursors.encode("messages", chatId, last.createdAt(), last.id()) : null; }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import com.example.mtusi_messenger.dto.CreateUserRequest;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import com.example.mtusi_messenger.repository.UserRepository;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
private final UserRepository users;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public User create(CreateUserRequest r) {
|
||||
String username = r.username(); String display = r.display_name();
|
||||
if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken");
|
||||
String passwordHash = passwordEncoder.encode(r.password());
|
||||
try {
|
||||
return users.save(new User(UUID.randomUUID(), username, display,
|
||||
Instant.now().truncatedTo(ChronoUnit.MICROS)), passwordHash);
|
||||
} catch (DuplicateKeyException e) {
|
||||
throw ApiExceptions.conflict("Username is already taken");
|
||||
}
|
||||
}
|
||||
public User get(UUID id) { return users.findById(id).orElseThrow(() -> ApiExceptions.unauthorized("Unknown user identity")); }
|
||||
public boolean exists(UUID id) { return users.findById(id).isPresent(); }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class UuidValidator {
|
||||
|
||||
private static final Pattern UUID_PATTERN = Pattern.compile(
|
||||
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
||||
);
|
||||
|
||||
private UuidValidator() {}
|
||||
|
||||
public static UUID parse(String value) {
|
||||
if (value == null || !UUID_PATTERN.matcher(value).matches()) {
|
||||
throw ApiExceptions.invalid("Invalid UUID");
|
||||
}
|
||||
|
||||
try {
|
||||
return UUID.fromString(value);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw ApiExceptions.invalid("Invalid UUID");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.example.mtusi_messenger.web;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import com.example.mtusi_messenger.dto.ErrorResponse;
|
||||
import com.example.mtusi_messenger.exception.ApiException;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
@ExceptionHandler(ApiException.class)
|
||||
ResponseEntity<ErrorResponse> api(ApiException e, HttpServletRequest req) {
|
||||
var body = body(e.code(), e.getMessage(), req);
|
||||
var builder = ResponseEntity.status(e.status());
|
||||
if (e.status() == HttpStatus.UNAUTHORIZED && e.authenticate() != null) {
|
||||
builder.header("WWW-Authenticate", e.authenticate());
|
||||
}
|
||||
return builder.body(body);
|
||||
}
|
||||
@ExceptionHandler({MethodArgumentNotValidException.class, MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class})
|
||||
ResponseEntity<ErrorResponse> bad(Exception e, HttpServletRequest req) { return ResponseEntity.badRequest().body(body("invalid_request", "Invalid request", req)); }
|
||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||
ResponseEntity<ErrorResponse> unsupported(HttpServletRequest req) { return ResponseEntity.status(415).body(body("unsupported_media_type", "Unsupported media type", req)); }
|
||||
@ExceptionHandler(DataAccessException.class)
|
||||
ResponseEntity<ErrorResponse> unavailable(DataAccessException e, HttpServletRequest req) {
|
||||
return ResponseEntity.status(503).body(body("unavailable", "Storage temporarily unavailable", req));
|
||||
}
|
||||
@ExceptionHandler(Exception.class)
|
||||
ResponseEntity<ErrorResponse> internal(Exception e, HttpServletRequest req) { return ResponseEntity.status(500).body(body("internal_error", "Internal server error", req)); }
|
||||
private ErrorResponse body(
|
||||
String code,
|
||||
String message,
|
||||
HttpServletRequest req
|
||||
) {
|
||||
String id = (String) req.getAttribute(RequestIdFilter.ATTRIBUTE);
|
||||
|
||||
return new ErrorResponse(
|
||||
new ErrorResponse.ErrorBody(code, message, id)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.example.mtusi_messenger.web;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.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.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
|
||||
public class InstanceIdFilter extends OncePerRequestFilter {
|
||||
public static final String HEADER = "X-Instance-Id";
|
||||
private final String instanceId;
|
||||
|
||||
public InstanceIdFilter() {
|
||||
String configured = System.getenv("INSTANCE_ID");
|
||||
this.instanceId = configured == null || configured.isBlank()
|
||||
? localHostOrRandom()
|
||||
: configured;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
response.setHeader(HEADER, instanceId);
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private static String localHostOrRandom() {
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostName();
|
||||
} catch (UnknownHostException e) {
|
||||
return "api-" + UUID.randomUUID();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.example.mtusi_messenger.web;
|
||||
|
||||
import jakarta.validation.Constraint;
|
||||
import jakarta.validation.Payload;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
@Documented
|
||||
@Constraint(validatedBy = UnicodeBlankValidator.class)
|
||||
@Target({ FIELD, PARAMETER, RECORD_COMPONENT, ANNOTATION_TYPE })
|
||||
@Retention(RUNTIME)
|
||||
public @interface NotUnicodeBlank {
|
||||
String message() default "must not be blank";
|
||||
Class<?>[] groups() default {};
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.example.mtusi_messenger.web;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class RequestIdFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String HEADER = "X-Request-Id";
|
||||
public static final String ATTRIBUTE = "request_id";
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest req,
|
||||
HttpServletResponse res,
|
||||
FilterChain chain
|
||||
) throws ServletException, IOException {
|
||||
|
||||
String id = UUID.randomUUID().toString();
|
||||
|
||||
req.setAttribute(ATTRIBUTE, id);
|
||||
res.setHeader(HEADER, id);
|
||||
|
||||
try {
|
||||
chain.doFilter(req, res);
|
||||
} finally {
|
||||
MDC.remove(ATTRIBUTE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.example.mtusi_messenger.web;
|
||||
|
||||
import jakarta.validation.ConstraintValidator;
|
||||
import jakarta.validation.ConstraintValidatorContext;
|
||||
|
||||
public class UnicodeBlankValidator
|
||||
implements ConstraintValidator<NotUnicodeBlank, String> {
|
||||
|
||||
@Override
|
||||
public boolean isValid(
|
||||
String value,
|
||||
ConstraintValidatorContext context) {
|
||||
|
||||
if (value == null || value.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return value.codePoints().anyMatch(codePoint ->
|
||||
!Character.isWhitespace(codePoint)
|
||||
&& !Character.isSpaceChar(codePoint)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.example.mtusi_messenger.web;
|
||||
import jakarta.validation.Constraint;
|
||||
import jakarta.validation.Payload;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
|
||||
import static java.lang.annotation.ElementType.FIELD;
|
||||
import static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.ElementType.PARAMETER;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
@Documented
|
||||
@Constraint(validatedBy = UnicodeSizeValidator.class)
|
||||
@Target({
|
||||
FIELD,
|
||||
METHOD,
|
||||
PARAMETER,
|
||||
ANNOTATION_TYPE
|
||||
})
|
||||
@Retention(RUNTIME)
|
||||
public @interface UnicodeSize {
|
||||
|
||||
String message() default "size must be between {min} and {max} Unicode code points";
|
||||
|
||||
int min() default 0;
|
||||
|
||||
int max() default Integer.MAX_VALUE;
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.example.mtusi_messenger.web;
|
||||
|
||||
import jakarta.validation.ConstraintValidator;
|
||||
import jakarta.validation.ConstraintValidatorContext;
|
||||
|
||||
public class UnicodeSizeValidator
|
||||
implements ConstraintValidator<UnicodeSize, String> {
|
||||
|
||||
private int min;
|
||||
private int max;
|
||||
|
||||
@Override
|
||||
public void initialize(UnicodeSize annotation) {
|
||||
this.min = annotation.min();
|
||||
this.max = annotation.max();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(
|
||||
String value,
|
||||
ConstraintValidatorContext context
|
||||
) {
|
||||
if (value == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
int codePointCount = value.codePointCount(0, value.length());
|
||||
|
||||
return codePointCount >= min
|
||||
&& codePointCount <= max;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user