feat: implement S3 attachments and presigned uploads

This commit is contained in:
sinveria
2026-11-10 12:08:50 +03:00
parent aaa834e412
commit d96d4a2836
50 changed files with 3138 additions and 72 deletions
+422
View File
@@ -0,0 +1,422 @@
import hashlib
import tempfile
import uuid
from datetime import datetime, timezone, timedelta
from urllib.parse import quote
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, Response
from fastapi.responses import StreamingResponse
from sqlalchemy import select
from sqlalchemy.orm import Session
from botocore.exceptions import BotoCoreError, ClientError
from app.api.deps import get_db, get_current_user
from app.core.config import settings
from app.models import CreateAttachmentUpload
from app.db.models import Attachment, AttachmentUpload, User
from app.services.object_storage import client, create_presigned_upload_url
from app.services.image_validation import MAX_BYTES, validate_image_file
from app.repositories.chat_repository import ChatRepository
router = APIRouter(prefix="/api/v1", tags=["Attachments"])
def iso_utc(value):
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def attachment_json(item):
return {
"id": str(item.id), "chat_id": str(item.chat_id), "owner_id": str(item.owner_id),
"filename": item.filename, "content_type": item.content_type,
"size_bytes": item.size_bytes, "sha256": item.sha256, "status": item.status,
"variants": [], "error_code": item.error_code,
"created_at": iso_utc(item.created_at), "updated_at": iso_utc(item.updated_at),
}
def member_attachment(db, attachment_id, user_id):
item = db.get(Attachment, attachment_id)
if item is None or not ChatRepository(db).is_member(item.chat_id, user_id):
raise HTTPException(404, "Attachment not found")
return item
async def read_limited(request: Request):
declared = request.headers.get("content-length")
if declared and declared.isdigit() and int(declared) > MAX_BYTES:
raise HTTPException(413, "Image exceeds 10 MiB")
size = 0
# Keep at most 1 MiB in RAM; larger bodies spill to a temporary file.
spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b")
try:
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BYTES:
raise HTTPException(413, "Image exceeds 10 MiB")
spool.write(chunk)
spool.seek(0)
return spool, size
except Exception:
spool.close()
raise
def sha256_file(fileobj):
digest = hashlib.sha256()
fileobj.seek(0)
while True:
chunk = fileobj.read(1024 * 1024)
if not chunk: break
digest.update(chunk)
fileobj.seek(0)
return digest.hexdigest()
@router.post("/chats/{chat_id}/attachments/presigned", status_code=201)
def create_attachment_upload(
chat_id: str,
payload: CreateAttachmentUpload,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
raise HTTPException(400, "Invalid chat UUID") from None
if not ChatRepository(db).is_member(chat_uuid, user.id):
raise HTTPException(404, "Chat not found")
if payload.size_bytes > settings.max_upload_bytes:
raise HTTPException(413, "Image exceeds configured upload limit")
upload_id = uuid.uuid4()
object_key = f"uploads/{chat_uuid}/{upload_id}"
expires_at = datetime.now(timezone.utc) + timedelta(
seconds=settings.presigned_upload_ttl_seconds
)
try:
upload_url = create_presigned_upload_url(
object_key=object_key,
content_type=payload.content_type,
)
except (BotoCoreError, ClientError):
raise HTTPException(503, "Object storage unavailable") from None
upload = AttachmentUpload(
id=upload_id,
chat_id=chat_uuid,
owner_id=user.id,
filename=payload.filename,
content_type=payload.content_type,
expected_size_bytes=payload.size_bytes,
expected_sha256=payload.sha256.lower(),
object_key=object_key,
status="pending",
expires_at=expires_at,
)
try:
db.add(upload)
db.commit()
except Exception:
db.rollback()
raise HTTPException(503, "Could not save upload metadata") from None
return {
"upload_id": str(upload_id),
"upload_url": upload_url,
"method": "PUT",
"headers": {
"Content-Type": payload.content_type,
},
"expires_in": settings.presigned_upload_ttl_seconds,
"expires_at": iso_utc(expires_at),
}
@router.post("/attachments/uploads/{upload_id}/complete", status_code=200)
def complete_attachment_upload(
upload_id: str,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
try:
parsed_id = uuid.UUID(upload_id)
except ValueError:
raise HTTPException(400, "Invalid upload UUID") from None
# Lock the upload row to prevent concurrent completion.
upload = db.scalar(
select(AttachmentUpload)
.where(AttachmentUpload.id == parsed_id)
.with_for_update()
)
if upload is None:
raise HTTPException(404, "Upload not found")
if (
upload.owner_id != user.id
or not ChatRepository(db).is_member(upload.chat_id, user.id)
):
raise HTTPException(404, "Upload not found")
# Idempotent completion: return the existing attachment.
if upload.status == "completed":
item = db.scalar(
select(Attachment).where(
Attachment.object_key == upload.object_key
)
)
if item is None:
raise HTTPException(409, "Completed attachment not found")
return attachment_json(item)
if upload.status != "pending":
raise HTTPException(409, "Upload is not pending")
now = datetime.now(timezone.utc)
if upload.expires_at <= now:
upload.status = "expired"
db.commit()
try:
client().delete_object(
Bucket=settings.s3_bucket,
Key=upload.object_key,
)
except Exception:
pass
raise HTTPException(409, "Upload has expired")
s3 = client()
# Read the object from S3.
try:
result = s3.get_object(
Bucket=settings.s3_bucket,
Key=upload.object_key,
)
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code in {"NoSuchKey", "404", "NotFound"}:
raise HTTPException(409, "Uploaded object not found") from None
raise HTTPException(503, "Object storage unavailable") from None
except BotoCoreError:
raise HTTPException(503, "Object storage unavailable") from None
body = result["Body"]
spool = tempfile.SpooledTemporaryFile(
max_size=1024 * 1024,
mode="w+b",
)
def reject_upload(status_code: int, detail: str):
upload.status = "failed"
db.commit()
try:
s3.delete_object(
Bucket=settings.s3_bucket,
Key=upload.object_key,
)
except Exception:
pass
raise HTTPException(status_code=status_code, detail=detail)
try:
actual_size = result.get("ContentLength")
if actual_size != upload.expected_size_bytes:
reject_upload(409, "Uploaded file size mismatch")
if actual_size > settings.max_upload_bytes:
reject_upload(413, "Image exceeds configured upload limit")
total = 0
digest = hashlib.sha256()
try:
while True:
chunk = body.read(64 * 1024)
if not chunk:
break
total += len(chunk)
if total > settings.max_upload_bytes:
reject_upload(413, "Image exceeds configured upload limit")
if total > upload.expected_size_bytes:
reject_upload(409, "Uploaded file size mismatch")
digest.update(chunk)
spool.write(chunk)
finally:
body.close()
if total != upload.expected_size_bytes:
reject_upload(409, "Uploaded file size mismatch")
if digest.hexdigest() != upload.expected_sha256:
reject_upload(409, "Uploaded file checksum mismatch")
# Validate the actual image content, not only S3 metadata.
try:
actual_type, _, _ = validate_image_file(
spool,
upload.content_type,
)
except HTTPException as exc:
reject_upload(exc.status_code, str(exc.detail))
attachment = Attachment(
id=uuid.uuid4(),
chat_id=upload.chat_id,
owner_id=upload.owner_id,
filename=upload.filename,
content_type=actual_type,
size_bytes=total,
sha256=digest.hexdigest(),
object_key=upload.object_key,
status="ready",
error_code=None,
)
upload.status = "completed"
upload.completed_at = now
db.add(attachment)
db.commit()
db.refresh(attachment)
return attachment_json(attachment)
except HTTPException:
raise
except (BotoCoreError, ClientError):
db.rollback()
raise HTTPException(503, "Object storage unavailable") from None
except Exception:
db.rollback()
raise
finally:
spool.close()
@router.post("/chats/{chat_id}/attachments", status_code=201)
async def upload_attachment(
chat_id: str, request: Request, filename: str = Query(..., min_length=1, max_length=255),
db: Session = Depends(get_db), user: User = Depends(get_current_user),
):
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
raise HTTPException(400, "Invalid chat UUID") from None
if not ChatRepository(db).is_member(chat_uuid, user.id):
raise HTTPException(404, "Chat not found")
if not filename.strip() or any(c in filename for c in ("/", "\\", "\x00")) or any(ord(c) < 32 or ord(c) == 127 for c in filename):
raise HTTPException(400, "Unsafe filename")
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if content_type not in {"image/png", "image/jpeg"}:
raise HTTPException(415, "Only PNG and JPEG are supported")
spool, size = await read_limited(request)
try:
actual_type, _, _ = validate_image_file(spool, content_type)
digest = sha256_file(spool)
attachment_id = uuid.uuid4()
object_key = f"original/{chat_uuid}/{attachment_id}"
s3 = client()
try:
s3.put_object(Bucket=settings.s3_bucket, Key=object_key, Body=spool, ContentType=actual_type)
except (BotoCoreError, ClientError):
raise HTTPException(503, "Object storage unavailable") from None
item = Attachment(
id=attachment_id, chat_id=chat_uuid, owner_id=user.id, filename=filename,
content_type=actual_type, size_bytes=size, sha256=digest,
object_key=object_key, status="ready", error_code=None,
)
try:
db.add(item)
db.commit()
db.refresh(item)
except Exception:
db.rollback()
try: s3.delete_object(Bucket=settings.s3_bucket, Key=object_key)
except Exception: pass
raise HTTPException(503, "Could not save attachment metadata") from None
return attachment_json(item)
finally:
spool.close()
@router.get("/attachments/{attachment_id}")
def get_attachment(attachment_id: str, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
try: parsed = uuid.UUID(attachment_id)
except ValueError: raise HTTPException(400, "Invalid attachment UUID") from None
item = member_attachment(db, parsed, user.id)
if item.status != "ready":
raise HTTPException(409, "Attachment upload is not completed")
return attachment_json(item)
@router.get("/attachments/{attachment_id}/content")
def download_attachment(attachment_id: str, variant: str = "original", db: Session = Depends(get_db), user: User = Depends(get_current_user)):
if variant != "original":
raise HTTPException(404, "Variant not found")
try: parsed = uuid.UUID(attachment_id)
except ValueError: raise HTTPException(400, "Invalid attachment UUID") from None
item = member_attachment(db, parsed, user.id)
if item.status != "ready":
raise HTTPException(409, "Attachment is not ready")
spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b")
try:
result = client().get_object(Bucket=settings.s3_bucket, Key=item.object_key)
body = result["Body"]
total = 0
digest = hashlib.sha256()
try:
while True:
chunk = body.read(64 * 1024)
if not chunk:
break
total += len(chunk)
if total > MAX_BYTES:
raise HTTPException(503, "Stored object exceeds configured limit")
digest.update(chunk)
spool.write(chunk)
finally:
body.close()
if total != item.size_bytes or digest.hexdigest() != item.sha256:
raise HTTPException(503, "Stored object checksum mismatch")
spool.seek(0)
except (BotoCoreError, ClientError):
spool.close()
raise HTTPException(503, "Object storage unavailable") from None
except Exception:
spool.close()
raise
def stream_verified_file():
try:
while True:
chunk = spool.read(64 * 1024)
if not chunk:
break
yield chunk
finally:
spool.close()
return StreamingResponse(
stream_verified_file(),
media_type=item.content_type,
headers={"Content-Disposition": f"inline; filename*=UTF-8''{quote(item.filename)}"},
)
+2 -2
View File
@@ -20,7 +20,7 @@ def message_to_response(message) -> MessageResponse:
return MessageResponse(
id=str(message.id), chat_id=str(message.chat_id),
sender_id=str(message.sender_id), text=message.text,
created_at=message.created_at,
created_at=message.created_at, attachment_ids=message.attachment_ids or [],
)
@@ -44,7 +44,7 @@ def create_message(
try:
message = MessageService(db).create_message(
chat_id=parsed_id, sender_id=user.id, text=body.text,
idempotency_key=idempotency_key,
idempotency_key=idempotency_key, attachment_ids=body.attachment_ids,
)
return message_to_response(message)
except MessageNotFoundError:
+25
View File
@@ -1,4 +1,5 @@
import os
from pydantic import AliasChoices, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -15,6 +16,30 @@ class Settings(BaseSettings):
idempotency_ttl_seconds: int = 86400
instance_id: str = os.getenv("INSTANCE_ID") or os.getenv("HOSTNAME") or "api-local"
shutdown_grace_seconds: int = 20
s3_endpoint_url: str = Field(
default="http://minio:9000",
validation_alias=AliasChoices("S3_ENDPOINT_URL", "S3_ENDPOINT"),
)
s3_public_endpoint_url: str = Field(
default="http://localhost:9000",
validation_alias=AliasChoices("S3_PUBLIC_ENDPOINT_URL"),
)
presigned_upload_ttl_seconds: int = 300
attachment_cleanup_interval_seconds: int = Field(default=60, ge=5, le=3600)
attachment_cleanup_grace_seconds: int = Field(default=600, ge=0, le=86400)
attachment_cleanup_batch_size: int = Field(default=100, ge=1, le=1000)
s3_region: str = Field(default="us-east-1", validation_alias=AliasChoices("S3_REGION"))
s3_bucket: str = Field(default="messenger-attachments", validation_alias=AliasChoices("S3_BUCKET"))
s3_access_key: str = Field(
default="messenger-api",
validation_alias=AliasChoices("S3_ACCESS_KEY", "S3_ACCESS_KEY_ID"),
)
s3_secret_key: str = Field(
default="change-me-api-secret",
validation_alias=AliasChoices("S3_SECRET_KEY", "S3_SECRET_ACCESS_KEY"),
)
max_upload_bytes: int = 10 * 1024 * 1024
max_image_pixels: int = 40_000_000
model_config = SettingsConfigDict(
env_file=".env", env_file_encoding="utf-8", extra="ignore"
+83
View File
@@ -4,6 +4,7 @@ from datetime import datetime, timezone
from sqlalchemy import (
DateTime,
JSON,
ForeignKey,
Index,
String,
@@ -129,6 +130,7 @@ class Message(Base):
Text,
nullable=False,
)
attachment_ids: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=utc_now,
@@ -213,3 +215,84 @@ class IdempotencyRecord(Base):
),
Index("ix_idempotency_records_expires_at", "expires_at"),
)
class Attachment(Base):
__tablename__ = "attachments"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False, index=True)
owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[str] = mapped_column(String(32), nullable=False)
size_bytes: Mapped[int] = mapped_column(nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
object_key: Mapped[str] = mapped_column(String(512), unique=True, nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="ready")
error_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
class AttachmentUpload(Base):
__tablename__ = "attachment_uploads"
id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
primary_key=True,
default=uuid.uuid4,
)
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", ondelete="CASCADE"),
nullable=False,
)
filename: Mapped[str] = mapped_column(
String(255),
nullable=False,
)
content_type: Mapped[str] = mapped_column(
String(32),
nullable=False,
)
expected_size_bytes: Mapped[int] = mapped_column(
nullable=False,
)
expected_sha256: Mapped[str] = mapped_column(
String(64),
nullable=False,
)
object_key: Mapped[str] = mapped_column(
String(512),
unique=True,
nullable=False,
)
status: Mapped[str] = mapped_column(
String(16),
nullable=False,
default="pending",
)
expires_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=utc_now,
nullable=False,
)
completed_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True),
nullable=True,
)
__table_args__ = (
Index("ix_attachment_uploads_chat_id", "chat_id"),
Index("ix_attachment_uploads_owner_id", "owner_id"),
Index("ix_attachment_uploads_expires_at", "expires_at"),
)
+25 -5
View File
@@ -1,6 +1,7 @@
import asyncio
import logging
import uuid
from contextlib import asynccontextmanager
from contextlib import asynccontextmanager, suppress
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
@@ -13,25 +14,43 @@ from app.api.auth import router as auth_router
from app.api.users import router as users_router
from app.api.chats import router as chats_router
from app.api.messages import router as messages_router
from app.api.attachments import router as attachments_router
from app.core.config import settings
from app.db.session import engine
from app.services.object_storage import client as s3_client
from app.services.attachment_cleanup import cleanup_expired_uploads
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
logger = logging.getLogger(__name__)
async def attachment_cleanup_loop():
while True:
try:
# Synchronous boto3/SQLAlchemy I/O must not block the event loop.
await asyncio.to_thread(cleanup_expired_uploads)
except Exception:
logger.exception("Attachment cleanup worker iteration failed")
await asyncio.sleep(settings.attachment_cleanup_interval_seconds)
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Application startup instance_id=%s", settings.instance_id)
cleanup_task = asyncio.create_task(attachment_cleanup_loop())
try:
yield
finally:
cleanup_task.cancel()
with suppress(asyncio.CancelledError):
await cleanup_task
engine.dispose()
logger.info("Application shutdown instance_id=%s", settings.instance_id)
app = FastAPI(title=settings.app_name, version="1.3.0", lifespan=lifespan)
app = FastAPI(title=settings.app_name, version="1.4.0", lifespan=lifespan)
app.include_router(users_router)
app.include_router(auth_router)
app.include_router(chats_router)
app.include_router(messages_router)
app.include_router(attachments_router)
@app.middleware("http")
async def response_headers(request: Request, call_next):
@@ -77,10 +96,11 @@ def readiness():
try:
with engine.connect() as connection:
connection.execute(text("SELECT 1"))
s3_client().head_bucket(Bucket=settings.s3_bucket)
return {"status": "ok"}
except SQLAlchemyError:
logger.exception("PostgreSQL readiness check failed")
except Exception:
logger.exception("PostgreSQL or S3 readiness check failed")
raise HTTPException(
status_code=503,
detail="Database unavailable",
detail="Required storage unavailable",
) from None
+32 -4
View File
@@ -1,6 +1,6 @@
from datetime import datetime, timezone
from typing import List, Optional
from typing import List, Optional, Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator
@@ -67,14 +67,20 @@ class Chat(BaseConfig):
class CreateMessage(BaseConfig):
text: str = Field(..., min_length=1, max_length=4000)
text: str = Field(..., max_length=4000)
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
@field_validator("attachment_ids")
@classmethod
def validate_attachment_ids(cls, value):
if len(value) != len(set(value)):
raise ValueError("attachment_ids must be unique")
return value
@field_validator("text")
@classmethod
def validate_text(cls, value: str) -> str:
value = value.strip()
if not value:
raise ValueError("text must not be blank")
return value
@@ -84,6 +90,7 @@ class Message(BaseConfig):
sender_id: str
text: str
created_at: datetime
attachment_ids: List[str] = Field(default_factory=list)
class Health(BaseConfig):
@@ -108,3 +115,24 @@ class ChatPage(BaseConfig):
class MessagePage(BaseConfig):
items: List[Message]
next_cursor: Optional[str] = None
class CreateAttachmentUpload(BaseConfig):
filename: str = Field(..., min_length=1, max_length=255)
content_type: Literal["image/png", "image/jpeg"]
size_bytes: int = Field(..., gt=0, le=10 * 1024 * 1024)
sha256: str = Field(..., pattern=r"^[a-fA-F0-9]{64}$")
@field_validator("filename")
@classmethod
def validate_filename(cls, value: str) -> str:
value = value.strip()
if (
not value
or any(c in value for c in ("/", "\\", "\x00"))
or any(ord(c) < 32 or ord(c) == 127 for c in value)
):
raise ValueError("Unsafe filename")
return value
+2
View File
@@ -28,11 +28,13 @@ class MessageRepository:
chat_id: uuid.UUID,
sender_id: uuid.UUID,
text: str,
attachment_ids: list[str] | None = None,
) -> Message:
message = Message(
chat_id=chat_id,
sender_id=sender_id,
text=text,
attachment_ids=attachment_ids or [],
)
self.db.add(message)
+66
View File
@@ -0,0 +1,66 @@
"""Best-effort cleanup for abandoned presigned uploads."""
import logging
from datetime import datetime, timedelta, timezone
from sqlalchemy import select
from app.core.config import settings
from app.db.models import AttachmentUpload
from app.db.session import SessionLocal
from app.services.object_storage import client
logger = logging.getLogger(__name__)
def cleanup_expired_uploads() -> int:
"""Delete old pending objects and mark their upload records expired.
A grace period protects clients completing an upload near URL expiry.
PostgreSQL SKIP LOCKED makes this safe across multiple API replicas.
"""
cutoff = datetime.now(timezone.utc) - timedelta(
seconds=settings.attachment_cleanup_grace_seconds
)
deleted_count = 0
with SessionLocal() as db:
uploads = db.scalars(
select(AttachmentUpload)
.where(
AttachmentUpload.status == "pending",
AttachmentUpload.expires_at <= cutoff,
)
.order_by(AttachmentUpload.expires_at.asc())
.limit(settings.attachment_cleanup_batch_size)
.with_for_update(skip_locked=True)
).all()
if not uploads:
return 0
s3 = client()
try:
for upload in uploads:
# DeleteObject is idempotent: a missing object is also safe.
s3.delete_object(
Bucket=settings.s3_bucket,
Key=upload.object_key,
)
upload.status = "expired"
deleted_count += 1
db.commit()
except Exception:
db.rollback()
logger.exception(
"Attachment cleanup batch failed; pending records will be retried"
)
return 0
if deleted_count:
logger.info(
"Expired abandoned attachment uploads cleaned: count=%d",
deleted_count,
)
return deleted_count
+41
View File
@@ -0,0 +1,41 @@
from io import BytesIO
from PIL import Image, UnidentifiedImageError
from fastapi import HTTPException
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
ALLOWED = {"PNG": "image/png", "JPEG": "image/jpeg"}
def validate_image_file(fileobj, declared_type: str):
"""Validate a seekable, size-limited file without loading its full encoded bytes."""
try:
fileobj.seek(0)
with Image.open(fileobj) as image:
fmt = image.format
width, height = image.size
if fmt not in ALLOWED:
raise HTTPException(415, "Only PNG and JPEG are supported")
if width * height > MAX_PIXELS:
raise HTTPException(413, "Image exceeds 40 million pixels")
image.verify()
fileobj.seek(0)
with Image.open(fileobj) as image:
image.load()
except HTTPException:
raise
except (UnidentifiedImageError, OSError, ValueError, SyntaxError, Image.DecompressionBombError):
raise HTTPException(415, "Invalid or corrupted image") from None
actual_type = ALLOWED[fmt]
if declared_type != actual_type:
raise HTTPException(415, "Content-Type does not match image content")
fileobj.seek(0)
return actual_type, width, height
def validate_image(data: bytes, declared_type: str):
if not data:
raise HTTPException(415, "Empty image")
if len(data) > MAX_BYTES:
raise HTTPException(413, "Image exceeds 10 MiB")
return validate_image_file(BytesIO(data), declared_type)
+22 -5
View File
@@ -15,7 +15,7 @@ from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.orm import Session
from app.core.config import settings
from app.db.models import IdempotencyRecord, Message
from app.db.models import Attachment, IdempotencyRecord, Message
from app.repositories.chat_repository import ChatRepository
from app.repositories.message_repository import MessageRepository
@@ -137,6 +137,7 @@ class MessageService:
"chat_id": str(message.chat_id),
"sender_id": str(message.sender_id),
"text": message.text,
"attachment_ids": message.attachment_ids or [],
"created_at": message.created_at.isoformat(),
}
for message in messages
@@ -154,6 +155,7 @@ class MessageService:
chat_id=uuid.UUID(item["chat_id"]),
sender_id=uuid.UUID(item["sender_id"]),
text=item["text"],
attachment_ids=item.get("attachment_ids", []),
created_at=datetime.fromisoformat(item["created_at"]),
)
for item in data["items"]
@@ -210,19 +212,34 @@ class MessageService:
sender_id: uuid.UUID,
text: str,
idempotency_key: str,
attachment_ids: list[str] | None = None,
) -> Message:
text = text.strip()
if not text or len(text) > 4000:
attachment_ids = attachment_ids or []
if (not text and not attachment_ids) or len(text) > 4000 or len(attachment_ids) > 10:
raise InvalidMessageDataError("Invalid message text")
# Access is checked for every retry, before consulting the key.
if not self.chats.is_member(chat_id, sender_id):
raise MessageNotFoundError()
if len(attachment_ids) != len(set(attachment_ids)):
raise InvalidMessageDataError("Duplicate attachment IDs")
if attachment_ids:
try:
parsed_attachment_ids = [uuid.UUID(value) for value in attachment_ids]
except (ValueError, TypeError):
raise InvalidMessageDataError("Invalid attachment UUID") from None
attachments = list(self.db.scalars(select(Attachment).where(Attachment.id.in_(parsed_attachment_ids))).all())
if len(attachments) != len(parsed_attachment_ids) or any(a.chat_id != chat_id for a in attachments):
raise MessageNotFoundError()
if any(a.status != "ready" for a in attachments):
raise InvalidMessageDataError("Attachment is not ready")
method = "POST"
path = f"/api/v1/chats/{chat_id}/messages"
request_hash = hashlib.sha256(
json.dumps({"text": text}, sort_keys=True, separators=(",", ":")).encode("utf-8")
json.dumps({"text": text, "attachment_ids": attachment_ids}, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
now = datetime.now(timezone.utc)
expires_at = now + timedelta(seconds=max(settings.idempotency_ttl_seconds, 86400))
@@ -258,7 +275,7 @@ class MessageService:
if existing is None:
# Rare expiration race: retry once in a fresh transaction.
self.db.rollback()
return self.create_message(chat_id, sender_id, text, idempotency_key)
return self.create_message(chat_id, sender_id, text, idempotency_key, attachment_ids)
if existing.request_hash != request_hash:
self.db.rollback()
raise IdempotencyConflictError()
@@ -271,7 +288,7 @@ class MessageService:
return message
message = self.messages.create(
chat_id=chat_id, sender_id=sender_id, text=text
chat_id=chat_id, sender_id=sender_id, text=text, attachment_ids=attachment_ids
)
self.db.execute(
update(IdempotencyRecord)
+39
View File
@@ -0,0 +1,39 @@
import boto3
from botocore.config import Config
from app.core.config import settings
def client(endpoint_url=None):
return boto3.client(
"s3", endpoint_url=endpoint_url or settings.s3_endpoint_url,
aws_access_key_id=settings.s3_access_key,
aws_secret_access_key=settings.s3_secret_key,
region_name=settings.s3_region,
config=Config(signature_version="s3v4", connect_timeout=3, read_timeout=15, retries={"max_attempts": 2}, s3={"addressing_style": "path"}),
)
def ensure_bucket() -> None:
s3 = client()
try:
s3.head_bucket(Bucket=settings.s3_bucket)
except Exception:
s3.create_bucket(Bucket=settings.s3_bucket)
def presigned_client():
return client(endpoint_url=settings.s3_public_endpoint_url)
def create_presigned_upload_url(object_key: str, content_type: str) -> str:
s3 = presigned_client()
return s3.generate_presigned_url(
ClientMethod="put_object",
Params={
"Bucket": settings.s3_bucket,
"Key": object_key,
"ContentType": content_type,
},
ExpiresIn=settings.presigned_upload_ttl_seconds,
)