Implement lab 7 security and mTLS

This commit is contained in:
2026-11-26 16:55:53 +03:00
parent 20afc2c790
commit ab7b467957
54 changed files with 3240 additions and 25 deletions
+57
View File
@@ -0,0 +1,57 @@
"""Worker-side variant generation: thumbnail (grade 3), crop + optimized (grade 4)."""
import io
from PIL import Image, ImageOps
def _normalize(img: Image.Image) -> Image.Image:
"""Apply EXIF orientation, then flatten any alpha onto white."""
img = ImageOps.exif_transpose(img)
if img.mode in ("RGBA", "LA", "P"):
rgba = img.convert("RGBA")
background = Image.new("RGB", rgba.size, (255, 255, 255))
background.paste(rgba, mask=rgba.split()[-1])
return background
return img.convert("RGB")
def thumbnail(data: bytes) -> tuple[bytes, int, int]:
"""JPEG, contained within 256x256, never upscaled, rounded down, min 1px."""
with Image.open(io.BytesIO(data)) as raw:
img = _normalize(raw)
scale = min(256 / img.width, 256 / img.height, 1.0)
width = max(1, int(img.width * scale))
height = max(1, int(img.height * scale))
resized = img.resize((width, height), Image.LANCZOS)
buf = io.BytesIO()
resized.save(buf, "JPEG", quality=85)
return buf.getvalue(), width, height
def crop(data: bytes) -> tuple[bytes, int, int]:
"""JPEG, centered 128x128 square; small sources may be upscaled."""
with Image.open(io.BytesIO(data)) as raw:
img = _normalize(raw)
scale = 128 / min(img.width, img.height)
width = max(128, round(img.width * scale))
height = max(128, round(img.height * scale))
resized = img.resize((width, height), Image.LANCZOS)
left = (width - 128) // 2
top = (height - 128) // 2
cropped = resized.crop((left, top, left + 128, top + 128))
buf = io.BytesIO()
cropped.save(buf, "JPEG", quality=85)
return buf.getvalue(), 128, 128
def optimized(data: bytes) -> tuple[bytes, int, int]:
"""WebP, contained within 1280x1280, never upscaled, EXIF stripped."""
with Image.open(io.BytesIO(data)) as raw:
img = _normalize(raw)
scale = min(1280 / img.width, 1280 / img.height, 1.0)
width = max(1, int(img.width * scale))
height = max(1, int(img.height * scale))
resized = img.resize((width, height), Image.LANCZOS)
buf = io.BytesIO()
resized.save(buf, "WEBP", quality=80) # save() never copies source EXIF for WEBP
return buf.getvalue(), width, height