forked from mtusi2026/mtusi2026lab4
Добавить прямую загрузку по короткой подписи.
Proxy endpoint сохранён. Complete сверяет владельца, размер и checksum, а сравнение трафика API на двух размерах лежит в evidence.
This commit is contained in:
@@ -178,6 +178,14 @@ async def sweep_orphans() -> int:
|
||||
continue
|
||||
await s3.delete_key(key)
|
||||
await conn.execute("DELETE FROM blob_writes WHERE object_key = $1", key)
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE direct_uploads
|
||||
SET status = 'aborted'
|
||||
WHERE object_key = $1 AND status = 'pending'
|
||||
""",
|
||||
key,
|
||||
)
|
||||
deleted += 1
|
||||
if deleted:
|
||||
logger.info("removed %s uncommitted objects past grace", deleted)
|
||||
|
||||
@@ -37,6 +37,8 @@ LB_DRAIN_SECONDS = float(_env("LB_DRAIN_SECONDS", "2"))
|
||||
# container uses its own hostname; stop-one.sh maps that value to one replica.
|
||||
INSTANCE_ID = _env("INSTANCE_ID", socket.gethostname())
|
||||
S3_ENDPOINT = _env("S3_ENDPOINT", "http://s3:9000")
|
||||
S3_PUBLIC_ENDPOINT = _env("S3_PUBLIC_ENDPOINT", "http://127.0.0.1:9000")
|
||||
PRESIGN_TTL_SECONDS = min(max(int(_env("PRESIGN_TTL_SECONDS", "60")), 15), 300)
|
||||
S3_REGION = _env("S3_REGION", "us-east-1")
|
||||
S3_BUCKET = _env("S3_BUCKET", "messenger-attachments")
|
||||
S3_ACCESS_KEY_ID = _file_or_env("S3_ACCESS_KEY_ID")
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
"""Presigned PUT that does not replace the proxy upload endpoint."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from app import config, db, images, s3
|
||||
from app.attachments import _compensate, _public
|
||||
from app.errors import AppError
|
||||
from app.store import format_ts
|
||||
|
||||
|
||||
def _aware(value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=timezone.utc)
|
||||
return value
|
||||
|
||||
|
||||
async def begin_upload(
|
||||
chat_id: str,
|
||||
owner_id: str,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
size_bytes: int,
|
||||
) -> dict:
|
||||
upload_id = uuid4()
|
||||
key = f"originals/{upload_id}"
|
||||
created = datetime.now(timezone.utc)
|
||||
expires_at = created + timedelta(seconds=config.PRESIGN_TTL_SECONDS)
|
||||
async with db.require().acquire() as conn:
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO blob_writes (object_key, committed, created_at)
|
||||
VALUES ($1, FALSE, $2)
|
||||
""",
|
||||
key,
|
||||
created,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO direct_uploads (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
object_key, status, expires_at, created_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 'pending', $8, $9)
|
||||
""",
|
||||
upload_id,
|
||||
UUID(chat_id),
|
||||
UUID(owner_id),
|
||||
filename,
|
||||
content_type,
|
||||
size_bytes,
|
||||
key,
|
||||
expires_at,
|
||||
created,
|
||||
)
|
||||
try:
|
||||
url = await asyncio.to_thread(s3.presign_put, key, content_type, size_bytes)
|
||||
except Exception:
|
||||
await _compensate(key)
|
||||
async with db.require().acquire() as conn:
|
||||
await conn.execute(
|
||||
"UPDATE direct_uploads SET status = 'aborted' WHERE id = $1 AND status = 'pending'",
|
||||
upload_id,
|
||||
)
|
||||
raise
|
||||
return {
|
||||
"upload_id": str(upload_id),
|
||||
"method": "PUT",
|
||||
"url": url,
|
||||
"headers": {"Content-Type": content_type},
|
||||
"expires_at": format_ts(expires_at),
|
||||
"size_bytes": size_bytes,
|
||||
}
|
||||
|
||||
|
||||
async def _abort_pending(upload_id: UUID, key: str) -> None:
|
||||
async with db.require().acquire() as conn:
|
||||
changed = await conn.fetchval(
|
||||
"""
|
||||
UPDATE direct_uploads
|
||||
SET status = 'aborted'
|
||||
WHERE id = $1 AND status = 'pending'
|
||||
RETURNING id
|
||||
""",
|
||||
upload_id,
|
||||
)
|
||||
if changed is not None:
|
||||
await _compensate(key)
|
||||
|
||||
|
||||
async def complete_upload(upload_id: str, owner_id: str, claimed_sha: str) -> dict:
|
||||
async with db.require().acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
object_key, status, expires_at
|
||||
FROM direct_uploads
|
||||
WHERE id = $1 AND owner_id = $2
|
||||
""",
|
||||
UUID(upload_id),
|
||||
UUID(owner_id),
|
||||
)
|
||||
if row is None:
|
||||
raise AppError(404, "upload not found")
|
||||
if row["status"] != "pending":
|
||||
raise AppError(409, "upload is already finished")
|
||||
if _aware(row["expires_at"]) <= datetime.now(timezone.utc):
|
||||
await _abort_pending(row["id"], row["object_key"])
|
||||
raise AppError(409, "upload signature expired")
|
||||
|
||||
actual_size = await s3.head_size(row["object_key"])
|
||||
if actual_size is None:
|
||||
raise AppError(409, "upload is incomplete")
|
||||
if actual_size != row["size_bytes"] or actual_size > config.MAX_UPLOAD_BYTES:
|
||||
await _abort_pending(row["id"], row["object_key"])
|
||||
raise AppError(400, "uploaded size does not match")
|
||||
|
||||
data = await s3.get_bytes(row["object_key"])
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
if len(data) != row["size_bytes"] or digest != claimed_sha:
|
||||
await _abort_pending(row["id"], row["object_key"])
|
||||
raise AppError(400, "checksum does not match")
|
||||
try:
|
||||
images.inspect_image(data, row["content_type"])
|
||||
except images.ImageRejected as exc:
|
||||
await _abort_pending(row["id"], row["object_key"])
|
||||
raise AppError(exc.status, exc.message) from None
|
||||
|
||||
created = datetime.now(timezone.utc)
|
||||
try:
|
||||
async with db.require().acquire() as conn:
|
||||
async with conn.transaction():
|
||||
locked = await conn.fetchrow(
|
||||
"""
|
||||
SELECT status, object_key
|
||||
FROM direct_uploads
|
||||
WHERE id = $1 AND owner_id = $2
|
||||
FOR UPDATE
|
||||
""",
|
||||
row["id"],
|
||||
UUID(owner_id),
|
||||
)
|
||||
if locked is None or locked["status"] != "pending":
|
||||
raise AppError(409, "upload is already finished")
|
||||
intent = await conn.fetchrow(
|
||||
"SELECT committed FROM blob_writes WHERE object_key = $1 FOR UPDATE",
|
||||
row["object_key"],
|
||||
)
|
||||
if intent is None or intent["committed"]:
|
||||
raise AppError(409, "upload is already finished")
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, object_key, status, error_code, created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'ready', NULL, $9, $9)
|
||||
""",
|
||||
row["id"],
|
||||
row["chat_id"],
|
||||
row["owner_id"],
|
||||
row["filename"],
|
||||
row["content_type"],
|
||||
len(data),
|
||||
digest,
|
||||
row["object_key"],
|
||||
created,
|
||||
)
|
||||
await conn.execute(
|
||||
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
|
||||
row["object_key"],
|
||||
)
|
||||
await conn.execute(
|
||||
"UPDATE direct_uploads SET status = 'completed' WHERE id = $1",
|
||||
row["id"],
|
||||
)
|
||||
except AppError:
|
||||
raise
|
||||
except Exception:
|
||||
raise AppError(503, "service unavailable") from None
|
||||
return _public(
|
||||
{
|
||||
"id": row["id"],
|
||||
"chat_id": row["chat_id"],
|
||||
"owner_id": row["owner_id"],
|
||||
"filename": row["filename"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": len(data),
|
||||
"sha256": digest,
|
||||
"status": "ready",
|
||||
"created_at": created,
|
||||
"updated_at": created,
|
||||
}
|
||||
)
|
||||
@@ -17,6 +17,8 @@ from app.docs import openapi_json, swagger_ui
|
||||
from app.errors import AppError, error_response, from_app_error
|
||||
from app.middleware import RequestContextMiddleware
|
||||
from app.routes import (
|
||||
begin_direct_upload,
|
||||
complete_direct_upload,
|
||||
create_chat,
|
||||
create_message,
|
||||
create_session,
|
||||
@@ -93,6 +95,8 @@ def build_app() -> Starlette:
|
||||
Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]),
|
||||
Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]),
|
||||
Route("/api/v1/chats/{chat_id}/attachments", upload_attachment, methods=["POST"]),
|
||||
Route("/api/v1/chats/{chat_id}/uploads", begin_direct_upload, methods=["POST"]),
|
||||
Route("/api/v1/uploads/{upload_id}/complete", complete_direct_upload, methods=["POST"]),
|
||||
Route("/api/v1/attachments/{attachment_id}", get_attachment, methods=["GET"]),
|
||||
Route("/api/v1/attachments/{attachment_id}/content", download_attachment, methods=["GET"]),
|
||||
Route("/api/v1/_lab/metrics", lab_metrics, methods=["GET"]),
|
||||
|
||||
+53
-1
@@ -1,10 +1,11 @@
|
||||
import base64
|
||||
import binascii
|
||||
import re
|
||||
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, Response
|
||||
|
||||
from app import attachments, cache, config, db, images, rediscli, s3, sessions, store
|
||||
from app import attachments, cache, config, db, direct, images, rediscli, s3, sessions, store
|
||||
from app.cursor_codec import decode_cursor, encode_cursor
|
||||
from app.errors import BASIC_CHALLENGE, BEARER_CHALLENGE, AppError, error_response
|
||||
from app.passwords import dummy_hash, hash_password, verify_password
|
||||
@@ -311,6 +312,57 @@ async def upload_attachment(request: Request) -> Response:
|
||||
return _json(created, rid, 201)
|
||||
|
||||
|
||||
async def begin_direct_upload(request: Request) -> Response:
|
||||
rid = request.state.request_id
|
||||
user = await _bearer_user(request)
|
||||
chat_id = request.path_params["chat_id"]
|
||||
if validate_uuid(chat_id):
|
||||
return error_response(400, "invalid chat id", rid)
|
||||
raw = await request.body()
|
||||
body, err = parse_json_body(raw)
|
||||
if err:
|
||||
return error_response(400, err, rid)
|
||||
assert body is not None
|
||||
if require_exact_keys(body, {"filename", "content_type", "size_bytes"}, {"filename", "content_type", "size_bytes"}):
|
||||
return error_response(400, "invalid upload payload", rid)
|
||||
if validate_filename(body["filename"]):
|
||||
return error_response(400, "invalid filename", rid)
|
||||
content_type = body["content_type"]
|
||||
if content_type not in ("image/png", "image/jpeg"):
|
||||
return error_response(415, "unsupported media type", rid)
|
||||
size = body["size_bytes"]
|
||||
if isinstance(size, bool) or not isinstance(size, int):
|
||||
return error_response(400, "invalid size", rid)
|
||||
if size > config.MAX_UPLOAD_BYTES:
|
||||
return error_response(413, "file exceeds upload limit", rid)
|
||||
if size < 1:
|
||||
return error_response(400, "invalid size", rid)
|
||||
if await store.load_chat_for_member(chat_id, user["id"]) is None:
|
||||
return error_response(404, "chat not found", rid)
|
||||
started = await direct.begin_upload(chat_id, user["id"], body["filename"], content_type, size)
|
||||
return _json(started, rid, 201)
|
||||
|
||||
|
||||
async def complete_direct_upload(request: Request) -> Response:
|
||||
rid = request.state.request_id
|
||||
user = await _bearer_user(request)
|
||||
upload_id = request.path_params["upload_id"]
|
||||
if validate_uuid(upload_id):
|
||||
return error_response(400, "invalid upload id", rid)
|
||||
raw = await request.body()
|
||||
body, err = parse_json_body(raw)
|
||||
if err:
|
||||
return error_response(400, err, rid)
|
||||
assert body is not None
|
||||
if require_exact_keys(body, {"sha256"}, {"sha256"}):
|
||||
return error_response(400, "invalid upload payload", rid)
|
||||
digest = body["sha256"]
|
||||
if not isinstance(digest, str) or re.fullmatch(r"[a-f0-9]{64}", digest) is None:
|
||||
return error_response(400, "invalid checksum", rid)
|
||||
created = await direct.complete_upload(upload_id, user["id"], digest)
|
||||
return _json(created, rid, 201)
|
||||
|
||||
|
||||
async def get_attachment(request: Request) -> Response:
|
||||
rid = request.state.request_id
|
||||
user = await _bearer_user(request)
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.errors import AppError
|
||||
|
||||
logger = logging.getLogger("messenger.s3")
|
||||
_client = None
|
||||
_signer = None
|
||||
|
||||
|
||||
def _client_or_create():
|
||||
@@ -38,6 +39,26 @@ def _client_or_create():
|
||||
return _client
|
||||
|
||||
|
||||
def _signer_or_create():
|
||||
"""Signs URLs for the host the browser/client can reach. It does not send traffic."""
|
||||
global _signer
|
||||
if _signer is None:
|
||||
if not config.S3_ACCESS_KEY_ID or not config.S3_SECRET_ACCESS_KEY:
|
||||
raise AppError(503, "service unavailable")
|
||||
_signer = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=config.S3_PUBLIC_ENDPOINT,
|
||||
aws_access_key_id=config.S3_ACCESS_KEY_ID,
|
||||
aws_secret_access_key=config.S3_SECRET_ACCESS_KEY,
|
||||
region_name=config.S3_REGION,
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
return _signer
|
||||
|
||||
|
||||
def _unavailable(exc: Exception) -> AppError:
|
||||
code = ""
|
||||
if isinstance(exc, ClientError):
|
||||
@@ -91,6 +112,39 @@ async def get_bytes(key: str) -> bytes:
|
||||
raise _unavailable(exc) from None
|
||||
|
||||
|
||||
def presign_put(key: str, content_type: str, size: int) -> str:
|
||||
return _signer_or_create().generate_presigned_url(
|
||||
"put_object",
|
||||
Params={
|
||||
"Bucket": config.S3_BUCKET,
|
||||
"Key": key,
|
||||
"ContentType": content_type,
|
||||
"ContentLength": size,
|
||||
},
|
||||
ExpiresIn=config.PRESIGN_TTL_SECONDS,
|
||||
HttpMethod="PUT",
|
||||
)
|
||||
|
||||
|
||||
async def head_size(key: str) -> int | None:
|
||||
def _head() -> int | None:
|
||||
try:
|
||||
response = _client_or_create().head_object(Bucket=config.S3_BUCKET, Key=key)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
if code in {"404", "NoSuchKey", "NotFound"}:
|
||||
return None
|
||||
raise
|
||||
return int(response["ContentLength"])
|
||||
|
||||
try:
|
||||
return await asyncio.to_thread(_head)
|
||||
except AppError:
|
||||
raise
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
raise _unavailable(exc) from None
|
||||
|
||||
|
||||
async def delete_key(key: str) -> None:
|
||||
def _delete() -> None:
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user