feat: import lab 7 security implementation

This commit is contained in:
2026-12-02 23:44:32 +03:00
parent 20afc2c790
commit ee28cd7dbd
259 changed files with 84919 additions and 35 deletions
+122
View File
@@ -0,0 +1,122 @@
"""Лаба 7: предел размера тела запроса вне загрузки вложения (64 KiB).
Отказ — 400 `invalid_request` реплики (с `X-Request-Id` и `X-Instance-Id`),
тело дальше предела не читается; в LB предела нет. Порядок кодов прежний:
без токена на защищённой ручке — 401 раньше 400 («сначала аутентификация»).
Наибольшее валидное тело контракта (сообщение из 4000 экранированных
суррогатных пар и 10 вложений, ~48,4 KB) принимается; загрузка вложения
пределом JSON не ограничена.
"""
import json
import httpx
import images
from helpers import (
BEARER_CHALLENGE,
SESSIONS,
assert_error,
assert_unauthorized,
basic_header,
create_chat,
headers,
messages_path,
new_key,
read_history,
register,
uploaded,
)
BODY_MAX_BYTES = 65536
TOO_LARGE = "Request body is too large"
def _post_message(
client: httpx.Client, chat: dict, content, auth: dict
) -> httpx.Response: # noqa: ANN001
return client.post(
messages_path(chat),
content=content,
headers={
**auth,
"Content-Type": "application/json",
"Idempotency-Key": new_key(),
},
)
def _chunks(total: int, size: int = 8192): # noqa: ANN202
"""Тело частями без Content-Length (httpx шлёт chunked)."""
sent = 0
while sent < total:
part = min(size, total - sent)
sent += part
yield b" " * part
def test_declared_body_over_limit(client: httpx.Client) -> None:
alice = register(client, "body")
chat = create_chat(client, alice)
body = b'{"text": "x"' + b" " * (BODY_MAX_BYTES + 1 - 13) + b"}"
assert len(body) == BODY_MAX_BYTES + 1
response = _post_message(client, chat, body, headers(alice))
error = assert_error(response, 400, "invalid_request")
assert error["message"] == TOO_LARGE
# без токена — 401 раньше размера (порядок кодов контракта)
anonymous = _post_message(client, chat, body, {})
assert_unauthorized(anonymous, BEARER_CHALLENGE)
assert read_history(client, alice, chat, limit=10)[0] == []
def test_chunked_body_over_limit(client: httpx.Client) -> None:
alice = register(client, "body")
chat = create_chat(client, alice)
response = _post_message(
client, chat, _chunks(BODY_MAX_BYTES + 8192), headers(alice)
)
error = assert_error(response, 400, "invalid_request")
assert error["message"] == TOO_LARGE
assert read_history(client, alice, chat, limit=10)[0] == []
def test_login_large_body(client: httpx.Client) -> None:
"""Вход тело не читает, но объявленное тело больше предела — 400 до
проверки credentials, сессии нет."""
alice = register(client, "body")
response = client.post(
SESSIONS,
headers={
**basic_header(alice["username"], alice["password"]),
"Content-Type": "application/json",
},
content=b" " * (BODY_MAX_BYTES + 1),
)
error = assert_error(response, 400, "invalid_request")
assert error["message"] == TOO_LARGE
assert "token" not in response.text
def test_largest_valid_body_accepted(client: httpx.Client) -> None:
alice = register(client, "body")
chat = create_chat(client, alice)
attachment_ids = [uploaded(client, alice, chat)["id"] for _ in range(10)]
# 4000 символов вне BMP, каждый — экранированная суррогатная пара
text = "\\ud83d\\ude00" * 4000
body = (
'{"text": "' + text + '", "attachment_ids": ' + json.dumps(attachment_ids) + "}"
).encode("ascii")
assert 48000 < len(body) < BODY_MAX_BYTES
response = _post_message(client, chat, body, headers(alice))
assert response.status_code == 201, response.text
message = response.json()
assert message["text"] == "\U0001f600" * 4000
assert message["attachment_ids"] == attachment_ids
def test_upload_not_limited_by_json_limit(client: httpx.Client) -> None:
alice = register(client, "body")
chat = create_chat(client, alice)
data = images.png_of_size(4 * BODY_MAX_BYTES, seed=7)
assert len(data) > BODY_MAX_BYTES
uploaded(client, alice, chat, data)