fix problems

This commit is contained in:
2026-10-30 11:07:02 +03:00
parent e3a6372e91
commit b94b07654f
7 changed files with 71 additions and 12 deletions
+6
View File
@@ -9,3 +9,9 @@ POSTGRES_USER=messenger
POSTGRES_PASSWORD=change-me-local-only
REDIS_HOST=redis
REDIS_PORT=6379
DB_POOL_SIZE=4
DB_CONNECTION_TIMEOUT_MS=1000
DB_REQUEST_TIMEOUT_MS=2000
DB_SOCKET_TIMEOUT_SECONDS=1
DB_STATEMENT_TIMEOUT_MS=1000
DB_QUERY_TIMEOUT_SECONDS=1
+1 -1
View File
@@ -30,7 +30,7 @@ Spring Boot API работает от имени непривилегирова
Пароль при регистрации не возвращается и хранится как SCrypt-хеш. `POST /api/v1/auth/sessions` принимает только Basic `username:password`, создаёт случайный 256-битный opaque Bearer-токен и сохраняет его в Redis с TTL `SESSION_TTL_SECONDS`. Redis включён с AOF и named volume, поэтому действующие сессии переживают проверяемый рестарт. Logout удаляет ключ сессии. Бизнес-endpoint используют только Bearer; `X-User-Id` игнорируется.
История использует keyset-запрос по `(chat_id, created_at, id)` с индексом `idx_messages_chat_created_id`. Страница получает `limit + 1` строк, а cursor кодируется и подписывается HMAC. Таймауты и размер пула PostgreSQL задаются в `application.properties`. При недоступности PostgreSQL или Redis API возвращает ограниченную ошибку `503 unavailable`.
История использует keyset-запрос по `(chat_id, created_at, id)` с индексом `idx_messages_chat_created_id`. Страница получает `limit + 1` строк, а cursor кодируется и подписывается HMAC. PostgreSQL ограничен пулом из 4 соединений; `socketTimeout` и `statement_timeout` ограничены 1 секундой, а серверный deadline DB-операции — 2 секундами. При недоступности PostgreSQL или Redis API возвращает ограниченную ошибку `503 unavailable`.
## Доказательства критериев
+3 -1
View File
@@ -35,7 +35,9 @@ final class Input {
if (node == null || !node.isTextual()) throw ApiException.invalid("Пароль должен быть строкой");
String value = node.textValue();
int length = value.codePointCount(0, value.length());
if (length < 12 || length > 128) throw ApiException.invalid("Пароль должен содержать от 12 до 128 символов");
if (length < 12 || length > 128 || value.codePoints().allMatch(Input::isUnicodeWhitespace)) {
throw ApiException.invalid("Пароль должен содержать от 12 до 128 непробельных символов");
}
return value;
}
@@ -30,7 +30,10 @@ public class MessengerController {
@PostMapping(value = "/auth/sessions", consumes = "*/*")
@ResponseStatus(HttpStatus.CREATED)
Session login(HttpServletRequest request) {
Session login(HttpServletRequest request) throws java.io.IOException {
if (request.getInputStream().read() != -1) {
throw ApiException.invalid("Вход не принимает тело запроса");
}
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Basic ")) throw ApiException.unauthorized();
try {
@@ -1,15 +1,22 @@
package ru.mtusi.messenger;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static ru.mtusi.messenger.Models.*;
@@ -21,16 +28,22 @@ public class SessionService {
private final SCryptPasswordEncoder passwords = SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8();
private final SecureRandom random = new SecureRandom();
private final long ttlSeconds;
private final long databaseTimeoutMillis;
private final ExecutorService databaseExecutor = Executors.newFixedThreadPool(4);
public SessionService(MessengerStore store, StringRedisTemplate redis,
@Value("${SESSION_TTL_SECONDS:3600}") long ttlSeconds) {
this.store = store; this.redis = redis; this.ttlSeconds = Math.max(2, ttlSeconds);
@Value("${SESSION_TTL_SECONDS:3600}") long ttlSeconds,
@Value("${DB_REQUEST_TIMEOUT_MS:2000}") long databaseTimeoutMillis) {
this.store = store;
this.redis = redis;
this.ttlSeconds = Math.max(2, ttlSeconds);
this.databaseTimeoutMillis = Math.max(250, databaseTimeoutMillis);
}
public String hash(String password) { return passwords.encode(password); }
public Session login(String username, String password) {
Credentials credentials = store.credentials(username);
Credentials credentials = database(() -> store.credentials(username));
if (credentials == null || !passwords.matches(password, credentials.passwordHash())) throw ApiException.unauthorized();
byte[] bytes = new byte[32];
random.nextBytes(bytes);
@@ -50,7 +63,7 @@ public class SessionService {
try { value = redis.opsForValue().get(key(token)); }
catch (RuntimeException exception) { throw new ApiException(503, "unavailable", "Сервис сессий недоступен"); }
if (value == null) throw ApiException.unauthorized();
User user = store.findUser(java.util.UUID.fromString(value));
User user = database(() -> store.findUser(UUID.fromString(value)));
if (user == null) throw ApiException.unauthorized();
return user;
}
@@ -64,4 +77,26 @@ public class SessionService {
public void check() { redis.opsForValue().get("messenger:readiness"); }
private String key(String token) { return "messenger:session:" + token; }
private <T> T database(java.util.concurrent.Callable<T> operation) {
Future<T> future = databaseExecutor.submit(operation);
try {
return future.get(databaseTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (TimeoutException exception) {
future.cancel(true);
throw new ApiException(503, "unavailable", "Хранилище данных недоступно");
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new ApiException(503, "unavailable", "Хранилище данных недоступно");
} catch (ExecutionException exception) {
Throwable cause = exception.getCause();
if (cause instanceof RuntimeException runtime) throw runtime;
throw new IllegalStateException(cause);
}
}
@PreDestroy
void shutdownDatabaseExecutor() {
databaseExecutor.shutdownNow();
}
}
+9 -4
View File
@@ -4,13 +4,18 @@ server.port=${APP_PORT:8080}
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=5s
spring.datasource.url=${DATABASE_URL:jdbc:postgresql://${DB_HOST:postgres}:${DB_PORT:5432}/${DB_NAME:messenger}}
spring.datasource.url=${DATABASE_URL:jdbc:postgresql://${DB_HOST:postgres}:${DB_PORT:5432}/${DB_NAME:messenger}?socketTimeout=1&options=-c%20statement_timeout%3D1000}
spring.datasource.username=${DB_USERNAME:messenger}
spring.datasource.password=${DB_PASSWORD:messenger}
spring.datasource.hikari.maximum-pool-size=${DB_POOL_SIZE:10}
spring.datasource.hikari.connection-timeout=${DB_CONNECTION_TIMEOUT_MS:3000}
spring.datasource.hikari.validation-timeout=1000
spring.datasource.hikari.maximum-pool-size=${DB_POOL_SIZE:4}
spring.datasource.hikari.connection-timeout=${DB_CONNECTION_TIMEOUT_MS:1000}
spring.datasource.hikari.validation-timeout=250
spring.datasource.hikari.transaction-isolation=TRANSACTION_READ_COMMITTED
# Connection timeout only limits waiting for a free pool slot. These settings
# also bound an already running PostgreSQL statement and socket read.
spring.datasource.hikari.data-source-properties.[socketTimeout]=${DB_SOCKET_TIMEOUT_SECONDS:1}
spring.datasource.hikari.data-source-properties.[options]=-c statement_timeout=${DB_STATEMENT_TIMEOUT_MS:1000}
spring.jdbc.template.query-timeout=${DB_QUERY_TIMEOUT_SECONDS:1}s
spring.data.redis.host=${REDIS_HOST:redis}
spring.data.redis.port=${REDIS_PORT:6379}
+8
View File
@@ -42,6 +42,14 @@ def main():
bob = c.user("grade4_bob")
# Basic is only for login; business endpoints require the returned Bearer token.
c.call("POST", "/api/v1/users", 400, body={
"username": "spaces_" + uuid.uuid4().hex[:16],
"display_name": "Whitespace",
"password": "\u0085" * 12,
})
c.call("POST", "/api/v1/auth/sessions", 400,
headers={**basic(alice["registration"]["username"], alice["registration"]["password"]),
"Content-Type": "application/json"}, raw=b"{}")
wrong = c.call("POST", "/api/v1/auth/sessions", 401,
headers=basic(alice["registration"]["username"], "wrong-password-123"))
check(wrong["headers"].get("WWW-Authenticate", "").startswith("Basic"),