Исправить проверки lab2
Исправить Unicode-границы, пароль, токены, пагинацию и ответы зависимостей. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -5,8 +5,11 @@ import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.*;
|
||||
import org.springframework.boot.*;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
@@ -15,9 +18,13 @@ import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import com.fasterxml.jackson.databind.MapperFeature;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.*;
|
||||
import java.util.*;
|
||||
import java.util.Base64;
|
||||
@@ -40,6 +47,12 @@ public class MessengerApplication {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
// Отключаем автоматическое превращение чисел в строки при чтении JSON.
|
||||
@Bean
|
||||
Jackson2ObjectMapperBuilderCustomizer strictJson() {
|
||||
return builder -> builder.featuresToDisable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
|
||||
}
|
||||
|
||||
// @Bean регистрирует фильтр в контейнере Spring.
|
||||
// Фильтр добавляет общий идентификатор каждому HTTP-ответу.
|
||||
@Bean OncePerRequestFilter requestId() {
|
||||
@@ -71,11 +84,11 @@ public class MessengerApplication {
|
||||
// Ответ успешного входа с Bearer-токеном.
|
||||
record Session(String token, String token_type, Instant expires_at, User user) {}
|
||||
// Тело запроса регистрации.
|
||||
record UserIn(String username, String display_name, String password) {}
|
||||
record UserIn(JsonNode username, JsonNode display_name, JsonNode password) {}
|
||||
// Тело запроса создания чата.
|
||||
record ChatIn(String title, List<UUID> member_ids) {}
|
||||
record ChatIn(JsonNode title, List<UUID> member_ids) {}
|
||||
// Тело запроса отправки сообщения.
|
||||
record MessageIn(String text) {}
|
||||
record MessageIn(JsonNode text) {}
|
||||
// Поля внутренней ошибки API.
|
||||
record Error(String code, String message, String request_id) {}
|
||||
// Обёртка, требуемая форматом JSON ошибки.
|
||||
@@ -106,6 +119,8 @@ public class MessengerApplication {
|
||||
final StringRedisTemplate redis;
|
||||
// BCryptPasswordEncoder проверяет и хеширует пароли.
|
||||
final BCryptPasswordEncoder encoder;
|
||||
// Генератор создаёт 32 случайных байта для каждой сессии.
|
||||
final SecureRandom random = new SecureRandom();
|
||||
// TTL можно уменьшить через переменную окружения для проверки expiry.
|
||||
final long ttl = Long.parseLong(System.getenv().getOrDefault("SESSION_TTL_SECONDS", "3600"));
|
||||
Api(JdbcTemplate d, StringRedisTemplate r, BCryptPasswordEncoder e) {
|
||||
@@ -146,6 +161,19 @@ public class MessengerApplication {
|
||||
// Пользователь должен состоять в чате, иначе ресурс для него скрыт.
|
||||
return Boolean.TRUE.equals(db.queryForObject("select exists(select 1 from chat_members where chat_id=? and user_id=?)",Boolean.class,chat,user));
|
||||
}
|
||||
// Считает символы как Unicode code points, а не как UTF-16 char.
|
||||
int codePointLength(String value) {
|
||||
return value.codePointCount(0,value.length());
|
||||
}
|
||||
// Возвращает значение только если JSON-поле действительно является строкой.
|
||||
String string(JsonNode value) { return value!=null && value.isTextual()?value.textValue():null; }
|
||||
// Проверяет обязательную непустую строку и её максимальную длину.
|
||||
boolean text(String value, int max) { return value!=null && !value.isBlank() && codePointLength(value)<=max; }
|
||||
// Предварительный SHA-256 сохраняет весь пароль перед ограниченным BCrypt.
|
||||
String passwordValue(String value) {
|
||||
try { return Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); }
|
||||
catch (Exception e) { throw new IllegalStateException("password hashing is unavailable",e); }
|
||||
}
|
||||
|
||||
// Готовность проверяет не только Java-процесс, но и его зависимости.
|
||||
// @GetMapping связывает GET-запрос с Java-методом.
|
||||
@@ -157,16 +185,19 @@ public class MessengerApplication {
|
||||
@PostMapping("/api/v1/users")
|
||||
// @RequestBody преобразует JSON-тело запроса в объект UserIn.
|
||||
ResponseEntity<User> register(@RequestBody UserIn in) {
|
||||
String username=in==null?null:string(in.username());
|
||||
String displayName=in==null?null:string(in.display_name());
|
||||
String password=in==null?null:string(in.password());
|
||||
// До запроса в базу проверяем формат обязательных полей.
|
||||
if(in==null || in.username()==null || !in.username().matches("[a-z0-9_]{3,32}") || in.display_name()==null || in.display_name().isBlank() || in.display_name().length()>100 || in.password()==null || in.password().length()<12 || in.password().length()>128) bad();
|
||||
if(username==null || !username.matches("[a-z0-9_]{3,32}") || !text(displayName,100) || password==null || codePointLength(password)<12 || codePointLength(password)>128) bad();
|
||||
// Создаём UUID пользователя и фиксируем время регистрации.
|
||||
UUID id=UUID.randomUUID(); Instant now=Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS);
|
||||
// Значения передаются параметрами, а не склеиваются со строкой SQL.
|
||||
try { db.update("insert into users values(?,?,?,?,?)",id,in.username(),in.display_name(),encoder.encode(in.password()),java.sql.Timestamp.from(now)); }
|
||||
try { db.update("insert into users values(?,?,?,?,?)",id,username,displayName,encoder.encode(passwordValue(password)),java.sql.Timestamp.from(now)); }
|
||||
// Уникальное ограничение username превращаем в понятный ответ 409.
|
||||
catch(DuplicateKeyException e) { throw new ApiException(HttpStatus.CONFLICT,"conflict","username is already used"); }
|
||||
// Возвращаем созданного пользователя без пароля.
|
||||
return ResponseEntity.status(201).body(new User(id,in.username(),in.display_name(),now));
|
||||
return ResponseEntity.status(201).body(new User(id,username,displayName,now));
|
||||
}
|
||||
// POST-метод входа проверяет Basic-логин и создаёт Bearer-сессию.
|
||||
@PostMapping("/api/v1/auth/sessions")
|
||||
@@ -180,11 +211,12 @@ public class MessengerApplication {
|
||||
// Получаем BCrypt-хеш пользователя из PostgreSQL.
|
||||
String hash=p.length==2 ? db.query("select password_hash from users where username=?",rs -> rs.next()?rs.getString(1):null,p[0]) : null;
|
||||
// Сравниваем введённый пароль с сохранённым хешем.
|
||||
if(p.length!=2 || hash==null || !encoder.matches(p[1],hash)) { HttpHeaders x=new HttpHeaders(); x.set("WWW-Authenticate","Basic realm=\"messenger\", charset=\"UTF-8\""); throw new ApiException(HttpStatus.UNAUTHORIZED,"unauthorized","invalid credentials"); }
|
||||
if(p.length!=2 || hash==null || codePointLength(p[1])<12 || codePointLength(p[1])>128 || !encoder.matches(passwordValue(p[1]),hash)) { HttpHeaders x=new HttpHeaders(); x.set("WWW-Authenticate","Basic realm=\"messenger\", charset=\"UTF-8\""); throw new ApiException(HttpStatus.UNAUTHORIZED,"unauthorized","invalid credentials"); }
|
||||
// После успешной проверки загружаем полную модель пользователя.
|
||||
User u=user(db.queryForObject("select id from users where username=?",UUID.class,p[0]));
|
||||
// Генерируем непрозрачный случайный токен сессии.
|
||||
String token=Base64.getUrlEncoder().withoutPadding().encodeToString(new byte[32]); token=UUID.randomUUID()+token;
|
||||
byte[] secret=new byte[32]; random.nextBytes(secret);
|
||||
String token=Base64.getUrlEncoder().withoutPadding().encodeToString(secret);
|
||||
// Вычисляем момент, когда сессия перестанет действовать.
|
||||
Instant exp=Instant.now().plusSeconds(ttl);
|
||||
// Сессия автоматически удалится из Redis после окончания TTL.
|
||||
@@ -203,25 +235,41 @@ public class MessengerApplication {
|
||||
// POST-запрос создаёт новый чат.
|
||||
@PostMapping("/api/v1/chats") ResponseEntity<Chat> createChat(@RequestBody ChatIn in,HttpServletRequest r) {
|
||||
// Владелец чата определяется по Bearer-сессии.
|
||||
UUID owner=auth(r); if(in==null||in.title()==null||in.title().isBlank()||in.member_ids()==null||in.member_ids().isEmpty()||new HashSet<>(in.member_ids()).size()!=in.member_ids().size()||!in.member_ids().contains(owner)) bad();
|
||||
String title=in==null?null:string(in.title());
|
||||
UUID owner=auth(r); if(!text(title,100)||in.member_ids()==null||in.member_ids().isEmpty()||in.member_ids().size()>100||new HashSet<>(in.member_ids()).size()!=in.member_ids().size()||!in.member_ids().contains(owner)) bad();
|
||||
// Проверяем существование каждого участника.
|
||||
for(UUID id:in.member_ids()) if(user(id)==null) bad();
|
||||
// ID и время создаются сервером.
|
||||
UUID id=UUID.randomUUID(); Instant now=Instant.now();
|
||||
// Записываем чат и участников в одной транзакции.
|
||||
db.update("insert into chats values(?,?,?)",id,in.title(),java.sql.Timestamp.from(now)); for(UUID m:in.member_ids()) db.update("insert into chat_members values(?,?)",id,m);
|
||||
db.update("insert into chats values(?,?,?)",id,title,java.sql.Timestamp.from(now)); for(UUID m:in.member_ids()) db.update("insert into chat_members values(?,?)",id,m);
|
||||
// Возвращаем созданную модель чата.
|
||||
return ResponseEntity.status(201).body(new Chat(id,in.title(),in.member_ids(),now));
|
||||
return ResponseEntity.status(201).body(new Chat(id,title,in.member_ids(),now));
|
||||
}
|
||||
// GET-запрос получает список чатов текущего пользователя.
|
||||
@GetMapping("/api/v1/chats")
|
||||
Page<Chat> chats(HttpServletRequest r) {
|
||||
// Определяем пользователя, для которого строится список.
|
||||
UUID u=auth(r);
|
||||
String cursor=r.getParameter("cursor");
|
||||
int limit=parseLimit(r.getParameter("limit"));
|
||||
// Запрашиваем только чаты, где пользователь является участником.
|
||||
List<Chat> x=db.query("select c.id,c.title,c.created_at from chats c join chat_members m on m.chat_id=c.id where m.user_id=? order by c.created_at,c.id", (rs,n)->new Chat(rs.getObject(1,UUID.class),rs.getString(2),db.query("select user_id from chat_members where chat_id=?", (z,k)->z.getObject(1,UUID.class),rs.getObject(1)),rs.getTimestamp(3).toInstant()),u);
|
||||
// Возвращаем список как страницу без следующего cursor.
|
||||
return new Page<>(x,null);
|
||||
String sql="select c.id,c.title,c.created_at from chats c join chat_members m on m.chat_id=c.id where m.user_id=? ";
|
||||
List<Object> args=new ArrayList<>(List.of(u));
|
||||
if(cursor!=null) {
|
||||
try {
|
||||
String[] p=new String(Base64.getUrlDecoder().decode(cursor),StandardCharsets.UTF_8).split("\\|",-1);
|
||||
if(p.length!=2) bad();
|
||||
sql+="and (c.created_at,c.id)>(?,?) ";
|
||||
args.add(java.sql.Timestamp.from(OffsetDateTime.parse(p[0]).toInstant()));
|
||||
args.add(UUID.fromString(p[1]));
|
||||
} catch(Exception e) { if(e instanceof ApiException a) throw a; bad(); }
|
||||
}
|
||||
sql+="order by c.created_at,c.id limit ?";
|
||||
args.add(limit+1);
|
||||
List<Chat> x=db.query(sql,(rs,n)->new Chat(rs.getObject(1,UUID.class),rs.getString(2),db.query("select user_id from chat_members where chat_id=?", (z,k)->z.getObject(1,UUID.class),rs.getObject(1)),rs.getTimestamp(3).toInstant()),args.toArray());
|
||||
String next=x.size()>limit?Base64.getUrlEncoder().withoutPadding().encodeToString((x.get(limit-1).created_at()+"|"+x.get(limit-1).id()).getBytes(StandardCharsets.UTF_8)):null;
|
||||
return new Page<>(x.subList(0,Math.min(limit,x.size())),next);
|
||||
}
|
||||
// {id} является переменной частью URL.
|
||||
@GetMapping("/api/v1/chats/{id}")
|
||||
@@ -236,9 +284,10 @@ public class MessengerApplication {
|
||||
// @PathVariable получает id чата, а @RequestBody — текст из JSON.
|
||||
@PostMapping("/api/v1/chats/{id}/messages") ResponseEntity<Message> message(@PathVariable UUID id,@RequestBody MessageIn in,HttpServletRequest r) {
|
||||
// Автор сообщения берётся из сессии, а не из тела запроса.
|
||||
UUID u=auth(r); if(!member(id,u)) throw notFound(); if(in==null||in.text()==null||in.text().isBlank()||in.text().length()>4000) bad();
|
||||
String messageText=in==null?null:string(in.text());
|
||||
UUID u=auth(r); if(!member(id,u)) throw notFound(); if(!text(messageText,4000)) bad();
|
||||
// Сервер создаёт ID и время сообщения.
|
||||
UUID mid=UUID.randomUUID(); Instant now=Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS); db.update("insert into messages values(?,?,?,?,?)",mid,id,u,in.text(),java.sql.Timestamp.from(now)); return ResponseEntity.status(201).body(new Message(mid,id,u,in.text(),now));
|
||||
UUID mid=UUID.randomUUID(); Instant now=Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS); db.update("insert into messages values(?,?,?,?,?)",mid,id,u,messageText,java.sql.Timestamp.from(now)); return ResponseEntity.status(201).body(new Message(mid,id,u,messageText,now));
|
||||
}
|
||||
// GET-запрос возвращает историю сообщений с cursor-пагинацией.
|
||||
// @RequestParam получает limit и cursor из параметров URL.
|
||||
@@ -253,9 +302,10 @@ public class MessengerApplication {
|
||||
try {
|
||||
// Cursor хранит время и ID последнего сообщения предыдущей страницы.
|
||||
// Декодируем cursor из Base64 в обычную строку.
|
||||
String[] p=new String(Base64.getUrlDecoder().decode(cursor),StandardCharsets.UTF_8).split("\\|");
|
||||
String[] p=new String(Base64.getUrlDecoder().decode(cursor),StandardCharsets.UTF_8).split("\\|",-1);
|
||||
if(p.length!=3 || !id.equals(UUID.fromString(p[0]))) bad();
|
||||
// Добавляем условие keyset-пагинации после последнего сообщения.
|
||||
sql+="and (created_at,id)>(?,?) "; args.add(java.sql.Timestamp.from(OffsetDateTime.parse(p[0]).toInstant())); args.add(UUID.fromString(p[1]));
|
||||
sql+="and (created_at,id)>(?,?) "; args.add(java.sql.Timestamp.from(OffsetDateTime.parse(p[1]).toInstant())); args.add(UUID.fromString(p[2]));
|
||||
} catch(Exception e) { bad(); }
|
||||
}
|
||||
// Сортируем историю и берём одну запись сверх лимита для следующего cursor.
|
||||
@@ -263,8 +313,10 @@ public class MessengerApplication {
|
||||
// Выполняем запрос и превращаем строки базы в объекты Message.
|
||||
List<Message> x=db.query(sql,(rs,n)->new Message(rs.getObject(1,UUID.class),rs.getObject(2,UUID.class),rs.getObject(3,UUID.class),rs.getString(4),rs.getTimestamp(5).toInstant()),args.toArray());
|
||||
// Если запись сверх лимита есть, кодируем её позицию как следующий cursor.
|
||||
String next=x.size()>limit?Base64.getUrlEncoder().encodeToString((x.get(limit-1).created_at()+"|"+x.get(limit-1).id()).getBytes()):null; return new Page<>(x.subList(0,Math.min(limit,x.size())),next);
|
||||
String next=x.size()>limit?Base64.getUrlEncoder().withoutPadding().encodeToString((id+"|"+x.get(limit-1).created_at()+"|"+x.get(limit-1).id()).getBytes(StandardCharsets.UTF_8)):null; return new Page<>(x.subList(0,Math.min(limit,x.size())),next);
|
||||
}
|
||||
// Преобразует limit списка чатов в число и проверяет диапазон.
|
||||
int parseLimit(String value) { try { int limit=value==null?50:Integer.parseInt(value); if(limit<1||limit>100) bad(); return limit; } catch(NumberFormatException e) { bad(); return 0; } }
|
||||
// Формируем ошибку, не раскрывая наличие чужого объекта.
|
||||
ApiException notFound(){return new ApiException(HttpStatus.NOT_FOUND,"not_found","object not found");}
|
||||
// Формируем общую ошибку некорректного запроса.
|
||||
@@ -289,6 +341,10 @@ public class MessengerApplication {
|
||||
// Неправильный JSON считается ошибкой входных данных клиента.
|
||||
// Этот обработчик ловит неправильный или повреждённый JSON.
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class) ResponseEntity<ErrorBody> malformed(HttpServletRequest r){ return ResponseEntity.badRequest().body(new ErrorBody(new Error("invalid_request","invalid request",id(r)))); }
|
||||
// Ошибка преобразования UUID или числового параметра означает неверный запрос.
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class) ResponseEntity<ErrorBody> mismatch(HttpServletRequest r){ return ResponseEntity.badRequest().body(new ErrorBody(new Error("invalid_request","invalid request",id(r)))); }
|
||||
// Ошибка PostgreSQL возвращается как временная недоступность зависимости.
|
||||
@ExceptionHandler(DataAccessException.class) ResponseEntity<ErrorBody> database(DataAccessException e,HttpServletRequest r){ return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(new ErrorBody(new Error("unavailable","database is unavailable",id(r)))); }
|
||||
// Получаем ID запроса, который добавил фильтр.
|
||||
String id(HttpServletRequest r){ return String.valueOf(r.getAttribute("requestId")); }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user