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:
@@ -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<ImageOptimizer.OptimizedImage> 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 "";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user