forked from mtusi2026/mtusi2026lab4
Реализовать ЛР4: S3-хранилище и вложения на оценку 3
Стенд: PostgreSQL 16 + две API-реплики за HAProxy + SeaweedFS S3 в приватном bucket. Метаданные вложений в PostgreSQL, байты в S3, object key назначает сервер. Лимиты 10 MiB и 40 млн пикселей, MIME по магическим байтам, проверка filename. Добавлены smoke/негативные тесты, хуки restart/stop-one, сценарий отказа S3 и отчёт с доказательствами.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Messenger API for laboratory 4."""
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Idempotent S3 bucket bootstrap using an administrative identity."""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config as BotoConfig
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
|
||||
def required(name):
|
||||
value = os.environ.get(name)
|
||||
if not value:
|
||||
raise RuntimeError("required configuration is missing: " + name)
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
endpoint = required("S3_ENDPOINT")
|
||||
region = os.environ.get("S3_REGION", "us-east-1")
|
||||
bucket = required("S3_BUCKET")
|
||||
access_key = required("S3_ADMIN_ACCESS_KEY_ID")
|
||||
secret_key = required("S3_ADMIN_SECRET_ACCESS_KEY")
|
||||
|
||||
client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
region_name=region,
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
config=BotoConfig(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=2,
|
||||
read_timeout=10,
|
||||
retries={"max_attempts": 2, "mode": "standard"},
|
||||
),
|
||||
)
|
||||
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
client.head_bucket(Bucket=bucket)
|
||||
break
|
||||
except ClientError as error:
|
||||
code = str(error.response.get("Error", {}).get("Code", ""))
|
||||
if code in ("404", "NoSuchBucket", "NotFound"):
|
||||
try:
|
||||
client.create_bucket(Bucket=bucket)
|
||||
break
|
||||
except ClientError as create_error:
|
||||
create_code = str(
|
||||
create_error.response.get("Error", {}).get("Code", "")
|
||||
)
|
||||
if create_code in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
|
||||
break
|
||||
last_error = create_error
|
||||
else:
|
||||
last_error = error
|
||||
except BotoCoreError as error:
|
||||
last_error = error
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("S3 bucket bootstrap failed") from last_error
|
||||
time.sleep(1)
|
||||
|
||||
# SeaweedFS buckets are private by default and anonymous requests have no
|
||||
# grant. Some S3 implementations close the connection for unsupported
|
||||
# policy operations, so this best-effort cleanup must not fail bootstrap.
|
||||
try:
|
||||
client.delete_bucket_policy(Bucket=bucket)
|
||||
except (BotoCoreError, ClientError):
|
||||
pass
|
||||
sys.stderr.write("bucket is ready: %s\n" % bucket)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Runtime configuration loaded from environment variables or *_FILE secrets."""
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _secret(name, default=None, required=False):
|
||||
value = os.environ.get(name)
|
||||
if value is None:
|
||||
file_name = os.environ.get(name + "_FILE")
|
||||
if file_name:
|
||||
value = Path(file_name).read_text(encoding="utf-8").strip()
|
||||
if value is None:
|
||||
if required:
|
||||
raise RuntimeError("required configuration is missing: " + name)
|
||||
return default
|
||||
return value
|
||||
|
||||
|
||||
def _int_secret(name, default):
|
||||
value = _secret(name)
|
||||
return default if value is None else int(value)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Config:
|
||||
database_url: str
|
||||
s3_endpoint: str
|
||||
s3_region: str
|
||||
s3_bucket: str
|
||||
s3_access_key_id: str
|
||||
s3_secret_access_key: str
|
||||
max_upload_bytes: int
|
||||
max_image_pixels: int
|
||||
session_ttl_seconds: int
|
||||
idempotency_ttl_seconds: int
|
||||
instance_id: str
|
||||
cursor_secret: str
|
||||
host: str
|
||||
port: int
|
||||
|
||||
@classmethod
|
||||
def from_env(cls):
|
||||
return cls(
|
||||
database_url=_secret("DATABASE_URL", required=True),
|
||||
s3_endpoint=_secret("S3_ENDPOINT", "http://s3:9000"),
|
||||
s3_region=_secret("S3_REGION", "us-east-1"),
|
||||
s3_bucket=_secret("S3_BUCKET", "messenger-attachments"),
|
||||
s3_access_key_id=_secret("S3_ACCESS_KEY_ID", required=True),
|
||||
s3_secret_access_key=_secret("S3_SECRET_ACCESS_KEY", required=True),
|
||||
max_upload_bytes=_int_secret("MAX_UPLOAD_BYTES", 10_485_760),
|
||||
max_image_pixels=_int_secret("MAX_IMAGE_PIXELS", 40_000_000),
|
||||
session_ttl_seconds=_int_secret("SESSION_TTL_SECONDS", 3600),
|
||||
idempotency_ttl_seconds=_int_secret("IDEMPOTENCY_TTL_SECONDS", 86_400),
|
||||
instance_id=_secret("INSTANCE_ID", "api-local"),
|
||||
cursor_secret=_secret("CURSOR_SECRET", "local-dev-only-cursor-secret"),
|
||||
host=_secret("APP_HOST", "0.0.0.0"),
|
||||
port=_int_secret("APP_PORT", 8080),
|
||||
)
|
||||
@@ -0,0 +1,128 @@
|
||||
"""PostgreSQL pool and idempotent schema bootstrap."""
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
MIGRATION_LOCK = 0x4C414234 # "LAB4"
|
||||
|
||||
SCHEMA = [
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
)
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
)
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS sessions_expires_idx ON sessions(expires_at)",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
)
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
)
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members(user_id, chat_id)",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id),
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
)
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS messages_chat_order_idx ON messages(chat_id, created_at, id)",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
owner_id UUID NOT NULL REFERENCES users(id),
|
||||
filename TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL,
|
||||
variants JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
error_code TEXT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL
|
||||
)
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments(chat_id)",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS 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,
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
UNIQUE (message_id, position)
|
||||
)
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments(attachment_id)",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS idempotency (
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
key TEXT NOT NULL,
|
||||
request_hash TEXT NOT NULL,
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (user_id, chat_id, key)
|
||||
)
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS idempotency_created_idx ON idempotency(created_at)",
|
||||
]
|
||||
|
||||
|
||||
def wait_for_database(dsn, timeout_seconds=90):
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with psycopg.connect(dsn, connect_timeout=3) as connection:
|
||||
connection.execute("SELECT 1")
|
||||
return
|
||||
except psycopg.Error as error:
|
||||
last_error = error
|
||||
time.sleep(1)
|
||||
raise RuntimeError("PostgreSQL did not become available") from last_error
|
||||
|
||||
|
||||
def create_pool(dsn):
|
||||
return ConnectionPool(
|
||||
conninfo=dsn,
|
||||
min_size=1,
|
||||
max_size=10,
|
||||
timeout=10,
|
||||
kwargs={"row_factory": dict_row},
|
||||
open=False,
|
||||
)
|
||||
|
||||
|
||||
def migrate(pool):
|
||||
with pool.connection() as connection:
|
||||
with connection.transaction():
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT pg_advisory_xact_lock(%s)", (MIGRATION_LOCK,))
|
||||
for statement in SCHEMA:
|
||||
cursor.execute(statement)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Bounded image inspection: sniff MIME, enforce pixel limit, verify decoding."""
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
# We enforce the configured limit explicitly before any full decode. Disabling
|
||||
# Pillow's own heuristic keeps the error deterministic for the API contract.
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
|
||||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_MAGIC = b"\xff\xd8\xff"
|
||||
|
||||
|
||||
class InvalidImage(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ImageTooLarge(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def sniff_content_type(data):
|
||||
if data.startswith(PNG_MAGIC):
|
||||
return "image/png"
|
||||
if data.startswith(JPEG_MAGIC):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def inspect_image(data, declared_content_type, max_pixels):
|
||||
"""Validate bytes and return (actual_content_type, width, height)."""
|
||||
actual = sniff_content_type(data)
|
||||
if actual is None or actual != declared_content_type:
|
||||
raise InvalidImage("unsupported or mismatched image content")
|
||||
|
||||
try:
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
width, height = image.size
|
||||
if width <= 0 or height <= 0:
|
||||
raise InvalidImage("invalid image dimensions")
|
||||
if width * height > max_pixels:
|
||||
raise ImageTooLarge("decoded pixel limit exceeded")
|
||||
if image.format not in ("PNG", "JPEG"):
|
||||
raise InvalidImage("unsupported image format")
|
||||
image.verify()
|
||||
|
||||
# verify() checks structure; load() catches truncated payloads and
|
||||
# corrupt compressed streams that would otherwise reach the client.
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
image.load()
|
||||
except ImageTooLarge:
|
||||
raise
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
raise InvalidImage("corrupt image") from None
|
||||
|
||||
return actual, width, height
|
||||
@@ -0,0 +1,4 @@
|
||||
from .server import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Password hashing, opaque sessions and signed pagination cursors."""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import secrets
|
||||
|
||||
SCRYPT_N = 2 ** 14
|
||||
SCRYPT_R = 8
|
||||
SCRYPT_P = 1
|
||||
SCRYPT_DKLEN = 32
|
||||
SCRYPT_MAXMEM = 64 * 1024 * 1024
|
||||
|
||||
DUMMY_PASSWORD_HASH = None
|
||||
|
||||
|
||||
def _b64encode(value):
|
||||
return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _b64decode(value):
|
||||
padding = "=" * (-len(value) % 4)
|
||||
return base64.urlsafe_b64decode(value + padding)
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
salt = secrets.token_bytes(16)
|
||||
digest = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=SCRYPT_N,
|
||||
r=SCRYPT_R,
|
||||
p=SCRYPT_P,
|
||||
dklen=SCRYPT_DKLEN,
|
||||
maxmem=SCRYPT_MAXMEM,
|
||||
)
|
||||
return "scrypt${}${}${}${}${}".format(
|
||||
SCRYPT_N, SCRYPT_R, SCRYPT_P, _b64encode(salt), _b64encode(digest)
|
||||
)
|
||||
|
||||
|
||||
def verify_password(password, stored):
|
||||
try:
|
||||
algorithm, n, r, p, salt, digest = stored.split("$")
|
||||
if algorithm != "scrypt":
|
||||
return False
|
||||
expected = _b64decode(digest)
|
||||
actual = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=_b64decode(salt),
|
||||
n=int(n),
|
||||
r=int(r),
|
||||
p=int(p),
|
||||
dklen=len(expected),
|
||||
maxmem=SCRYPT_MAXMEM,
|
||||
)
|
||||
return hmac.compare_digest(actual, expected)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def dummy_password_hash():
|
||||
global DUMMY_PASSWORD_HASH
|
||||
if DUMMY_PASSWORD_HASH is None:
|
||||
DUMMY_PASSWORD_HASH = hash_password(secrets.token_urlsafe(24))
|
||||
return DUMMY_PASSWORD_HASH
|
||||
|
||||
|
||||
def new_session_token():
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _signature(secret, payload):
|
||||
return hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()[:32]
|
||||
|
||||
|
||||
def encode_cursor(secret, payload):
|
||||
raw = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
return _b64encode(raw) + "." + _signature(secret, raw)
|
||||
|
||||
|
||||
def decode_cursor(secret, value):
|
||||
if not value or "." not in value:
|
||||
raise ValueError("invalid cursor")
|
||||
encoded, signature = value.rsplit(".", 1)
|
||||
raw = _b64decode(encoded)
|
||||
if not hmac.compare_digest(_signature(secret, raw), signature):
|
||||
raise ValueError("invalid cursor")
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("invalid cursor")
|
||||
return payload
|
||||
+1074
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,55 @@
|
||||
"""Private S3-compatible object storage client."""
|
||||
import boto3
|
||||
from botocore.config import Config as BotoConfig
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self, endpoint, region, bucket, access_key_id, secret_access_key):
|
||||
self.bucket = bucket
|
||||
self.client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
region_name=region,
|
||||
aws_access_key_id=access_key_id,
|
||||
aws_secret_access_key=secret_access_key,
|
||||
config=BotoConfig(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=2,
|
||||
read_timeout=5,
|
||||
# Fail fast: a stalled storage call must not hold an API thread
|
||||
# for the whole client timeout, and retries are the client's job.
|
||||
retries={"max_attempts": 1, "mode": "standard"},
|
||||
),
|
||||
)
|
||||
|
||||
def ready(self):
|
||||
try:
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
return True
|
||||
except (BotoCoreError, ClientError):
|
||||
return False
|
||||
|
||||
def put(self, key, data, content_type):
|
||||
self.client.put_object(
|
||||
Bucket=self.bucket,
|
||||
Key=key,
|
||||
Body=data,
|
||||
ContentType=content_type,
|
||||
ContentLength=len(data),
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def is_missing_object(error):
|
||||
if not isinstance(error, ClientError):
|
||||
return False
|
||||
code = str(error.response.get("Error", {}).get("Code", ""))
|
||||
status = error.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
return code in ("NoSuchKey", "NotFound", "404") or status == 404
|
||||
Reference in New Issue
Block a user