Port final lab 5 validation, session and PNG recovery fixes

This commit is contained in:
Artyom
2026-11-07 02:35:40 +03:00
parent 97feb04b3f
commit bc1d7aa771
41 changed files with 4363 additions and 53 deletions
@@ -5,10 +5,12 @@ import warnings
from collections.abc import Callable
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures.process import BrokenProcessPool
from contextlib import closing
from dataclasses import dataclass
from io import BytesIO
from PIL import Image, ImageOps
from PIL import Image, ImageChops, ImageOps
from PIL.PngImagePlugin import PngImageFile
from messenger.attachments.application.ports import Rendition
from messenger.attachments.domain.errors import (
@@ -27,6 +29,7 @@ from messenger.attachments.domain.variants import (
THUMBNAIL_BOX,
fit,
)
from messenger.attachments.infrastructure.png import SIGNATURE, read_png_header, verify_png_pixels
from messenger.shared.application.errors import Unavailable
KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG}
@@ -38,6 +41,8 @@ JPEG = {1: {"quality": 85, "optimize": True}, 2: {"quality": 90, "optimize": Tru
WEBP = {1: {"quality": 80, "method": 4}, 2: {"quality": 85, "method": 4}}
ENCODINGS = {"JPEG": (ImageKind.JPEG.value, "jpg"), "WEBP": ("image/webp", "webp")}
REDUCING_GAP = 3.0
PNG_WIDE_DEPTH = 16
COLOR_TILE_SIDE = 256
@dataclass(frozen=True, slots=True)
@@ -60,6 +65,7 @@ class PillowImageInspector:
def _inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
try:
header = read_png_header(data) if data.startswith(SIGNATURE) else None
image = Image.open(BytesIO(data), formats=tuple(KINDS))
except BOMBS as error:
raise PayloadTooLarge("изображение больше допустимого числа пикселей") from error
@@ -67,28 +73,87 @@ class PillowImageInspector:
raise UnsupportedImage("содержимое не является изображением PNG или JPEG") from error
with image:
kind = KINDS[str(image.format)]
width, height = image.size
width, height = image.size if header is None else header[:2]
if kind is not declared:
raise UnsupportedImage("содержимое не совпадает с заявленным Content-Type")
if width * height > self._max_pixels:
raise PayloadTooLarge("изображение больше допустимого числа пикселей")
try:
if kind is ImageKind.JPEG:
if header is None:
image.draft("RGB", (width // JPEG_SCALE or 1, height // JPEG_SCALE or 1))
image.load()
else:
image.verify()
verify_png_pixels(data, header)
except Exception as error:
raise UnsupportedImage("изображение повреждено или обрезано") from error
return ImageInfo(kind, width, height)
def map_tiles(
image: Image.Image, mode: str, transform: Callable[[Image.Image], Image.Image]
) -> Image.Image:
result = Image.new(mode, image.size)
for y in range(0, image.height, COLOR_TILE_SIDE):
for x in range(0, image.width, COLOR_TILE_SIDE):
box = (
x,
y,
min(x + COLOR_TILE_SIDE, image.width),
min(y + COLOR_TILE_SIDE, image.height),
)
with closing(image.crop(box)) as tile, closing(transform(tile)) as transformed:
result.paste(transformed, box)
return result
def rgb_mask(image: Image.Image, color: tuple[int, ...]) -> Image.Image:
return map_tiles(image, "L", lambda tile: rgb_tile_mask(tile, color))
def rgb_tile_mask(image: Image.Image, color: tuple[int, ...]) -> Image.Image:
mask = Image.new("L", image.size, 255)
for channel, value in zip("RGB", color, strict=True):
mask = ImageChops.multiply(
mask, image.getchannel(channel).point([255 if i == value else 0 for i in range(256)])
)
return mask
def apply_png_transparency(image: PngImageFile, data: bytes) -> None:
if (transparent := image.info.get("transparency")) is None:
return
depth = read_png_header(data)[2]
if image.mode == "L" and depth in (2, 4):
image.info["transparency"] = transparent * 255 // ((1 << depth) - 1)
elif image.mode == "RGB" and depth == PNG_WIDE_DEPTH:
with closing(PngImageFile(BytesIO(data))) as low:
low.tile = [tile._replace(args="RGB;16L") for tile in low.tile]
mask = rgb_mask(low, tuple(value & 255 for value in transparent))
with (
closing(mask),
closing(rgb_mask(image, tuple(value >> 8 for value in transparent))) as high,
closing(ImageChops.multiply(mask, high)) as combined,
):
image.paste((255, 255, 255), mask=combined)
image.info.pop("transparency")
def flatten(image: Image.Image) -> Image.Image:
if image.mode == "RGB" and "transparency" not in image.info:
return image
return map_tiles(image, "RGB", flatten_tile)
def flatten_tile(image: Image.Image) -> Image.Image:
if image.mode in WIDE_MODES:
image = image.convert("I").point(lambda value: value / 256, "L")
if image.mode == "P":
image = image.convert("RGBA" if "transparency" in image.info else "RGB")
if image.mode in ALPHA_MODES:
image = image.convert("I")
if (transparent := image.info.pop("transparency", None)) is not None:
mask = [0] * 65536
mask[transparent] = 255
image.paste(65535, mask=image.point(mask, "L"))
image = image.point(lambda value: value / 256, "L")
if image.mode in ALPHA_MODES or "transparency" in image.info:
image = image.convert("RGBA")
if image.mode == "RGBA":
background = Image.new("RGB", image.size, "white")
@@ -116,12 +181,17 @@ def decoded(data: bytes, max_pixels: int) -> tuple[Image.Image, int, int]:
width, height = image.size
if width * height > max_pixels:
raise UnreadableImage("изображение больше допустимого числа пикселей")
if isinstance(image, PngImageFile):
apply_png_transparency(image, data)
image.draft(None, fit(width, height, OPTIMIZED_BOX))
stored = image.size
ImageOps.exif_transpose(image, in_place=True)
if image.size != stored:
width, height = height, width
return flatten(image), width, height
upright = flatten(image)
if upright is not image:
image.close()
return upright, width, height
except UnreadableImage, MemoryError:
raise
except Exception as error:
@@ -0,0 +1,118 @@
import struct
import zlib
from collections.abc import Iterator
type PngHeader = tuple[int, int, int, int, int, int, int]
SIGNATURE = b"\x89PNG\r\n\x1a\n"
HEADER_BYTES = 13
CHUNK_OVERHEAD = 12
BLOCK_BYTES = 65_536
MAX_FILTER = 4
PIXELS = {
0: (1, (1, 2, 4, 8, 16)),
2: (3, (8, 16)),
3: (1, (1, 2, 4, 8)),
4: (2, (8, 16)),
6: (4, (8, 16)),
}
ADAM7 = (
(0, 0, 8, 8),
(4, 0, 8, 8),
(0, 4, 4, 8),
(2, 0, 4, 4),
(0, 2, 2, 4),
(1, 0, 2, 2),
(0, 1, 1, 2),
)
def _chunks(data: bytes) -> Iterator[tuple[bytes, memoryview]]:
view = memoryview(data)
offset = len(SIGNATURE)
while offset + CHUNK_OVERHEAD <= len(data):
size = struct.unpack_from(">I", data, offset)[0]
kind = data[offset + 4 : offset + 8]
start, end = offset + 8, offset + 8 + size
if end + 4 > len(data):
raise ValueError("truncated PNG chunk")
yield kind, view[start:end]
if kind == b"IEND":
return
offset = end + 4
raise ValueError("missing PNG end")
def read_png_header(data: bytes) -> PngHeader:
chunks = _chunks(data)
kind, header = next(chunks)
if kind != b"IHDR" or len(header) != HEADER_BYTES:
raise ValueError("invalid first PNG header")
if any(kind == b"IHDR" for kind, _ in chunks):
raise ValueError("duplicate PNG header")
return struct.unpack(">IIBBBBB", header)
def _scanlines(header: PngHeader) -> Iterator[tuple[int, int]]:
width, height, depth, color, compression, filtering, interlace = header
samples, depths = PIXELS[color]
if depth not in depths or compression or filtering or interlace not in (0, 1):
raise ValueError("invalid PNG header")
passes = ADAM7 if interlace else ((0, 0, 1, 1),)
for x, y, dx, dy in passes:
columns, rows = (width - x + dx - 1) // dx, (height - y + dy - 1) // dy
if columns > 0 and rows > 0:
stride = 1 + (columns * samples * depth + 7) // 8
yield stride, stride * rows
def _idat(data: bytes) -> Iterator[memoryview]:
started = ended = False
for kind, payload in _chunks(data):
if kind == b"IDAT":
if ended:
raise ValueError("nonconsecutive PNG image data")
started = True
for position in range(0, len(payload), BLOCK_BYTES):
yield payload[position : position + BLOCK_BYTES]
elif started:
ended = True
def _inflate(data: bytes) -> Iterator[bytes]:
decoder = zlib.decompressobj()
for block in _idat(data):
if decoder.eof:
continue
pending = block
while True:
decoded = decoder.decompress(pending, BLOCK_BYTES)
yield decoded
pending = decoder.unconsumed_tail
if decoder.eof or (not pending and len(decoded) < BLOCK_BYTES):
break
if not decoder.eof:
raise ValueError("incomplete PNG compressed data")
def verify_png_pixels(data: bytes, header: PngHeader) -> None:
passes = _scanlines(header)
stride, remaining = next(passes)
offset = 0
for decoded in _inflate(data):
cursor = 0
while cursor < len(decoded):
if not remaining:
stride, remaining = next(passes, (0, 0))
offset = 0
if not remaining:
raise ValueError("extra PNG pixel data")
size = min(remaining, len(decoded) - cursor)
filters = decoded[cursor + (-offset % stride) : cursor + size : stride]
if max(filters, default=0) > MAX_FILTER:
raise ValueError("invalid PNG filter")
cursor += size
offset += size
remaining -= size
if remaining or next(passes, None) is not None:
raise ValueError("incomplete PNG pixel data")
@@ -69,10 +69,10 @@ class CloseSessionHandler:
self._revocations = revocations
async def __call__(self, command: CloseSession) -> None:
await self._revocations.revoke(command.session)
try:
async with self._uow.transaction():
await self._uow.sessions.remove(command.session.token_hash)
await self._revocations.revoke(command.session)
self._uow.record(SessionClosed(user_id=command.session.user_id))
await self._uow.commit()
except BaseException:
+2
View File
@@ -30,6 +30,8 @@ class DisplayName:
def __post_init__(self) -> None:
if not isinstance(self.value, str):
raise InvalidUserData("поле display_name должно быть строкой")
if "\x00" in self.value:
raise InvalidUserData("поле display_name не может содержать NUL")
if not self.value.strip():
raise InvalidUserData("поле display_name не может быть пустым или состоять из пробелов")
if len(self.value) > DISPLAY_NAME_MAX:
@@ -30,14 +30,14 @@ def challenge_for(path: str) -> str:
def basic_credentials(value: str) -> tuple[str, str] | None:
scheme, _, encoded = value.partition(" ")
if scheme.lower() != "basic":
if scheme.lower() != "basic" or not encoded.isascii():
return None
try:
decoded = b64decode(encoded.strip(), validate=True).decode("utf-8")
except Base64Error, UnicodeDecodeError:
return None
username, separator, password = decoded.partition(":")
if not separator or not username.isascii():
if not separator or not username.isascii() or "\x00" in username:
return None
return username, password
@@ -166,10 +166,12 @@ class PostgresSessionDirectory:
async with self._database.session() as session:
row = (
await session.execute(
select(SessionRow).where(
select(SessionRow)
.where(
SessionRow.token_hash == token_hash,
SessionRow.expires_at > now,
)
.with_for_update(read=True, key_share=True)
)
).scalar_one_or_none()
if row is None:
@@ -1,7 +1,7 @@
import time
from collections.abc import Awaitable
from datetime import datetime, timedelta
from uuid import UUID
from uuid import UUID, uuid4
from redis.asyncio import Redis
from redis.exceptions import RedisError
@@ -13,6 +13,16 @@ from messenger.shared.application.ports import Logger
REVOKED = "-"
FAILURES = (RedisError, OSError)
FILL = """
if redis.call('GET', KEYS[2]) ~= ARGV[1] then return false end
redis.call('DEL', KEYS[2])
if ARGV[2] == '' then return false end
return redis.call('SET', KEYS[1], ARGV[2], 'PXAT', ARGV[3], 'NX')
"""
REVOKE = """
redis.call('SET', KEYS[1], ARGV[1], 'PXAT', ARGV[2])
return redis.call('DEL', KEYS[2])
"""
def key_of(token_hash: bytes) -> str:
@@ -72,18 +82,26 @@ class CachedSessionDirectory:
if cached is not None:
session = decode(token_hash, cached)
return session if session.expires_at > now else None
marker, nonce = f"{key}:fill", uuid4().hex
until = milliseconds(now + self._limit)
reserved = self._closed() and await self._quietly(
self._client.set(marker, nonce, pxat=until, nx=True)
)
session = await self._origin.find(token_hash, now)
if session is not None and self._closed():
until = milliseconds(min(session.expires_at, now + self._limit))
await self._quietly(self._client.set(key, encode(session), pxat=until, nx=True))
if reserved and self._closed():
value = encode(session) if session is not None else ""
if session is not None:
until = min(until, milliseconds(session.expires_at))
await self._quietly(self._client.eval(FILL, 2, key, marker, nonce, value, until))
return session
async def revoke(self, session: Session) -> None:
if not self._closed():
raise Unavailable("кэш сессий недоступен")
key = key_of(session.token_hash)
try:
await self._client.set(
key_of(session.token_hash), REVOKED, pxat=milliseconds(session.expires_at)
await self._client.eval(
REVOKE, 2, key, f"{key}:fill", REVOKED, milliseconds(session.expires_at)
)
except FAILURES as error:
self._trip(error)
+4
View File
@@ -15,6 +15,8 @@ class ChatTitle:
def __post_init__(self) -> None:
if not isinstance(self.value, str):
raise InvalidChatData("поле title должно быть строкой")
if "\x00" in self.value:
raise InvalidChatData("поле title не может содержать NUL")
if not self.value.strip():
raise InvalidChatData("поле title не может быть пустым или состоять из пробелов")
if len(self.value) > CHAT_TITLE_MAX:
@@ -31,6 +33,8 @@ class MessageText:
def __post_init__(self) -> None:
if not isinstance(self.value, str):
raise InvalidMessageText("поле text должно быть строкой")
if "\x00" in self.value:
raise InvalidMessageText("поле text не может содержать NUL")
if self.value and not self.value.strip():
raise InvalidMessageText("поле text не может состоять из пробелов")
if len(self.value) > MESSAGE_TEXT_MAX: