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

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