package ru.mtusi.messenger; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.HexFormat; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import ru.mtusi.messenger.MessengerApplication.ApiException; // Вложения: метаданные в PostgreSQL, байты в приватном S3. Доступ только через API участникам чата. // Приём (lab5): оригинал → staging в S3, затем вложение + job + outbox одной транзакцией → 202 queued; // варианты создаёт worker асинхронно. @RestController class Attachments { static final long MAX_BYTES = 10L * 1024 * 1024; static final Set VARIANTS = Set.of("thumbnail", "crop", "optimized"); static final Logger log = LoggerFactory.getLogger(Attachments.class); record Attachment(UUID id, UUID chat_id, UUID owner_id, String filename, String content_type, long size_bytes, String sha256, String status, List variants, String error_code, Instant created_at, Instant updated_at) {} record Variant(String name, String content_type, long size_bytes, int width, int height, String sha256) {} final MessengerApplication.Api api; final JdbcTemplate db; final Storage storage; final Jobs jobs; // Не больше N загрузок на реплику одновременно: диск под временные файлы и CPU проверки ограничены. final Semaphore uploads = new Semaphore(Integer.parseInt(System.getenv().getOrDefault("MAX_CONCURRENT_UPLOADS", "8"))); Attachments(MessengerApplication.Api api, JdbcTemplate db, Storage storage, Jobs jobs) { this.api = api; this.db = db; this.storage = storage; this.jobs = jobs; } @PostMapping("/api/v1/chats/{id}/attachments") ResponseEntity upload(@PathVariable UUID id, @RequestParam(required = false) String filename, HttpServletRequest r) throws IOException, InterruptedException { // Порядок как у остальных endpoint: сессия → доступ к чату → входные данные. UUID user = api.auth(r); if (!api.member(id, user)) throw api.notFound(); if (!validFilename(filename)) api.bad(); String declared = declaredType(r.getContentType()); if (declared == null) throw unsupported(); // Заявленный размер проверяем до чтения тела. if (r.getContentLengthLong() > MAX_BYTES) throw tooLarge(); if (!uploads.tryAcquire(10, TimeUnit.SECONDS)) throw unavailable("too many concurrent uploads, retry later"); Path tmp = Files.createTempFile("upload-", ".bin"); try { // 1. Тело — во временный файл с жёстким лимитом, SHA-256 считается по ходу. Файл живёт // только до конца запроса: это буфер проверки, а не хранилище оригинала. MessageDigest sha = sha256(); long size = 0; try (InputStream in = r.getInputStream(); OutputStream out = Files.newOutputStream(tmp)) { byte[] buf = new byte[65536]; while (true) { int n; try { n = in.read(buf); } catch (IOException e) { throw new ApiException(HttpStatus.BAD_REQUEST, "invalid_request", "upload interrupted"); } if (n < 0) break; size += n; if (size > MAX_BYTES) throw tooLarge(); sha.update(buf, 0, n); out.write(buf, 0, n); } } if (size == 0) api.bad(); // 2. Формат по содержимому, лимит пикселей по заголовку — до распаковки. ImageCheck.Info image; try { image = ImageCheck.inspect(tmp); } catch (ImageCheck.Invalid e) { throw e.tooLarge ? tooLarge() : unsupported(); } if (!image.contentType().equals(declared)) throw unsupported(); // 3. Полный проверенный оригинал — в устойчивый staging (приватный S3-префикс), до записи в БД. UUID attachmentId = UUID.randomUUID(); String staging = Storage.STAGING + attachmentId; String hash = HexFormat.of().formatHex(sha.digest()); try { storage.put(staging, tmp, declared); } catch (SdkException e) { log.warn("S3 staging put failed for attachment {}: {}", attachmentId, e.toString()); throw unavailable("object storage is unavailable"); } // 4. Метаданные, задание и outbox — одна транзакция; 202 только после её COMMIT. // Не записалось — убираем staging (иначе его удалит очистка staging по retention). Instant created = now(); try { jobs.accept(attachmentId, id, user, filename, declared, size, hash, image.width(), image.height(), created); } catch (RuntimeException e) { try { storage.delete(staging); } catch (SdkException ignored) {} throw e; } return ResponseEntity.status(202).body(new Attachment(attachmentId, id, user, filename, declared, size, hash, "queued", List.of(), null, created, created)); } finally { Files.deleteIfExists(tmp); uploads.release(); } } @GetMapping("/api/v1/attachments/{id}") Attachment metadata(@PathVariable UUID id, HttpServletRequest r) { return visible(id, api.auth(r)).attachment(); } // Байты отдаются потоком из S3 через авторизованный API, без redirect на bucket. @GetMapping("/api/v1/attachments/{id}/content") void content(@PathVariable UUID id, @RequestParam(required = false) String variant, HttpServletRequest r, HttpServletResponse s) throws IOException { Visible v = visible(id, api.auth(r)); String name = variant == null ? "original" : variant; if (!name.equals("original") && !VARIANTS.contains(name)) api.bad(); // queued/processing/failed — 409: оригинал ещё не опубликован, варианты не готовы. if (!v.attachment().status().equals("ready")) throw new ApiException(HttpStatus.CONFLICT, "conflict", "attachment is not ready"); Attachment a = v.attachment(); String key = v.key(), type = a.content_type(); long size = a.size_bytes(); if (!name.equals("original")) { Object[] x = db.query("select object_key,content_type,size_bytes from attachment_variants where attachment_id=? and pipeline_version=? and name=?", rs -> rs.next() ? new Object[]{rs.getString(1), rs.getString(2), rs.getLong(3)} : null, id, v.version(), name); if (x == null) throw api.notFound(); key = (String) x[0]; type = (String) x[1]; size = (long) x[2]; } ResponseInputStream in; try { in = storage.get(key); } catch (NoSuchKeyException e) { // Метаданные есть, объекта нет: рассинхронизация, её покажет и исправит сверка. log.error("object {} is missing for ready attachment {}", key, id); throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "internal_error", "internal server error"); } catch (SdkException e) { throw unavailable("object storage is unavailable"); } try (in) { s.setContentType(type); s.setContentLengthLong(size); s.setHeader("Cache-Control", "private, no-store"); s.setHeader("X-Content-Type-Options", "nosniff"); in.transferTo(s.getOutputStream()); } } record Visible(Attachment attachment, String key, Integer version) {} // Вложения чатов, где пользователь участник; uploading/lost и чужие — 404 без раскрытия существования. // Варианты — только текущей (последней зафиксированной) версии pipeline. Visible visible(UUID id, UUID user) { Visible v = db.query("select id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key,state,error_code,pipeline_version from attachments a" + " where id=? and state in ('queued','processing','ready','failed') and exists(select 1 from chat_members m where m.chat_id=a.chat_id and m.user_id=?)", rs -> { if (!rs.next()) return null; String state = rs.getString(11); Integer version = rs.getObject(13, Integer.class); List variants = state.equals("ready") && version != null ? db.query("select name,content_type,size_bytes,width,height,sha256 from attachment_variants" + " where attachment_id=? and pipeline_version=? order by array_position(array['thumbnail','crop','optimized']::text[],name::text)", (x, n) -> new Variant(x.getString(1), x.getString(2), x.getLong(3), x.getInt(4), x.getInt(5), x.getString(6)), id, version) : List.of(); return new Visible(new Attachment(rs.getObject(1, UUID.class), rs.getObject(2, UUID.class), rs.getObject(3, UUID.class), rs.getString(4), rs.getString(5), rs.getLong(6), rs.getString(7), state, variants, state.equals("failed") ? rs.getString(12) : null, rs.getTimestamp(8).toInstant(), rs.getTimestamp(9).toInstant()), rs.getString(10), version); }, id, user); if (v == null) throw api.notFound(); return v; } // filename только для отображения: 1–255 code points, без путей, NUL и управляющих символов. static boolean validFilename(String name) { if (name == null || name.isBlank() || name.equals(".") || name.equals("..")) return false; if (name.codePointCount(0, name.length()) > 255) return false; return name.codePoints().noneMatch(c -> c == '/' || c == '\\' || Character.getType(c) == Character.CONTROL || c == 0x2028 || c == 0x2029 || Character.getType(c) == Character.SURROGATE); } static String declaredType(String header) { try { MediaType t = MediaType.parseMediaType(header); String base = t.getType() + "/" + t.getSubtype(); return base.equals("image/png") || base.equals("image/jpeg") ? base : null; } catch (RuntimeException e) { return null; } } static Instant now() { return Instant.now().truncatedTo(ChronoUnit.MICROS); } static MessageDigest sha256() { try { return MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } static ApiException tooLarge() { return new ApiException(HttpStatus.PAYLOAD_TOO_LARGE, "payload_too_large", "attachment exceeds 10 MiB or 40 megapixels"); } static ApiException unsupported() { return new ApiException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "unsupported_media_type", "only valid PNG or JPEG content is accepted"); } static ApiException unavailable(String message) { return new ApiException(HttpStatus.SERVICE_UNAVAILABLE, "unavailable", message); } }