Forward final lab3 session security and validation fixes

This commit is contained in:
Artyom
2026-11-06 12:07:00 +03:00
parent f0fc084fbb
commit 75b93bbba5
41 changed files with 2864 additions and 28 deletions
@@ -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: