forked from mtusi2026/mtusi2026lab5
75 lines
3.2 KiB
Python
75 lines
3.2 KiB
Python
"""Bounded S3 calls and strict PNG/JPEG validation; never trust a client filename."""
|
|
import hashlib
|
|
import os
|
|
import warnings
|
|
|
|
import boto3
|
|
from botocore.config import Config
|
|
from PIL import Image, UnidentifiedImageError
|
|
|
|
from .common import ApiError
|
|
|
|
MAX_BYTES = 10 * 1024 * 1024
|
|
MAX_PIXELS = 40_000_000
|
|
HEALTH_KEY = 'originals/.storage-health'
|
|
HEALTH_BYTES = b'messenger-storage-ready-v1'
|
|
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
|
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
|
|
|
|
|
def validate_image(file, content_type):
|
|
try:
|
|
file.seek(0)
|
|
with Image.open(file, formats=['PNG', 'JPEG']) as image:
|
|
actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}[image.format]
|
|
if actual != content_type:
|
|
raise ApiError(415, 'unsupported_media_type', 'Image content does not match MIME')
|
|
if image.width * image.height > MAX_PIXELS:
|
|
raise ApiError(413, 'payload_too_large', 'Too many decoded pixels')
|
|
image.verify()
|
|
file.seek(0)
|
|
with Image.open(file, formats=['PNG', 'JPEG']) as image:
|
|
image.load() # JPEG.verify alone does not detect a truncated entropy stream.
|
|
file.seek(0)
|
|
digest = hashlib.file_digest(file, 'sha256').hexdigest()
|
|
file.seek(0)
|
|
return digest
|
|
except (Image.DecompressionBombWarning, Image.DecompressionBombError):
|
|
raise ApiError(413, 'payload_too_large', 'Too many decoded pixels') from None
|
|
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
|
raise ApiError(415, 'unsupported_media_type', 'Invalid PNG/JPEG') from None
|
|
|
|
|
|
class Storage:
|
|
def __init__(self):
|
|
self.bucket = os.environ['S3_BUCKET']
|
|
self.client = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'],
|
|
aws_access_key_id=os.environ['S3_ACCESS_KEY'],
|
|
aws_secret_access_key=os.environ['S3_SECRET_KEY'],
|
|
region_name='us-east-1',
|
|
config=Config(connect_timeout=2, read_timeout=4,
|
|
retries={'total_max_attempts': 1},
|
|
max_pool_connections=8,
|
|
s3={'addressing_style': 'path'}))
|
|
|
|
def ready(self):
|
|
# Listing proves only filer metadata readiness. After a SeaweedFS restart,
|
|
# volume registration can lag; require a real read from a persisted volume.
|
|
obj = self.get(HEALTH_KEY)
|
|
try:
|
|
if obj['Body'].read(len(HEALTH_BYTES)+1) != HEALTH_BYTES:
|
|
raise ApiError(503, 'unavailable', 'Storage probe unavailable')
|
|
finally:
|
|
obj['Body'].close()
|
|
|
|
def put(self, key, file, size, content_type, digest):
|
|
file.seek(0)
|
|
self.client.put_object(Bucket=self.bucket, Key=key, Body=file, ContentLength=size,
|
|
ContentType=content_type, Metadata={'sha256': digest})
|
|
|
|
def get(self, key):
|
|
return self.client.get_object(Bucket=self.bucket, Key=key)
|
|
|
|
def delete(self, key):
|
|
self.client.delete_object(Bucket=self.bucket, Key=key)
|