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 <uuid>.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 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-20 00:58:56 +03:00
parent 5cd60b6318
commit 98e6789b7e
5 changed files with 168 additions and 45 deletions

View File

@@ -3,9 +3,12 @@ package com.krylov.refound.controller.advertising;
import com.krylov.refound.service.advertising.AdvertisingMediaService; import com.krylov.refound.service.advertising.AdvertisingMediaService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; 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.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -23,9 +26,10 @@ public class AdvertisingMediaController {
private final AdvertisingMediaService mediaService; private final AdvertisingMediaService mediaService;
@GetMapping("/{*key}") @GetMapping("/{*key}")
public ResponseEntity<byte[]> getMedia(@PathVariable String key) { public ResponseEntity<Resource> getMedia(@PathVariable String key,
@RequestHeader(value = HttpHeaders.RANGE, required = false) String range) {
String mediaKey = key.startsWith("/") ? key.substring(1) : key; String mediaKey = key.startsWith("/") ? key.substring(1) : key;
log.info("GET ads-media: key={} -> mediaKey={}", key, mediaKey); log.debug("GET ads-media: key={} -> mediaKey={}, range={}", key, mediaKey, range);
return mediaService.downloadMedia(mediaKey); return mediaService.downloadMedia(mediaKey, range);
} }
} }

View File

@@ -29,6 +29,9 @@ import java.util.List;
@RequiredArgsConstructor @RequiredArgsConstructor
public class StorageStructureService { public class StorageStructureService {
/** Сколько хранится удалённый (неактуальный) вариант файла — шанс восстановить ошибочно удалённое. */
private static final int NONCURRENT_VERSION_DAYS = 30;
private final S3Client s3Client; private final S3Client s3Client;
private final MinioProperties properties; private final MinioProperties properties;
@@ -70,12 +73,17 @@ public class StorageStructureService {
try { try {
log.info("Установка политики жизненного цикла для бакета '{}'...", mainBucket); log.info("Установка политики жизненного цикла для бакета '{}'...", mainBucket);
// Текущие версии файлов не истекают: правило "удалять всё старше 180 дней"
// стирало аватары и картинки живых объявлений. Файлы удаляет само приложение
// (удаление поста/аватара, ночная чистка постов); при версионировании от них
// остаются неактуальные версии — их и убирает это правило. Id прежний, чтобы
// конфигурация бакета перезаписалась при старте.
LifecycleRule rule = LifecycleRule.builder() LifecycleRule rule = LifecycleRule.builder()
.id("delete-after-180-days-rule") .id("delete-after-180-days-rule")
.status(ExpirationStatus.ENABLED) .status(ExpirationStatus.ENABLED)
.filter(f -> f.prefix("")) .filter(f -> f.prefix(""))
.expiration(exp -> exp.days(180)) .noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(NONCURRENT_VERSION_DAYS))
.noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(180)) .expiration(exp -> exp.expiredObjectDeleteMarker(true))
.build(); .build();
BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder() BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder()

View File

@@ -4,6 +4,7 @@ import com.krylov.refound.config.MinioProperties;
import com.krylov.refound.dto.DownloadedFile; import com.krylov.refound.dto.DownloadedFile;
import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException; import com.krylov.refound.exception.ApiException;
import com.krylov.refound.util.ImageFormat;
import java.io.IOException; import java.io.IOException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
@@ -56,9 +57,9 @@ public class FileStorageService {
private static final String ORIGINAL_FILENAME_METADATA_KEY = "original-filename"; private static final String ORIGINAL_FILENAME_METADATA_KEY = "original-filename";
/** /**
* Сколько живёт запись о владельце файла. Совпадает с правилом жизненного цикла бакета * Сколько живёт запись о владельце файла. Она нужна только для DELETE /api/v1/files
* (180 дней), который ставит StorageStructureService: раньше файл исчезнет из MinIO, * (удалить свежезагруженную, но не прикреплённую картинку); файлы постов и аватаров
* чем протухнет отметка о нём. * удаляются сервисами без этой проверки. Позже удалить файл через API может только админ.
*/ */
private static final Duration OWNER_TTL = Duration.ofDays(180); private static final Duration OWNER_TTL = Duration.ofDays(180);
private static final String OWNER_KEY_PREFIX = "files:owner:"; private static final String OWNER_KEY_PREFIX = "files:owner:";
@@ -99,8 +100,13 @@ public class FileStorageService {
try { try {
byte[] content = file.getBytes(); 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<ImageOptimizer.OptimizedImage> optimized = imageOptimizer.optimize(content, contentType); Optional<ImageOptimizer.OptimizedImage> optimized = imageOptimizer.optimize(content, contentType);
if (optimized.isPresent()) { 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 "";
}
} }

View File

@@ -2,15 +2,21 @@ package com.krylov.refound.service.advertising;
import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException; import com.krylov.refound.exception.ApiException;
import com.krylov.refound.util.ImageFormat;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.time.Duration; import java.time.Duration;
import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value; 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.HttpHeaders;
import org.springframework.http.HttpRange;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; 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 long MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10 MB
private static final Set<String> ALLOWED_IMAGE_TYPES = Set.of("image/jpeg", "image/png", "image/webp"); private static final Set<String> 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. * Загружает изображение рекламного объявления в ads-media.
* Валидация полностью повторяет FileStorageService (10MB, jpeg/png/webp) — * Валидация повторяет FileStorageService (10MB, jpeg/png/webp по сигнатуре файла) —
* но целевой бакет другой, поэтому логика не переиспользуется напрямую. * но целевой бакет другой, поэтому логика не переиспользуется напрямую.
*/ */
public String uploadImage(MultipartFile file) { public String uploadImage(MultipartFile file) {
validateImage(file); validateImage(file);
String extension = extractExtension(file.getOriginalFilename());
String mediaKey = "images/%s%s".formatted(UUID.randomUUID(), extension);
try { 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() PutObjectRequest request = PutObjectRequest.builder()
.bucket(adsBucket) .bucket(adsBucket)
.key(mediaKey) .key(mediaKey)
.contentType(file.getContentType()) .contentType(format.contentType())
.build(); .build();
s3Client.putObject(request, RequestBody.fromInputStream(file.getInputStream(), file.getSize())); s3Client.putObject(request, RequestBody.fromBytes(content));
log.info("Ad image uploaded: {}", mediaKey); log.info("Ad image uploaded: {}", mediaKey);
return 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, по которому фронтенд сможет получить медиа на любом устройстве. * URL, по которому фронтенд сможет получить медиа на любом устройстве.
* Presigned URL непригоден: он подписан под host MinIO (localhost:9010), * Presigned URL непригоден: он подписан под host MinIO (localhost:9010),
@@ -112,35 +116,81 @@ public class AdvertisingMediaService {
} }
/** /**
* Отдаёт медиа рекламы из ads-media потоком/байтами через бэкенд — * Отдаёт медиа рекламы из ads-media потоком через бэкенд — без presigned URL,
* без presigned URL, доступно с любого устройства. * доступно с любого устройства.
*
* <p>Файл не читается в память целиком (ролик в десятки мегабайт на каждый
* запрос быстро съедал heap) и поддерживается заголовок Range: без ответа 206
* Safari на iOS не воспроизводит видео, а перемотка в остальных браузерах
* перекачивает файл с начала. Ключи медиа неизменяемы (UUID), поэтому ответ
* можно кэшировать.
*/ */
public ResponseEntity<byte[]> downloadMedia(String mediaKey) { public ResponseEntity<Resource> downloadMedia(String mediaKey, String rangeHeader) {
try { try {
HeadObjectResponse head = s3Client.headObject( HeadObjectResponse head = s3Client.headObject(
HeadObjectRequest.builder().bucket(adsBucket).key(mediaKey).build()); HeadObjectRequest.builder().bucket(adsBucket).key(mediaKey).build());
String contentType = head.contentType() != null long length = head.contentLength();
? head.contentType()
: MediaType.APPLICATION_OCTET_STREAM_VALUE;
byte[] content = s3Client.getObjectAsBytes(
GetObjectRequest.builder().bucket(adsBucket).key(mediaKey).build()).asByteArray();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline"); 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); GetObjectRequest.Builder get = GetObjectRequest.builder().bucket(adsBucket).key(mediaKey);
return ResponseEntity.ok() HttpStatus status = HttpStatus.OK;
.headers(headers) long bodyLength = length;
.contentType(MediaType.parseMediaType(contentType))
.body(content); 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) { } catch (NoSuchKeyException e) {
log.warn("Ad media not found: {}", mediaKey); log.warn("Ad media not found: {}", mediaKey);
throw new ApiException(ErrorCode.NOT_FOUND, "Медиа не найдено.", HttpStatus.NOT_FOUND); 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); log.error("Failed to download ad media mediaKey={}", mediaKey, e);
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при скачивании медиа.", HttpStatus.INTERNAL_SERVER_ERROR); 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<HttpRange> 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;
} }
} }

View File

@@ -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<ImageFormat> 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;
}
}