Port final lab 4 validation and session revocation fixes

This commit is contained in:
Artyom
2026-11-06 22:33:31 +03:00
parent f88e9ba43c
commit 0e92111661
47 changed files with 5097 additions and 32 deletions
@@ -27,6 +27,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}
@@ -60,6 +61,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,17 +69,18 @@ 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)
@@ -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: