forked from mtusi2026/mtusi2026lab5
перенос: реализация lab4 без изменений (API, миграции 0001-0004, HAProxy, Valkey, SeaweedFS, тесты)
Скопировано из mtusi2026lab4 (ветка solution/bvt2302-bodanyuk, commit 17c33cd) через git archive: исходники, миграции, собственные тесты, Dockerfile, compose, конфигурации infra/, скрипты и bench/. README, COURSE, contracts/, tests/ и отчёт lab4 не копировались. Makefile и .env.example — версии lab4 (skeleton-часть совпадает с lab5, строки broker добавляются в следующих коммитах). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
276dbdad8a
commit
5112be83cc
@@ -0,0 +1,148 @@
|
||||
"""Unit tests of the image checks (src/messenger/images.py) and the filename rules. No services.
|
||||
|
||||
The JPEG decoder (djpeg) exists in the API image; locally these tests are skipped without it
|
||||
(the same cases run against the stand in test_attachments.py)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "src"))
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
|
||||
import imagegen # noqa: E402
|
||||
from messenger import images, validation # noqa: E402
|
||||
from messenger.errors import InvalidRequest # noqa: E402
|
||||
|
||||
LIMIT = 40_000_000
|
||||
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
has_djpeg = pytest.mark.skipif(shutil.which("djpeg") is None, reason="djpeg (libjpeg-turbo-progs) not installed")
|
||||
|
||||
|
||||
def status(data: bytes) -> int:
|
||||
"""201 if accepted, else the HTTP status of the ImageError (413/415)."""
|
||||
try:
|
||||
info = images.sniff(data, LIMIT)
|
||||
if info is None:
|
||||
return 415 # header never completed
|
||||
asyncio.run(images.verify(data, info))
|
||||
return 201
|
||||
except images.ImageError as exc:
|
||||
return exc.status
|
||||
|
||||
|
||||
def test_public_fixture_is_accepted():
|
||||
assert images.sniff(SAMPLE, LIMIT) == images.ImageInfo("image/png", 320, 200)
|
||||
assert status(SAMPLE) == 201
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", [
|
||||
imagegen.png(37, 23, "RGBA"), imagegen.png(33, 17, "P"), imagegen.png(33, 17, "1"),
|
||||
imagegen.png(33, 17, "L"), imagegen.png(81, 57, "RGB", noise=True), imagegen.png(1, 1),
|
||||
], ids=["rgba", "palette", "1bit", "gray", "noise", "1x1"])
|
||||
def test_valid_png_kinds(data):
|
||||
assert status(data) == 201
|
||||
|
||||
|
||||
def test_interlaced_png_is_accepted():
|
||||
# Pillow cannot write Adam7; build one by hand: 9 x 9 grey, every pass with filter 0.
|
||||
from messenger.images import _png_segments
|
||||
raw = b"".join(b"\x00" + bytes(stride - 1) for size, stride in _png_segments(9, 9, 8, 0, 1)
|
||||
for _ in range(size // stride))
|
||||
data = imagegen.PNG_SIGNATURE + imagegen.ihdr(9, 9, 8, 0, 1) + imagegen.chunk(b"IDAT", __import__("zlib").compress(raw)) \
|
||||
+ imagegen.chunk(b"IEND", b"")
|
||||
assert status(data) == 201
|
||||
|
||||
|
||||
BROKEN_PNG = {
|
||||
"first 33 bytes of the fixture": SAMPLE[:33],
|
||||
"truncated (no IEND)": SAMPLE[:-12],
|
||||
"truncated in IDAT": SAMPLE[:len(SAMPLE) // 2],
|
||||
"flipped byte -> CRC error": SAMPLE[:500] + bytes([SAMPLE[500] ^ 0xFF]) + SAMPLE[501:],
|
||||
"garbage IDAT with valid CRC": imagegen.png_corrupt_idat(),
|
||||
"fewer rows than IHDR": imagegen.png_short_pixels(),
|
||||
"bytes after IEND (polyglot)": SAMPLE + b"PK\x03\x04zip",
|
||||
"text": b"just text, definitely not an image",
|
||||
"gif": b"GIF89a" + bytes(64),
|
||||
"two bytes of a signature": b"\x89P",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", list(BROKEN_PNG))
|
||||
def test_broken_png_is_415(name):
|
||||
assert status(BROKEN_PNG[name]) == 415, name
|
||||
|
||||
|
||||
def test_pixel_limit_is_checked_from_the_header():
|
||||
with pytest.raises(images.ImageError) as exc:
|
||||
images.sniff(imagegen.png_bomb_header()[:33], LIMIT) # 33 bytes are enough
|
||||
assert exc.value.status == 413
|
||||
exact = imagegen.PNG_SIGNATURE + imagegen.ihdr(8000, 5000) # exactly 40 000 000: allowed
|
||||
assert images.sniff(exact, LIMIT).width == 8000
|
||||
with pytest.raises(images.ImageError) as exc:
|
||||
images.sniff(imagegen.PNG_SIGNATURE + imagegen.ihdr(8001, 5000), LIMIT)
|
||||
assert exc.value.status == 413
|
||||
with pytest.raises(images.ImageError) as exc:
|
||||
images.sniff(imagegen.jpeg_bomb_header(), LIMIT)
|
||||
assert exc.value.status == 413
|
||||
|
||||
|
||||
def test_png_verification_is_streaming_and_fast():
|
||||
"""40 Mpx RGB = 120 MB of raw pixels: inflated in 1 MiB steps and discarded."""
|
||||
big = imagegen.png(8000, 5000, compress_level=9)
|
||||
started = time.perf_counter()
|
||||
assert status(big) == 201
|
||||
assert time.perf_counter() - started < 5
|
||||
|
||||
|
||||
def test_jpeg_header_is_parsed_incrementally():
|
||||
data = imagegen.jpeg(320, 200)
|
||||
assert images.sniff(data[:4], LIMIT) is None # SOF not arrived yet
|
||||
assert images.sniff(data, LIMIT) == images.ImageInfo("image/jpeg", 320, 200)
|
||||
|
||||
|
||||
@has_djpeg
|
||||
@pytest.mark.parametrize("data", [imagegen.jpeg(), imagegen.jpeg(640, 480, progressive=True)], ids=["base", "prog"])
|
||||
def test_valid_jpeg(data):
|
||||
assert status(data) == 201
|
||||
|
||||
|
||||
@has_djpeg
|
||||
@pytest.mark.parametrize("name,data", [
|
||||
("no scan data after SOS", imagegen.jpeg_without_scan_data()),
|
||||
("truncated", imagegen.jpeg(320, 240, noise=True)[:3000]),
|
||||
], ids=lambda v: v if isinstance(v, str) else "")
|
||||
def test_broken_jpeg_is_415(name, data):
|
||||
assert status(data) == 415, name
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ filename
|
||||
@pytest.mark.parametrize("name", ["photo.png", "фото отпуска.jpg", "a" * 255, "emoji 👨👩👧.png", " x ", "..."[:2] + "x"])
|
||||
def test_good_filenames(name):
|
||||
assert validation.filename_param([("filename", name)]) == name
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["", " ", " ", ".", "..", "a/b.png", "a\\b.png", "a\x00b", "c1\x85.png",
|
||||
"tab\t.png", "del\x7f.png", "x
y", "photognp.exe", "a" * 256])
|
||||
def test_bad_filenames(name):
|
||||
with pytest.raises(InvalidRequest):
|
||||
validation.filename_param([("filename", name)])
|
||||
|
||||
|
||||
def test_filename_must_be_single_and_present():
|
||||
with pytest.raises(InvalidRequest):
|
||||
validation.filename_param([])
|
||||
with pytest.raises(InvalidRequest):
|
||||
validation.filename_param([("filename", "a.png"), ("filename", "b.png")])
|
||||
|
||||
|
||||
def test_query_must_be_valid_utf8():
|
||||
assert validation.query_items(b"filename=%D1%84.png") == [("filename", "ф.png")]
|
||||
with pytest.raises(InvalidRequest):
|
||||
validation.query_items(b"filename=%FF%FE.png")
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Pure functions, no services: validation, cursor, Authorization parsing, Argon2id, config."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import datetime as dt
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger import authhdr, cursor, passwords, validation
|
||||
from messenger.config import ConfigError, Settings
|
||||
from messenger.errors import InvalidRequest, Unauthorized
|
||||
from messenger.timefmt import UTC, from_us, rfc3339, to_us
|
||||
|
||||
|
||||
def b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ password rules
|
||||
@pytest.mark.parametrize("password", ["Twelve-chars", "я" * 128, "пароль:с:двоеточиями", "😀" * 12, "a b c d e f g"])
|
||||
def test_valid_passwords(password):
|
||||
assert validation.password_field({"password": password}) == password
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password", ["short-11ch", "я" * 129, " " * 12, "\t\n " * 5, "\ud800" * 12, None, 123456789012])
|
||||
def test_invalid_passwords(password):
|
||||
with pytest.raises(InvalidRequest):
|
||||
validation.password_field({"password": password})
|
||||
|
||||
|
||||
def test_text_may_contain_nul_but_not_lone_surrogates():
|
||||
assert validation.text_field({"t": "a\u0000b"}, "t", 10) == "a\u0000b"
|
||||
with pytest.raises(InvalidRequest):
|
||||
validation.text_field({"t": "a\ud800"}, "t", 10)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ cursor
|
||||
CHAT = "3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11"
|
||||
|
||||
|
||||
def test_cursor_roundtrip_and_binding():
|
||||
key = (to_us(dt.datetime(2026, 10, 12, 12, 0, 0, 123456, tzinfo=UTC)), "11111111-1111-4111-8111-111111111111")
|
||||
token = cursor.encode(cursor.MESSAGES, CHAT, key)
|
||||
assert cursor.decode(token, cursor.MESSAGES, CHAT) == key
|
||||
with pytest.raises(InvalidRequest):
|
||||
cursor.decode(token, cursor.MESSAGES, "00000000-0000-4000-8000-000000000000") # other chat
|
||||
with pytest.raises(InvalidRequest):
|
||||
cursor.decode(token, cursor.CHATS, CHAT) # other resource
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
b"v1|m|" + CHAT.encode() + b"|253402300800000000|11111111-1111-4111-8111-111111111111", # 1 us after 9999-12-31
|
||||
b"v1|m|" + CHAT.encode() + b"|9999999999999999999|11111111-1111-4111-8111-111111111111", # int64 edge
|
||||
b"v1|m|" + CHAT.encode() + b"|-1|11111111-1111-4111-8111-111111111111",
|
||||
b"v1|m|" + CHAT.encode() + b"|1|not-a-uuid",
|
||||
b"v1|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-11111111111G",
|
||||
b"v2|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-111111111111",
|
||||
])
|
||||
def test_broken_cursors_are_400_not_500(payload):
|
||||
token = base64.urlsafe_b64encode(payload).rstrip(b"=").decode()
|
||||
with pytest.raises(InvalidRequest):
|
||||
cursor.decode(token, cursor.MESSAGES, CHAT)
|
||||
|
||||
|
||||
def test_time_helpers_are_exact():
|
||||
moment = dt.datetime(2026, 2, 28, 23, 59, 59, 999999, tzinfo=UTC)
|
||||
assert from_us(to_us(moment)) == moment
|
||||
assert rfc3339(moment) == "2026-02-28T23:59:59.999999Z"
|
||||
assert from_us(cursor.MAX_TS_US).year == 9999
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Authorization header
|
||||
def test_basic_is_parsed_and_password_may_contain_colons():
|
||||
assert authhdr.parse_basic("Basic " + b64("alice:pa:ss:wörd".encode())) == ("alice", "pa:ss:wörd")
|
||||
assert authhdr.parse_basic("basic " + b64(b"bob_1:x" * 1)) == ("bob_1", "x")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("header", [
|
||||
None, "", "Basic", "Basic é", "Basic !!!!", "Basic " + b64(b"no-colon"), "Basic " + b64(b"\xff\xfe:pw"),
|
||||
"Basic " + b64(b":password"), "Basic " + b64(b"alice:"), "Basic " + b64("Алиса:pw".encode()),
|
||||
"Bearer " + "a" * 43, "Basic " + "A" * 2000,
|
||||
])
|
||||
def test_bad_basic_is_401_with_basic_challenge(header):
|
||||
with pytest.raises(Unauthorized) as info:
|
||||
authhdr.parse_basic(header)
|
||||
assert info.value.headers["WWW-Authenticate"].startswith("Basic realm=\"messenger\"")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("header", [None, "", "Bearer", "Bearer short", "Bearer " + "a" * 43 + "!",
|
||||
"Basic " + b64(b"alice:password-123"), "Token " + "a" * 43, "Bearer " + "é" * 43])
|
||||
def test_bad_bearer_is_401_with_bearer_challenge(header):
|
||||
with pytest.raises(Unauthorized) as info:
|
||||
authhdr.parse_bearer(header)
|
||||
assert info.value.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def test_bearer_ok():
|
||||
token = "A_b-" + "x" * 39
|
||||
assert authhdr.parse_bearer("Bearer " + token) == token
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Argon2id
|
||||
def test_argon2id_hash_and_verify():
|
||||
async def scenario():
|
||||
stored = await passwords.hash_password("я" * 128)
|
||||
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
||||
assert await passwords.verify_password(stored, "я" * 128)
|
||||
assert not await passwords.verify_password(stored, "я" * 127)
|
||||
assert not await passwords.verify_password(None, "anything") # unknown user, dummy hash
|
||||
assert not await passwords.verify_password("not-a-hash", "anything")
|
||||
assert await passwords.hash_password("same password!") != await passwords.hash_password("same password!") # salt
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ config
|
||||
@pytest.fixture(autouse=True)
|
||||
def s3_credentials(monkeypatch):
|
||||
"""Lab 4: Settings require the API's S3 key pair; synthetic values for the unit tests."""
|
||||
monkeypatch.setenv("S3_ACCESS_KEY_ID", "AKTEST")
|
||||
monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret-for-unit-tests")
|
||||
|
||||
|
||||
def test_s3_settings_are_validated_and_contract_limits_cannot_be_raised(monkeypatch):
|
||||
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
|
||||
settings = Settings.from_env()
|
||||
assert (settings.max_upload_bytes, settings.max_image_pixels) == (10 * 1024 * 1024, 40_000_000)
|
||||
assert settings.fault_points == frozenset() and settings.upload_concurrency == 4
|
||||
for name, value in (("MAX_UPLOAD_BYTES", "10485761"), ("MAX_IMAGE_PIXELS", "40000001"),
|
||||
("FAULT_POINTS", "drop_database"), ("S3_ENDPOINT", "ftp://s3"), ("S3_BUCKET", "Bad_Bucket")):
|
||||
monkeypatch.setenv(name, value)
|
||||
with pytest.raises(ConfigError):
|
||||
Settings.from_env()
|
||||
monkeypatch.delenv(name)
|
||||
monkeypatch.delenv("S3_SECRET_ACCESS_KEY")
|
||||
with pytest.raises(ConfigError):
|
||||
Settings.from_env()
|
||||
|
||||
|
||||
def test_settings_read_secret_files_and_contract_names(tmp_path, monkeypatch):
|
||||
url_file = tmp_path / "database_url"
|
||||
url_file.write_text("postgresql://u:p@db/x\n", encoding="utf-8")
|
||||
monkeypatch.setenv("DATABASE_URL_FILE", str(url_file))
|
||||
monkeypatch.setenv("SESSION_STORE", "redis")
|
||||
monkeypatch.setenv("CACHE_URL", "redis://:p@valkey:6379/0")
|
||||
monkeypatch.setenv("SESSION_TTL_SECONDS", "2")
|
||||
settings = Settings.from_env()
|
||||
assert settings.database_url == "postgresql://u:p@db/x"
|
||||
assert settings.session_store == "valkey" and settings.session_ttl_seconds == 2
|
||||
monkeypatch.setenv("SESSION_TTL_SECONDS", "0")
|
||||
with pytest.raises(ConfigError):
|
||||
Settings.from_env()
|
||||
monkeypatch.setenv("SESSION_TTL_SECONDS", "2")
|
||||
monkeypatch.setenv("DATABASE_URL_FILE", str(tmp_path / "missing"))
|
||||
with pytest.raises(ConfigError) as info:
|
||||
Settings.from_env()
|
||||
assert "u:p" not in str(info.value)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ lab 3: idempotency, JSON, instance id
|
||||
@pytest.mark.parametrize("key", ["a", "k" * 128, "A-Za-z0-9._:-", "2026-10-16T10:00:00.1"])
|
||||
def test_valid_idempotency_keys(key):
|
||||
assert validation.idempotency_key(key) == key
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", [None, "", "k" * 129, "ключ", "a b", "a/b", "a,b", "a\tb", "a\x00b", "*", "é"])
|
||||
def test_invalid_idempotency_keys(key):
|
||||
with pytest.raises(InvalidRequest):
|
||||
validation.idempotency_key(key)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", [b'{"text":"a","text":"b"}', b'{"a":{"x":1,"x":2}}', b'\xff', b'{"text":"x"} {}'])
|
||||
def test_duplicate_keys_and_garbage_json_are_rejected(raw):
|
||||
with pytest.raises(InvalidRequest):
|
||||
validation.parse_json_object(raw)
|
||||
|
||||
|
||||
def test_attachment_ids_absent_equals_empty_and_is_validated():
|
||||
assert validation.attachment_ids_field({"text": "x"}) == []
|
||||
assert validation.attachment_ids_field({"attachment_ids": []}) == []
|
||||
one = "11111111-1111-4111-8111-111111111111"
|
||||
assert validation.attachment_ids_field({"attachment_ids": [one.upper()]}) == [one]
|
||||
for bad in (None, "x", [1], ["nope"], [one, one.upper()], [one] * 11):
|
||||
with pytest.raises(InvalidRequest):
|
||||
validation.attachment_ids_field({"attachment_ids": bad})
|
||||
|
||||
|
||||
def test_request_fingerprint_ignores_key_order_and_default_attachments():
|
||||
from messenger.app import request_fingerprint
|
||||
assert request_fingerprint("привет", []) == request_fingerprint("привет", [])
|
||||
assert request_fingerprint("привет", []) != request_fingerprint("привет ", [])
|
||||
assert request_fingerprint("a\u0000b", []) != request_fingerprint("ab", [])
|
||||
one = "11111111-1111-4111-8111-111111111111"
|
||||
assert request_fingerprint("x", [one]) != request_fingerprint("x", [])
|
||||
|
||||
|
||||
def test_instance_id_defaults_to_hostname_and_is_validated(monkeypatch):
|
||||
import socket
|
||||
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
|
||||
monkeypatch.delenv("INSTANCE_ID", raising=False)
|
||||
assert Settings.from_env().instance_id == socket.gethostname()
|
||||
monkeypatch.setenv("INSTANCE_ID", "replica-a")
|
||||
assert Settings.from_env().instance_id == "replica-a"
|
||||
for bad in ("with space", "x" * 65, "ip/1"):
|
||||
monkeypatch.setenv("INSTANCE_ID", bad)
|
||||
with pytest.raises(ConfigError):
|
||||
Settings.from_env()
|
||||
|
||||
|
||||
def test_idempotency_ttl_cannot_be_below_24_hours(monkeypatch):
|
||||
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
|
||||
monkeypatch.setenv("IDEMPOTENCY_TTL_SECONDS", "3600")
|
||||
with pytest.raises(ConfigError):
|
||||
Settings.from_env()
|
||||
|
||||
|
||||
def test_message_write_path_setting(monkeypatch):
|
||||
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
|
||||
monkeypatch.delenv("MESSAGE_WRITE_PATH", raising=False)
|
||||
assert Settings.from_env().message_write_path == "function"
|
||||
monkeypatch.setenv("MESSAGE_WRITE_PATH", "multi")
|
||||
assert Settings.from_env().message_write_path == "multi"
|
||||
monkeypatch.setenv("MESSAGE_WRITE_PATH", "fast")
|
||||
with pytest.raises(ConfigError):
|
||||
Settings.from_env()
|
||||
Reference in New Issue
Block a user