all for 4

This commit is contained in:
2026-11-11 23:05:16 +03:00
parent 1ec85a2402
commit a2e143caea
26 changed files with 5103 additions and 281 deletions
+176
View File
@@ -0,0 +1,176 @@
import json
import os
from pathlib import Path
import resource
import sys
import time
import warnings
from PIL import Image, ImageFile, ImageOps, UnidentifiedImageError
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
def fit_size(width, height, bound):
denominator = max(bound, width, height)
return (
max(1, width * bound // denominator),
max(1, height * bound // denominator),
)
def white_rgb(image):
rgba = image.convert("RGBA")
output = Image.new("RGB", rgba.size, "white")
output.paste(
rgba,
mask=rgba.getchannel("A"),
)
rgba.close()
return output
def main():
# Ограничения дочернего процесса Linux.
resource.setrlimit(
resource.RLIMIT_AS,
(768 * 1024**2,) * 2,
)
resource.setrlimit(
resource.RLIMIT_CPU,
(20, 21),
)
resource.setrlimit(
resource.RLIMIT_FSIZE,
(11 * 1024**2,) * 2,
)
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
ImageFile.LOAD_TRUNCATED_IMAGES = False
warnings.simplefilter(
"error",
Image.DecompressionBombWarning,
)
source, output = map(Path, sys.argv[1:3])
if not 0 < source.stat().st_size <= MAX_BYTES:
return 10
if os.environ.get("IMAGE_TEST_SLEEP") == "1":
time.sleep(60)
try:
image = Image.open(source)
if (
image.format not in ("PNG", "JPEG")
or image.width * image.height > MAX_PIXELS
):
image.close()
return 10
image.load()
ImageOps.exif_transpose(image, in_place=True)
except (
ValueError,
UnidentifiedImageError,
OSError,
SyntaxError,
Image.DecompressionBombWarning,
Image.DecompressionBombError,
):
return 10
with image:
manifest = []
variants = [
("thumbnail", 256, "image/jpeg", "jpg"),
("crop", 128, "image/jpeg", "jpg"),
("optimized", 1280, "image/webp", "webp"),
]
for name, bound, mime, extension in variants:
if name == "crop":
scaled = ImageOps.fit(
image,
(128, 128),
method=Image.Resampling.LANCZOS,
centering=(0.5, 0.5),
)
else:
scaled = image.resize(
fit_size(*image.size, bound),
Image.Resampling.LANCZOS,
)
if extension == "jpg":
rendered = white_rgb(scaled)
else:
rendered = scaled.convert("RGBA")
scaled.close()
rendered.info.clear()
path = output / (name + "." + extension)
if extension == "jpg":
rendered.save(
path,
"JPEG",
quality=85,
subsampling=2,
optimize=True,
exif=b"",
icc_profile=None,
)
else:
rendered.save(
path,
"WEBP",
quality=80,
method=4,
lossless=False,
exif=b"",
icc_profile=b"",
xmp=b"",
)
manifest.append(
{
"name": name,
"content_type": mime,
"width": rendered.width,
"height": rendered.height,
}
)
rendered.close()
if not 0 < path.stat().st_size <= MAX_BYTES:
return 11
(output / "manifest.json").write_text(
json.dumps(manifest),
encoding="utf-8",
)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except (MemoryError, OSError):
sys.exit(11)
+184
View File
@@ -0,0 +1,184 @@
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import zlib
from PIL import Image
SCRIPT = Path(__file__).with_name("process_image.py")
def execute(folder, expected):
result = subprocess.run(
[
sys.executable,
str(SCRIPT),
str(folder / "input.bin"),
str(folder),
],
capture_output=True,
timeout=30,
)
assert result.returncode == expected, (
folder.name,
result.returncode,
)
def main():
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
cases = [
(
"alpha",
(320, 200),
"RGBA",
(255, 0, 0, 0),
None,
[(256, 160), (128, 128), (320, 200)],
),
(
"small",
(20, 10),
"RGB",
"red",
None,
[(20, 10), (128, 128), (20, 10)],
),
(
"orientation",
(320, 200),
"RGB",
"blue",
6,
[(160, 256), (128, 128), (200, 320)],
),
]
for label, size, mode, color, orientation, expected in cases:
folder = root / label
folder.mkdir()
with Image.new(mode, size, color) as image:
if orientation:
exif = Image.Exif()
exif[274] = orientation
image.save(
folder / "input.bin",
"JPEG",
exif=exif,
)
else:
image.save(folder / "input.bin", "PNG")
execute(folder, 0)
names = [
"thumbnail.jpg",
"crop.jpg",
"optimized.webp",
]
for name, dimensions in zip(names, expected):
with Image.open(folder / name) as result:
assert result.size == dimensions
assert not result.getexif()
assert not any(
result.info.get(key)
for key in ["icc_profile", "xmp", "exif"]
)
if label == "alpha" and name.endswith(".jpg"):
assert result.getpixel((0, 0)) == (
255,
255,
255,
)
print("PASS:", label)
folder = root / "center_crop"
folder.mkdir()
with Image.new("RGB", (400, 200), "blue") as image:
image.paste("red", (0, 0, 100, 200))
image.paste("green", (300, 0, 400, 200))
image.save(folder / "input.bin", "PNG")
execute(folder, 0)
with Image.open(folder / "crop.jpg") as crop:
for x in [32, 96]:
red, green, blue = crop.getpixel((x, 64))
assert blue > 240
assert red < 15
assert green < 15
print("PASS: centered crop")
for label, data in [
("broken", b"not an image"),
("bytes_limit", b"x" * (10485760 + 1)),
]:
folder = root / label
folder.mkdir()
(folder / "input.bin").write_bytes(data)
execute(folder, 10)
print("PASS rejected:", label)
folder = root / "pixels"
folder.mkdir()
def chunk(kind, data):
return (
struct.pack(">I", len(data))
+ kind
+ data
+ struct.pack(
">I",
zlib.crc32(kind + data) & 0xffffffff,
)
)
png = (
b"\x89PNG\r\n\x1a\n"
+ chunk(
b"IHDR",
struct.pack(
">IIBBBBB",
10000,
10000,
8,
2,
0,
0,
0,
),
)
+ chunk(
b"IDAT",
zlib.compress(b"\0\0\0\0"),
)
+ chunk(b"IEND", b"")
)
(folder / "input.bin").write_bytes(png)
execute(folder, 10)
print("PASS rejected: pixels before decode")
if __name__ == "__main__":
main()
+5 -4
View File
@@ -28,7 +28,6 @@ mc alias set storage http://minio:9000 \
"$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null
mc mb --ignore-existing "storage/$S3_BUCKET"
mc anonymous set none "storage/$S3_BUCKET"
cat > /tmp/attachments-policy.json <<EOF
@@ -47,7 +46,7 @@ cat > /tmp/attachments-policy.json <<EOF
]
},
{
"Sid": "ManageOriginalAttachments",
"Sid": "ManageAttachmentObjects",
"Effect": "Allow",
"Action": [
"s3:GetObject",
@@ -57,7 +56,9 @@ cat > /tmp/attachments-policy.json <<EOF
"s3:ListMultipartUploadParts"
],
"Resource": [
"arn:aws:s3:::$S3_BUCKET/originals/*"
"arn:aws:s3:::$S3_BUCKET/originals/*",
"arn:aws:s3:::$S3_BUCKET/staging/*",
"arn:aws:s3:::$S3_BUCKET/variants/*"
]
}
]
@@ -90,4 +91,4 @@ mc alias set app http://minio:9000 \
mc stat "app/$S3_BUCKET" >/dev/null
echo "Bootstrap completed: private bucket and API user are ready"
echo "Bootstrap completed: private bucket and application user are ready"