diff --git a/messenger/bootstrap_s3.py b/messenger/bootstrap_s3.py new file mode 100644 index 00000000..2289adae --- /dev/null +++ b/messenger/bootstrap_s3.py @@ -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() diff --git a/messenger/images.py b/messenger/images.py new file mode 100644 index 00000000..60f28e27 --- /dev/null +++ b/messenger/images.py @@ -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 diff --git a/messenger/storage.py b/messenger/storage.py new file mode 100644 index 00000000..db0bdc92 --- /dev/null +++ b/messenger/storage.py @@ -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. diff --git a/migrations/003_attachments.sql b/migrations/003_attachments.sql new file mode 100644 index 00000000..dd0fcbfb --- /dev/null +++ b/migrations/003_attachments.sql @@ -0,0 +1,27 @@ +-- Lab4: only metadata and references live in PostgreSQL; bytes live in private S3. +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + owner_id uuid NOT NULL REFERENCES users(id), + filename text NOT NULL CHECK(char_length(filename) BETWEEN 1 AND 255), + content_type text NOT NULL CHECK(content_type IN ('image/png','image/jpeg')), + size_bytes bigint NOT NULL CHECK(size_bytes BETWEEN 1 AND 10485760), + sha256 text NOT NULL CHECK(sha256 ~ '^[a-f0-9]{64}$'), + object_key text NOT NULL UNIQUE, + status text NOT NULL DEFAULT 'ready' CHECK(status='ready'), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY(chat_id,owner_id) REFERENCES chat_members(chat_id,user_id) +); +CREATE INDEX attachments_chat_idx ON attachments(chat_id,id); +ALTER TABLE messages ALTER COLUMN text DROP NOT NULL; +ALTER TABLE messages DROP CONSTRAINT messages_text_check; +ALTER TABLE messages ADD CONSTRAINT messages_text_check CHECK(char_length(text) BETWEEN 0 AND 4000); +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + attachment_id uuid NOT NULL REFERENCES attachments(id), + position integer NOT NULL CHECK(position BETWEEN 0 AND 9), + PRIMARY KEY(message_id, attachment_id), + UNIQUE(message_id, position) +); +ALTER TABLE message_requests ADD COLUMN request_attachments jsonb NOT NULL DEFAULT '[]'::jsonb;