109 lines
3.5 KiB
Python
109 lines
3.5 KiB
Python
"""Validate binary uploads and keep original data in a private S3 bucket."""
|
|
|
|
import hashlib
|
|
import os
|
|
import tempfile
|
|
import warnings
|
|
from contextlib import closing
|
|
|
|
import boto3
|
|
from botocore.config import Config
|
|
from botocore.exceptions import ClientError
|
|
from PIL import Image
|
|
|
|
from db import setting
|
|
|
|
MAX_UPLOAD = 10 * 1024 * 1024
|
|
MAX_PIXELS = 40_000_000
|
|
MEDIA_TYPES = {"PNG": "image/png", "JPEG": "image/jpeg"}
|
|
|
|
|
|
class BadImage(Exception):
|
|
pass
|
|
|
|
|
|
class PixelLimit(Exception):
|
|
pass
|
|
|
|
|
|
def verify_image(file, mime):
|
|
try:
|
|
with warnings.catch_warnings():
|
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
|
with Image.open(file) as image:
|
|
if image.width * image.height > MAX_PIXELS:
|
|
raise PixelLimit()
|
|
if MEDIA_TYPES.get(image.format) != mime:
|
|
raise BadImage()
|
|
if getattr(image, "n_frames", 1) != 1:
|
|
raise BadImage()
|
|
image.verify()
|
|
file.seek(0)
|
|
with Image.open(file) as image:
|
|
image.load()
|
|
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
|
raise PixelLimit() from None
|
|
except (OSError, SyntaxError, ValueError):
|
|
raise BadImage() from None
|
|
finally:
|
|
file.seek(0)
|
|
|
|
|
|
class Objects:
|
|
def __init__(self):
|
|
self.bucket = os.environ.get("S3_BUCKET", "attachments")
|
|
self.client = boto3.client(
|
|
"s3", endpoint_url=os.environ.get("S3_ENDPOINT", "http://s3:9000"),
|
|
aws_access_key_id=setting("S3_ACCESS_KEY"),
|
|
aws_secret_access_key=setting("S3_SECRET_KEY"),
|
|
region_name="us-east-1", verify=os.environ.get("S3_CA_FILE") or True,
|
|
config=Config(connect_timeout=2, read_timeout=4, retries={"total_max_attempts": 1},
|
|
max_pool_connections=16, s3={"addressing_style": "path"},
|
|
request_checksum_calculation="when_required",
|
|
response_checksum_validation="when_required"),
|
|
)
|
|
|
|
@staticmethod
|
|
def key(attachment_id, variant="original"):
|
|
return f"{variant}/{attachment_id}"
|
|
|
|
@staticmethod
|
|
def result_key(attachment_id, version, variant):
|
|
if version == 0:
|
|
return Objects.key(attachment_id, variant)
|
|
return f"results/v{version}/{variant}/{attachment_id}"
|
|
|
|
def ready(self):
|
|
self.client.head_bucket(Bucket=self.bucket)
|
|
|
|
def put(self, key, file, mime, length):
|
|
digest = hashlib.file_digest(file, "sha256").hexdigest()
|
|
file.seek(0)
|
|
self.client.put_object(Bucket=self.bucket, Key=key, Body=file,
|
|
ContentType=mime, ContentLength=length)
|
|
return digest
|
|
|
|
def get(self, key):
|
|
result = self.client.get_object(Bucket=self.bucket, Key=key)
|
|
with closing(result["Body"]) as body:
|
|
data = body.read(MAX_UPLOAD + 1)
|
|
if len(data) > MAX_UPLOAD:
|
|
raise ValueError("object exceeds configured limit")
|
|
return data
|
|
|
|
def has(self, key):
|
|
try:
|
|
self.client.head_object(Bucket=self.bucket, Key=key)
|
|
except ClientError as error:
|
|
if str(error.response["Error"]["Code"]) in ("404", "NotFound", "NoSuchKey"):
|
|
return False
|
|
raise
|
|
return True
|
|
|
|
def delete(self, key):
|
|
self.client.delete_object(Bucket=self.bucket, Key=key)
|
|
|
|
|
|
def spool():
|
|
return tempfile.SpooledTemporaryFile(max_size=512 * 1024, mode="w+b")
|