forked from mtusi2026/mtusi2026lab4
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d28217985a | ||
|
|
3ab75600c1 | ||
|
|
6b09a1b446 | ||
|
|
794cff9a8c | ||
|
|
a3d6beb066 | ||
|
|
51f98e526e | ||
|
|
0d58963bc3 | ||
|
|
d4a73152e4 | ||
|
|
af209723d2 | ||
|
|
2b89811423 |
@@ -23,3 +23,9 @@ UPLOAD_CHUNK_SIZE=65536
|
|||||||
# SeaweedFS S3-шлюз credentials (только для локального стенда; не коммитить .env).
|
# SeaweedFS S3-шлюз credentials (только для локального стенда; не коммитить .env).
|
||||||
S3_ACCESS_KEY_ID=seaweedfs
|
S3_ACCESS_KEY_ID=seaweedfs
|
||||||
S3_SECRET_ACCESS_KEY=seaweedfs-local-only
|
S3_SECRET_ACCESS_KEY=seaweedfs-local-only
|
||||||
|
# Закрепление образов по digest (опционально; по умолчанию — теги из compose.yaml).
|
||||||
|
# Пример: POSTGRES_IMAGE=postgres:16.4-alpine@sha256:<digest>
|
||||||
|
# POSTGRES_IMAGE=
|
||||||
|
# REDIS_IMAGE=
|
||||||
|
# SEAWEEDFS_IMAGE=
|
||||||
|
# NGINX_IMAGE=
|
||||||
|
|||||||
@@ -30,3 +30,4 @@ coverage/
|
|||||||
.vscode/
|
.vscode/
|
||||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||||
|
.aider*
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
PYTHON ?= python3
|
PYTHON ?= python
|
||||||
BASE_URL ?= http://localhost:8080
|
BASE_URL ?= http://localhost:8080
|
||||||
CA_FILE ?=
|
CA_FILE ?=
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Отчёт — лабораторная 4
|
# Отчёт — лабораторная 4
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Бушков Евгений, БВТ2301
|
||||||
- Целевая оценка: **4** (трек 5 не заявляется)
|
- Целевая оценка: **4** (трек 5 не заявляется)
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: TODO после публикации
|
||||||
- Использованные источники, библиотеки и помощь ИИ: FastAPI, SQLAlchemy 2, Alembic, boto3, Pillow, SeaweedFS (S3-совместимое хранилище), argon2-cffi. ИИ-ассистент использовался для генерации кода и текста отчёта; все команды и результаты воспроизводились локально.
|
- Использованные источники, библиотеки и помощь ИИ: FastAPI, SQLAlchemy 2, Alembic, boto3, Pillow, SeaweedFS (S3-совместимое хранилище), argon2-cffi. ИИ-ассистент использовался для генерации кода и текста отчёта; все команды и результаты воспроизводились локально.
|
||||||
|
|||||||
+14
-3
@@ -28,9 +28,20 @@ def run_migrations_online() -> None:
|
|||||||
poolclass=pool.NullPool,
|
poolclass=pool.NullPool,
|
||||||
)
|
)
|
||||||
with connectable.connect() as connection:
|
with connectable.connect() as connection:
|
||||||
context.configure(connection=connection, target_metadata=target_metadata)
|
# Advisory lock сериализует параллельные запуски alembic upgrade
|
||||||
with context.begin_transaction():
|
# (например, при старте нескольких реплик одновременно).
|
||||||
context.run_migrations()
|
# В SQLAlchemy 2.0 engine.connect() открывает неявную транзакцию,
|
||||||
|
# поэтому после run_migrations() её нужно явно закоммитить —
|
||||||
|
# иначе DDL откатится при закрытии соединения.
|
||||||
|
connection.exec_driver_sql("SELECT pg_advisory_lock(727274)")
|
||||||
|
try:
|
||||||
|
context.configure(connection=connection, target_metadata=target_metadata)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
connection.commit()
|
||||||
|
finally:
|
||||||
|
connection.exec_driver_sql("SELECT pg_advisory_unlock(727274)")
|
||||||
|
connection.commit()
|
||||||
|
|
||||||
|
|
||||||
if context.is_offline_mode():
|
if context.is_offline_mode():
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""pending_uploads
|
||||||
|
|
||||||
|
Revision ID: 0003
|
||||||
|
Revises: 0002
|
||||||
|
Create Date: 2026-11-06
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision = "0003"
|
||||||
|
down_revision = "0002"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"pending_uploads",
|
||||||
|
sa.Column("object_key", sa.String(255), primary_key=True),
|
||||||
|
sa.Column("chat_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("chats.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
sa.Column("owner_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id"), nullable=False),
|
||||||
|
sa.Column("size_bytes", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("sha256", sa.String(64), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||||
|
)
|
||||||
|
op.create_index("ix_pending_uploads_created_at", "pending_uploads", ["created_at"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_pending_uploads_created_at", table_name="pending_uploads")
|
||||||
|
op.drop_table("pending_uploads")
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""fix created_at server defaults
|
||||||
|
|
||||||
|
Revision ID: 0004
|
||||||
|
Revises: 0003
|
||||||
|
Create Date: 2026-11-06
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = "0004"
|
||||||
|
down_revision = "0003"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
_TABLES = (
|
||||||
|
"users",
|
||||||
|
"sessions",
|
||||||
|
"chats",
|
||||||
|
"messages",
|
||||||
|
"attachments",
|
||||||
|
"pending_uploads",
|
||||||
|
"idempotency_keys",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for table in _TABLES:
|
||||||
|
op.alter_column(
|
||||||
|
table,
|
||||||
|
"created_at",
|
||||||
|
server_default=sa.func.now(),
|
||||||
|
existing_type=sa.DateTime(timezone=True),
|
||||||
|
existing_nullable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table in _TABLES:
|
||||||
|
op.alter_column(
|
||||||
|
table,
|
||||||
|
"created_at",
|
||||||
|
server_default=None,
|
||||||
|
existing_type=sa.DateTime(timezone=True),
|
||||||
|
existing_nullable=False,
|
||||||
|
)
|
||||||
@@ -86,6 +86,25 @@ class MessageAttachment(Base):
|
|||||||
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||||
|
|
||||||
|
|
||||||
|
class PendingUpload(Base):
|
||||||
|
"""Журнал намерения загрузить объект в S3.
|
||||||
|
|
||||||
|
Пишется до `put_object`, снимается в той же транзакции, что и вставка
|
||||||
|
`attachments`. Если процесс упал между S3 PUT и COMMIT, запись остаётся
|
||||||
|
и её подбирает reconciler (`scripts/reconcile_orphans.py`) после grace
|
||||||
|
period. PK — object_key, чтобы повторная запись того же ключа была
|
||||||
|
идемпотентной.
|
||||||
|
"""
|
||||||
|
__tablename__ = "pending_uploads"
|
||||||
|
object_key: Mapped[str] = mapped_column(String(255), primary_key=True)
|
||||||
|
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
|
||||||
|
size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||||
|
__table_args__ = (Index("ix_pending_uploads_created_at", "created_at"),)
|
||||||
|
|
||||||
|
|
||||||
class IdempotencyKey(Base):
|
class IdempotencyKey(Base):
|
||||||
__tablename__ = "idempotency_keys"
|
__tablename__ = "idempotency_keys"
|
||||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
|
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
|
||||||
|
|||||||
@@ -67,8 +67,8 @@ async def upload_attachment(
|
|||||||
if declared not in ("image/png", "image/jpeg"):
|
if declared not in ("image/png", "image/jpeg"):
|
||||||
raise ApiError(415, "unsupported_media_type", "Ожидается image/png или image/jpeg")
|
raise ApiError(415, "unsupported_media_type", "Ожидается image/png или image/jpeg")
|
||||||
|
|
||||||
# Читаем тело потоково с жёстким лимитом.
|
# Читаем тело потоково с жёстким лимитом (async-итератор Starlette).
|
||||||
data, sha, actual = s3.read_upload(request.stream(), declared)
|
data, sha, actual = await s3.read_upload(request.stream(), declared)
|
||||||
|
|
||||||
att_id = uuid.uuid4()
|
att_id = uuid.uuid4()
|
||||||
key = s3.new_object_key(str(cid), str(att_id))
|
key = s3.new_object_key(str(cid), str(att_id))
|
||||||
|
|||||||
@@ -23,6 +23,13 @@ logger = logging.getLogger("messenger.s3")
|
|||||||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||||||
JPEG_MAGIC = b"\xff\xd8\xff"
|
JPEG_MAGIC = b"\xff\xd8\xff"
|
||||||
|
|
||||||
|
# Жёсткий лимит Pillow: любая попытка декодировать больше пикселей
|
||||||
|
# бросает DecompressionBombError до выделения памяти под растр.
|
||||||
|
Image.MAX_IMAGE_PIXELS = settings.max_image_pixels
|
||||||
|
|
||||||
|
# Сколько байт достаточно, чтобы прочитать заголовок PNG/JPEG и размеры.
|
||||||
|
_HEADER_BYTES = 64 * 1024
|
||||||
|
|
||||||
|
|
||||||
def _client():
|
def _client():
|
||||||
return boto3.client(
|
return boto3.client(
|
||||||
@@ -63,19 +70,23 @@ def _detect_mime(head: bytes) -> str | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _validate_image(data: bytes, declared_mime: str) -> str:
|
def _validate_header(header: bytes, declared_mime: str) -> str:
|
||||||
"""Проверяет magic bytes, декодирует заголовок, считает пиксели.
|
"""Проверяет magic bytes и размеры по заголовку.
|
||||||
|
|
||||||
|
Полное декодирование не выполняется: Pillow читает только заголовок
|
||||||
|
(IHDR для PNG, SOF для JPEG), что не выделяет память под растр.
|
||||||
Возвращает фактический MIME. Бросает ApiError(415/413).
|
Возвращает фактический MIME. Бросает ApiError(415/413).
|
||||||
"""
|
"""
|
||||||
actual = _detect_mime(data[:16])
|
actual = _detect_mime(header[:16])
|
||||||
if actual is None:
|
if actual is None:
|
||||||
raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG")
|
raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG")
|
||||||
if actual != declared_mime:
|
if actual != declared_mime:
|
||||||
raise ApiError(415, "unsupported_media_type", "Content-Type не совпадает с содержимым")
|
raise ApiError(415, "unsupported_media_type", "Content-Type не совпадает с содержимым")
|
||||||
try:
|
try:
|
||||||
with Image.open(io.BytesIO(data)) as img:
|
with Image.open(io.BytesIO(header)) as img:
|
||||||
width, height = img.size
|
width, height = img.size
|
||||||
|
except Image.DecompressionBombError:
|
||||||
|
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
||||||
except (UnidentifiedImageError, OSError):
|
except (UnidentifiedImageError, OSError):
|
||||||
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
|
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
|
||||||
if width <= 0 or height <= 0:
|
if width <= 0 or height <= 0:
|
||||||
@@ -85,28 +96,33 @@ def _validate_image(data: bytes, declared_mime: str) -> str:
|
|||||||
return actual
|
return actual
|
||||||
|
|
||||||
|
|
||||||
def read_upload(stream: BinaryIO, declared_mime: str) -> tuple[bytes, str, str]:
|
async def read_upload(stream, declared_mime: str) -> tuple[bytes, str, str]:
|
||||||
"""Читает поток с лимитом, возвращает (bytes, sha256, actual_mime).
|
"""Читает async-поток Starlette с лимитом.
|
||||||
|
|
||||||
Файл ≤10 MiB, поэтому держим его в памяти — это упрощает валидацию
|
Возвращает (bytes, sha256, actual_mime). Файл ≤10 MiB, поэтому держим
|
||||||
и не создаёт неограниченного потребления RAM (лимит жёсткий).
|
его в памяти — это упрощает валидацию и не создаёт неограниченного
|
||||||
|
потребления RAM (лимит жёсткий). Валидация заголовка выполняется по
|
||||||
|
первым 64 KiB до полного чтения тела.
|
||||||
"""
|
"""
|
||||||
limit = settings.max_upload_bytes
|
limit = settings.max_upload_bytes
|
||||||
buf = bytearray()
|
buf = bytearray()
|
||||||
hasher = hashlib.sha256()
|
hasher = hashlib.sha256()
|
||||||
while True:
|
async for chunk in stream:
|
||||||
chunk = stream.read(settings.upload_chunk_size)
|
|
||||||
if not chunk:
|
if not chunk:
|
||||||
break
|
continue
|
||||||
buf.extend(chunk)
|
buf.extend(chunk)
|
||||||
hasher.update(chunk)
|
hasher.update(chunk)
|
||||||
|
# Лимит размера приоритетнее валидации содержимого: контракт
|
||||||
|
# требует 413 при превышении bytes, даже если заголовок битый.
|
||||||
if len(buf) > limit:
|
if len(buf) > limit:
|
||||||
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
|
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
|
||||||
if not buf:
|
if not buf:
|
||||||
raise ApiError(400, "invalid_request", "Пустое тело запроса")
|
raise ApiError(400, "invalid_request", "Пустое тело запроса")
|
||||||
data = bytes(buf)
|
# Валидация заголовка — только после того, как убедились, что лимит
|
||||||
actual = _validate_image(data, declared_mime)
|
# не превышен. Иначе битый заголовок в oversized-файле дал бы 415
|
||||||
return data, hasher.hexdigest(), actual
|
# вместо 413, что нарушает приоритет кодов контракта.
|
||||||
|
actual = _validate_header(bytes(buf[:_HEADER_BYTES]), declared_mime)
|
||||||
|
return bytes(buf), hasher.hexdigest(), actual
|
||||||
|
|
||||||
|
|
||||||
def put_object(key: str, data: bytes, content_type: str) -> None:
|
def put_object(key: str, data: bytes, content_type: str) -> None:
|
||||||
|
|||||||
+16
-2
@@ -57,6 +57,16 @@ services:
|
|||||||
command: ["sh", "-c", "pip install --quiet boto3==1.35.76 && python /bootstrap_s3.py"]
|
command: ["sh", "-c", "pip install --quiet boto3==1.35.76 && python /bootstrap_s3.py"]
|
||||||
restart: "no"
|
restart: "no"
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql+psycopg://messenger:messenger@postgres:5432/messenger
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
command: ["alembic", "upgrade", "head"]
|
||||||
|
restart: "no"
|
||||||
|
|
||||||
api-1:
|
api-1:
|
||||||
build: .
|
build: .
|
||||||
environment:
|
environment:
|
||||||
@@ -80,7 +90,9 @@ services:
|
|||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
s3-init:
|
s3-init:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
command: ["sh", "-c", "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8080"]
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||||
|
|
||||||
api-2:
|
api-2:
|
||||||
build: .
|
build: .
|
||||||
@@ -105,7 +117,9 @@ services:
|
|||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
s3-init:
|
s3-init:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
command: ["sh", "-c", "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8080"]
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||||
|
|
||||||
lb:
|
lb:
|
||||||
image: nginx:1.27-alpine
|
image: nginx:1.27-alpine
|
||||||
|
|||||||
@@ -30,10 +30,12 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|||||||
FIXTURE = os.path.join(ROOT, "tests", "fixtures", "sample.png")
|
FIXTURE = os.path.join(ROOT, "tests", "fixtures", "sample.png")
|
||||||
|
|
||||||
|
|
||||||
def request(method, path, body=None, token=None, raw=None, content_type=None):
|
def request(method, path, body=None, token=None, raw=None, content_type=None, extra_headers=None):
|
||||||
headers = {"Accept": "application/json"}
|
headers = {"Accept": "application/json"}
|
||||||
if token:
|
if token:
|
||||||
headers["Authorization"] = "Bearer " + token
|
headers["Authorization"] = "Bearer " + token
|
||||||
|
if extra_headers:
|
||||||
|
headers.update(extra_headers)
|
||||||
data = None
|
data = None
|
||||||
if raw is not None:
|
if raw is not None:
|
||||||
data = raw
|
data = raw
|
||||||
@@ -69,7 +71,6 @@ def make_user(label):
|
|||||||
)
|
)
|
||||||
assert status == 201, (status, user)
|
assert status == 201, (status, user)
|
||||||
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
||||||
status, session, _ = request("POST", "/api/v1/auth/sessions", raw=b"", content_type=None) if False else (None, None, None)
|
|
||||||
# Basic-вход: используем заголовок Authorization напрямую.
|
# Basic-вход: используем заголовок Authorization напрямую.
|
||||||
req = urllib.request.Request(
|
req = urllib.request.Request(
|
||||||
BASE_URL + "/api/v1/auth/sessions",
|
BASE_URL + "/api/v1/auth/sessions",
|
||||||
@@ -167,6 +168,7 @@ class AttachmentTests(unittest.TestCase):
|
|||||||
"/api/v1/chats/" + self.chat["id"] + "/messages",
|
"/api/v1/chats/" + self.chat["id"] + "/messages",
|
||||||
{"text": "", "attachment_ids": [att["id"]]},
|
{"text": "", "attachment_ids": [att["id"]]},
|
||||||
token=self.alice["token"],
|
token=self.alice["token"],
|
||||||
|
extra_headers={"Idempotency-Key": "other-chat-" + uuid.uuid4().hex},
|
||||||
)
|
)
|
||||||
self.assertEqual(status, 404)
|
self.assertEqual(status, 404)
|
||||||
self.assertEqual(body["error"]["code"], "not_found")
|
self.assertEqual(body["error"]["code"], "not_found")
|
||||||
@@ -179,6 +181,7 @@ class AttachmentTests(unittest.TestCase):
|
|||||||
"/api/v1/chats/" + self.chat["id"] + "/messages",
|
"/api/v1/chats/" + self.chat["id"] + "/messages",
|
||||||
{"text": "", "attachment_ids": [att["id"]]},
|
{"text": "", "attachment_ids": [att["id"]]},
|
||||||
token=self.alice["token"],
|
token=self.alice["token"],
|
||||||
|
extra_headers={"Idempotency-Key": "msg-att-" + uuid.uuid4().hex},
|
||||||
)
|
)
|
||||||
self.assertEqual(status, 201, msg)
|
self.assertEqual(status, 201, msg)
|
||||||
self.assertEqual(msg["attachment_ids"], [att["id"]])
|
self.assertEqual(msg["attachment_ids"], [att["id"]])
|
||||||
|
|||||||
Reference in New Issue
Block a user