forked from mtusi2026/mtusi2026lab4
Добавить приватные S3-вложения: валидация PNG/JPEG, загрузка и метаданные в БД
Байты хранятся в приватном bucket (случайный ключ, без публичного доступа), метаданные и связи — в PostgreSQL (миграция 003_attachments). Лимиты размера/пикселей проверяются до полной распаковки, идемпотентность учитывает состав вложений. bootstrap_s3 идемпотентно создаёт bucket.
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
"""Run after S3 readiness, repeatable. Default MinIO bucket is private."""
|
||||
import time
|
||||
from botocore.exceptions import ClientError, BotoCoreError
|
||||
from .config import Settings
|
||||
from .storage import ObjectStore
|
||||
|
||||
def main():
|
||||
storage = ObjectStore(Settings.from_env())
|
||||
for attempt in range(40):
|
||||
try:
|
||||
storage.s3.list_buckets()
|
||||
break
|
||||
except (ClientError, BotoCoreError, OSError):
|
||||
if attempt == 39:
|
||||
raise
|
||||
time.sleep(2)
|
||||
try:
|
||||
storage.s3.head_bucket(Bucket=storage.bucket)
|
||||
except ClientError as exc:
|
||||
if exc.response.get('ResponseMetadata', {}).get('HTTPStatusCode') not in (404,):
|
||||
raise
|
||||
storage.s3.create_bucket(Bucket=storage.bucket)
|
||||
# Public ACL/policy intentionally absent; MinIO bucket is private by default.
|
||||
print('Private S3 bucket exists')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Bounded image validation: magic+full decode, no trust in declared MIME."""
|
||||
import io
|
||||
from PIL import Image, ImageFile, UnidentifiedImageError
|
||||
from .domain import ApiError
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
|
||||
def validate_image(data, declared_type):
|
||||
if declared_type not in ('image/png', 'image/jpeg'):
|
||||
raise ApiError(415, 'unsupported_media_type', 'PNG or JPEG required')
|
||||
if len(data) > MAX_BYTES:
|
||||
raise ApiError(413, 'payload_too_large', 'Image exceeds 10 MiB')
|
||||
if not data:
|
||||
raise ApiError(415, 'unsupported_media_type', 'Empty image')
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as im:
|
||||
real_type = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(im.format)
|
||||
if real_type is None or real_type != declared_type:
|
||||
raise ApiError(415, 'unsupported_media_type', 'Image content type mismatch')
|
||||
if im.width * im.height > MAX_PIXELS:
|
||||
raise ApiError(413, 'payload_too_large', 'Image pixel limit exceeded')
|
||||
im.load() # reject malformed/truncated payload before PUT
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
raise ApiError(415, 'unsupported_media_type', 'Invalid image') from None
|
||||
except Image.DecompressionBombError:
|
||||
raise ApiError(413, 'payload_too_large', 'Image pixel limit exceeded') from None
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Private S3 object storage. No file bytes are stored on API disks."""
|
||||
from pathlib import Path
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from .domain import ApiError
|
||||
|
||||
class ObjectStore:
|
||||
def __init__(self, settings):
|
||||
self.bucket = settings.s3_bucket
|
||||
self.s3 = boto3.client('s3', endpoint_url=settings.s3_endpoint,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=Path(settings.s3_secret_file).read_text().strip(),
|
||||
region_name='us-east-1', config=Config(signature_version='s3v4',
|
||||
connect_timeout=3, read_timeout=10, retries={'max_attempts': 1}))
|
||||
|
||||
def ready(self):
|
||||
try:
|
||||
self.s3.head_bucket(Bucket=self.bucket)
|
||||
except (ClientError, BotoCoreError, OSError):
|
||||
raise ApiError(503, 'unavailable', 'Object storage unavailable') from None
|
||||
|
||||
def put(self, key, data, content_type):
|
||||
try:
|
||||
self.s3.put_object(Bucket=self.bucket, Key=key, Body=data, ContentType=content_type)
|
||||
except (ClientError, BotoCoreError, OSError):
|
||||
raise ApiError(503, 'unavailable', 'Object storage unavailable') from None
|
||||
|
||||
def get(self, key):
|
||||
try:
|
||||
return self.s3.get_object(Bucket=self.bucket, Key=key)['Body']
|
||||
except (ClientError, BotoCoreError, OSError):
|
||||
raise ApiError(503, 'unavailable', 'Object storage unavailable') from None
|
||||
|
||||
def delete(self, key):
|
||||
try:
|
||||
self.s3.delete_object(Bucket=self.bucket, Key=key)
|
||||
except (ClientError, BotoCoreError, OSError):
|
||||
pass # If compensation cannot reach S3, report it as an orphan limitation.
|
||||
Reference in New Issue
Block a user