From 98e6789b7ee4037e627b9ca750794c77cf5579ce Mon Sep 17 00:00:00 2001 From: SlimusMinus Date: Tue, 20 Oct 2026 00:58:56 +0300 Subject: [PATCH] Validate image signatures, stream ad media with Range, keep live files in MinIO - Uploaded images are checked by magic bytes; the key extension and stored Content-Type come from the detected format, not from the client's filename (an .html file sent as image/png was stored as .html). - /api/v1/ads-media streams from MinIO instead of loading whole videos into the heap, answers Range requests with 206 (iOS Safari needs it for video) and sets a long public Cache-Control for immutable keys. - The bucket lifecycle rule expired every object after 180 days, including avatars and images of live posts; now only noncurrent versions expire. Co-Authored-By: Claude Opus 5.5 --- .../AdvertisingMediaController.java | 10 +- .../health/StorageStructureService.java | 12 +- .../refound/service/FileStorageService.java | 22 ++-- .../advertising/AdvertisingMediaService.java | 108 +++++++++++++----- .../com/krylov/refound/util/ImageFormat.java | 61 ++++++++++ 5 files changed, 168 insertions(+), 45 deletions(-) create mode 100644 src/main/java/com/krylov/refound/util/ImageFormat.java diff --git a/src/main/java/com/krylov/refound/controller/advertising/AdvertisingMediaController.java b/src/main/java/com/krylov/refound/controller/advertising/AdvertisingMediaController.java index 2743e48..02aa224 100644 --- a/src/main/java/com/krylov/refound/controller/advertising/AdvertisingMediaController.java +++ b/src/main/java/com/krylov/refound/controller/advertising/AdvertisingMediaController.java @@ -3,9 +3,12 @@ package com.krylov.refound.controller.advertising; import com.krylov.refound.service.advertising.AdvertisingMediaService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -23,9 +26,10 @@ public class AdvertisingMediaController { private final AdvertisingMediaService mediaService; @GetMapping("/{*key}") - public ResponseEntity getMedia(@PathVariable String key) { + public ResponseEntity getMedia(@PathVariable String key, + @RequestHeader(value = HttpHeaders.RANGE, required = false) String range) { String mediaKey = key.startsWith("/") ? key.substring(1) : key; - log.info("GET ads-media: key={} -> mediaKey={}", key, mediaKey); - return mediaService.downloadMedia(mediaKey); + log.debug("GET ads-media: key={} -> mediaKey={}, range={}", key, mediaKey, range); + return mediaService.downloadMedia(mediaKey, range); } } \ No newline at end of file diff --git a/src/main/java/com/krylov/refound/health/StorageStructureService.java b/src/main/java/com/krylov/refound/health/StorageStructureService.java index 0d96632..8a08729 100644 --- a/src/main/java/com/krylov/refound/health/StorageStructureService.java +++ b/src/main/java/com/krylov/refound/health/StorageStructureService.java @@ -29,6 +29,9 @@ import java.util.List; @RequiredArgsConstructor public class StorageStructureService { + /** Сколько хранится удалённый (неактуальный) вариант файла — шанс восстановить ошибочно удалённое. */ + private static final int NONCURRENT_VERSION_DAYS = 30; + private final S3Client s3Client; private final MinioProperties properties; @@ -70,12 +73,17 @@ public class StorageStructureService { try { log.info("Установка политики жизненного цикла для бакета '{}'...", mainBucket); + // Текущие версии файлов не истекают: правило "удалять всё старше 180 дней" + // стирало аватары и картинки живых объявлений. Файлы удаляет само приложение + // (удаление поста/аватара, ночная чистка постов); при версионировании от них + // остаются неактуальные версии — их и убирает это правило. Id прежний, чтобы + // конфигурация бакета перезаписалась при старте. LifecycleRule rule = LifecycleRule.builder() .id("delete-after-180-days-rule") .status(ExpirationStatus.ENABLED) .filter(f -> f.prefix("")) - .expiration(exp -> exp.days(180)) - .noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(180)) + .noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(NONCURRENT_VERSION_DAYS)) + .expiration(exp -> exp.expiredObjectDeleteMarker(true)) .build(); BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder() diff --git a/src/main/java/com/krylov/refound/service/FileStorageService.java b/src/main/java/com/krylov/refound/service/FileStorageService.java index ef30666..0d6c013 100644 --- a/src/main/java/com/krylov/refound/service/FileStorageService.java +++ b/src/main/java/com/krylov/refound/service/FileStorageService.java @@ -4,6 +4,7 @@ import com.krylov.refound.config.MinioProperties; import com.krylov.refound.dto.DownloadedFile; import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.exception.ApiException; +import com.krylov.refound.util.ImageFormat; import java.io.IOException; import java.net.URLDecoder; import java.net.URLEncoder; @@ -56,9 +57,9 @@ public class FileStorageService { private static final String ORIGINAL_FILENAME_METADATA_KEY = "original-filename"; /** - * Сколько живёт запись о владельце файла. Совпадает с правилом жизненного цикла бакета - * (180 дней), который ставит StorageStructureService: раньше файл исчезнет из MinIO, - * чем протухнет отметка о нём. + * Сколько живёт запись о владельце файла. Она нужна только для DELETE /api/v1/files + * (удалить свежезагруженную, но не прикреплённую картинку); файлы постов и аватаров + * удаляются сервисами без этой проверки. Позже удалить файл через API может только админ. */ private static final Duration OWNER_TTL = Duration.ofDays(180); private static final String OWNER_KEY_PREFIX = "files:owner:"; @@ -99,8 +100,13 @@ public class FileStorageService { try { byte[] content = file.getBytes(); - String contentType = file.getContentType(); - String extension = extractExtension(originalFilename); + // Тип и расширение берём из содержимого файла, а не из запроса клиента + ImageFormat format = ImageFormat.detect(content).orElseThrow(() -> { + log.warn("Содержимое файла '{}' не похоже на JPEG/PNG/WebP (заявлен {}).", originalFilename, file.getContentType()); + return new ApiException(ErrorCode.VALIDATION_ERROR, "Недопустимый тип файла.", HttpStatus.BAD_REQUEST); + }); + String contentType = format.contentType(); + String extension = format.extension(); Optional optimized = imageOptimizer.optimize(content, contentType); if (optimized.isPresent()) { @@ -399,10 +405,4 @@ public class FileStorageService { } } - private String extractExtension(String originalFilename) { - if (originalFilename != null && originalFilename.contains(".")) { - return originalFilename.substring(originalFilename.lastIndexOf(".")); - } - return ""; - } } \ No newline at end of file diff --git a/src/main/java/com/krylov/refound/service/advertising/AdvertisingMediaService.java b/src/main/java/com/krylov/refound/service/advertising/AdvertisingMediaService.java index 7e4e246..ed31749 100644 --- a/src/main/java/com/krylov/refound/service/advertising/AdvertisingMediaService.java +++ b/src/main/java/com/krylov/refound/service/advertising/AdvertisingMediaService.java @@ -2,15 +2,21 @@ package com.krylov.refound.service.advertising; import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.exception.ApiException; +import com.krylov.refound.util.ImageFormat; import java.io.IOException; import java.io.InputStream; import java.time.Duration; +import java.util.List; import java.util.Set; import java.util.UUID; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.InputStreamResource; +import org.springframework.core.io.Resource; +import org.springframework.http.CacheControl; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpRange; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -41,26 +47,31 @@ public class AdvertisingMediaService { private static final long MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10 MB private static final Set ALLOWED_IMAGE_TYPES = Set.of("image/jpeg", "image/png", "image/webp"); + /** Медиа лежат под UUID-ключами и не меняются — браузер может хранить их долго. */ + private static final CacheControl MEDIA_CACHE_CONTROL = CacheControl.maxAge(Duration.ofDays(30)).cachePublic(); /** * Загружает изображение рекламного объявления в ads-media. - * Валидация полностью повторяет FileStorageService (10MB, jpeg/png/webp) — + * Валидация повторяет FileStorageService (10MB, jpeg/png/webp по сигнатуре файла) — * но целевой бакет другой, поэтому логика не переиспользуется напрямую. */ public String uploadImage(MultipartFile file) { validateImage(file); - String extension = extractExtension(file.getOriginalFilename()); - String mediaKey = "images/%s%s".formatted(UUID.randomUUID(), extension); - try { + byte[] content = file.getBytes(); + // Тип и расширение — по содержимому, а не по имени и Content-Type от клиента + ImageFormat format = ImageFormat.detect(content).orElseThrow(() -> + new ApiException(ErrorCode.VALIDATION_ERROR, "Недопустимый тип файла.", HttpStatus.BAD_REQUEST)); + String mediaKey = "images/%s%s".formatted(UUID.randomUUID(), format.extension()); + PutObjectRequest request = PutObjectRequest.builder() .bucket(adsBucket) .key(mediaKey) - .contentType(file.getContentType()) + .contentType(format.contentType()) .build(); - s3Client.putObject(request, RequestBody.fromInputStream(file.getInputStream(), file.getSize())); + s3Client.putObject(request, RequestBody.fromBytes(content)); log.info("Ad image uploaded: {}", mediaKey); return mediaKey; @@ -93,13 +104,6 @@ public class AdvertisingMediaService { } } - private String extractExtension(String originalFilename) { - if (originalFilename != null && originalFilename.contains(".")) { - return originalFilename.substring(originalFilename.lastIndexOf(".")); - } - return ""; - } - /** * URL, по которому фронтенд сможет получить медиа на любом устройстве. * Presigned URL непригоден: он подписан под host MinIO (localhost:9010), @@ -112,35 +116,81 @@ public class AdvertisingMediaService { } /** - * Отдаёт медиа рекламы из ads-media потоком/байтами через бэкенд — - * без presigned URL, доступно с любого устройства. + * Отдаёт медиа рекламы из ads-media потоком через бэкенд — без presigned URL, + * доступно с любого устройства. + * + *

Файл не читается в память целиком (ролик в десятки мегабайт на каждый + * запрос быстро съедал heap) и поддерживается заголовок Range: без ответа 206 + * Safari на iOS не воспроизводит видео, а перемотка в остальных браузерах + * перекачивает файл с начала. Ключи медиа неизменяемы (UUID), поэтому ответ + * можно кэшировать. */ - public ResponseEntity downloadMedia(String mediaKey) { + public ResponseEntity downloadMedia(String mediaKey, String rangeHeader) { try { HeadObjectResponse head = s3Client.headObject( HeadObjectRequest.builder().bucket(adsBucket).key(mediaKey).build()); - String contentType = head.contentType() != null - ? head.contentType() - : MediaType.APPLICATION_OCTET_STREAM_VALUE; - - byte[] content = s3Client.getObjectAsBytes( - GetObjectRequest.builder().bucket(adsBucket).key(mediaKey).build()).asByteArray(); - + long length = head.contentLength(); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline"); + headers.add(HttpHeaders.ACCEPT_RANGES, "bytes"); + headers.setCacheControl(MEDIA_CACHE_CONTROL); + headers.setContentType(head.contentType() != null + ? MediaType.parseMediaType(head.contentType()) + : MediaType.APPLICATION_OCTET_STREAM); - log.info("downloadMedia: served mediaKey={}, contentType={}, {} bytes", mediaKey, contentType, content.length); - return ResponseEntity.ok() - .headers(headers) - .contentType(MediaType.parseMediaType(contentType)) - .body(content); + GetObjectRequest.Builder get = GetObjectRequest.builder().bucket(adsBucket).key(mediaKey); + HttpStatus status = HttpStatus.OK; + long bodyLength = length; + + if (rangeHeader != null && !rangeHeader.isBlank()) { + long[] range = resolveRange(rangeHeader, length); + if (range == null) { + headers.set(HttpHeaders.CONTENT_RANGE, "bytes */" + length); + return ResponseEntity.status(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE).headers(headers).build(); + } + get.range("bytes=" + range[0] + "-" + range[1]); + headers.set(HttpHeaders.CONTENT_RANGE, "bytes " + range[0] + "-" + range[1] + "/" + length); + status = HttpStatus.PARTIAL_CONTENT; + bodyLength = range[1] - range[0] + 1; + } + + headers.setContentLength(bodyLength); + InputStream body = s3Client.getObject(get.build()); + log.debug("downloadMedia: mediaKey={}, status={}, {} bytes", mediaKey, status.value(), bodyLength); + return ResponseEntity.status(status).headers(headers).body(new InputStreamResource(body)); } catch (NoSuchKeyException e) { log.warn("Ad media not found: {}", mediaKey); throw new ApiException(ErrorCode.NOT_FOUND, "Медиа не найдено.", HttpStatus.NOT_FOUND); - } catch (S3Exception | SdkClientException e) { + } catch (S3Exception e) { + if (e.statusCode() == HttpStatus.NOT_FOUND.value()) { + // HEAD отсутствующего ключа приходит как S3Exception 404, а не NoSuchKeyException + log.warn("Ad media not found: {}", mediaKey); + throw new ApiException(ErrorCode.NOT_FOUND, "Медиа не найдено.", HttpStatus.NOT_FOUND); + } log.error("Failed to download ad media mediaKey={}", mediaKey, e); throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при скачивании медиа.", HttpStatus.INTERNAL_SERVER_ERROR); + } catch (SdkClientException e) { + log.error("Failed to download ad media mediaKey={}", mediaKey, e); + throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при скачивании медиа.", HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * Первый диапазон из заголовка Range как [start, end] включительно или null, + * если диапазон некорректен или вне файла. Несколько диапазонов сразу + * (multipart/byteranges) плееры не запрашивают. + */ + static long[] resolveRange(String rangeHeader, long length) { + try { + List ranges = HttpRange.parseRanges(rangeHeader); + if (ranges.isEmpty() || length <= 0) { + return null; + } + HttpRange range = ranges.get(0); + return new long[] {range.getRangeStart(length), range.getRangeEnd(length)}; + } catch (IllegalArgumentException e) { + return null; } } diff --git a/src/main/java/com/krylov/refound/util/ImageFormat.java b/src/main/java/com/krylov/refound/util/ImageFormat.java new file mode 100644 index 0000000..dc52508 --- /dev/null +++ b/src/main/java/com/krylov/refound/util/ImageFormat.java @@ -0,0 +1,61 @@ +package com.krylov.refound.util; + +import java.util.Optional; + +/** + * Форматы картинок, которые принимает сервис. Формат определяется по первым + * байтам файла (сигнатуре), а не по Content-Type и имени файла от клиента: + * иначе под видом image/png можно загрузить HTML или SVG с расширением .html, + * и он отдавался бы из хранилища с этим ключом. + */ +public enum ImageFormat { + JPEG("image/jpeg", ".jpg"), + PNG("image/png", ".png"), + WEBP("image/webp", ".webp"); + + private final String contentType; + private final String extension; + + ImageFormat(String contentType, String extension) { + this.contentType = contentType; + this.extension = extension; + } + + public String contentType() { + return contentType; + } + + /** Расширение для ключа объекта в хранилище (с точкой). */ + public String extension() { + return extension; + } + + /** Формат по сигнатуре файла или пусто, если это не JPEG/PNG/WebP. */ + public static Optional detect(byte[] content) { + if (content == null) { + return Optional.empty(); + } + if (startsWith(content, 0, 0xFF, 0xD8, 0xFF)) { + return Optional.of(JPEG); + } + if (startsWith(content, 0, 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A)) { + return Optional.of(PNG); + } + if (startsWith(content, 0, 'R', 'I', 'F', 'F') && startsWith(content, 8, 'W', 'E', 'B', 'P')) { + return Optional.of(WEBP); + } + return Optional.empty(); + } + + private static boolean startsWith(byte[] content, int offset, int... signature) { + if (content.length < offset + signature.length) { + return false; + } + for (int i = 0; i < signature.length; i++) { + if ((content[offset + i] & 0xFF) != signature[i]) { + return false; + } + } + return true; + } +}