forked from mtusi2026/mtusi2026lab4
grade4
This commit is contained in:
@@ -525,8 +525,14 @@ def validate_image_and_get_dimensions(data: bytes, content_type: str):
|
||||
if content_type == "image/png":
|
||||
if not data.startswith(b'\x89PNG\r\n\x1a\n'):
|
||||
raise HTTPException(status_code=415, detail="Invalid PNG signature")
|
||||
if len(data) >= 24:
|
||||
width, height = struct.unpack('>II', data[16:24])
|
||||
if len(data) < 33:
|
||||
raise HTTPException(status_code=415, detail="Truncated PNG")
|
||||
if data[12:16] != b'IHDR':
|
||||
raise HTTPException(status_code=415, detail="PNG missing IHDR chunk")
|
||||
ihdr_len = struct.unpack('>I', data[8:12])[0]
|
||||
if ihdr_len != 13:
|
||||
raise HTTPException(status_code=415, detail="Invalid IHDR length")
|
||||
width, height = struct.unpack('>II', data[16:24])
|
||||
elif content_type == "image/jpeg":
|
||||
if not data.startswith(b'\xff\xd8'):
|
||||
raise HTTPException(status_code=415, detail="Invalid JPEG signature")
|
||||
@@ -544,6 +550,9 @@ def validate_image_and_get_dimensions(data: bytes, content_type: str):
|
||||
else:
|
||||
raise HTTPException(status_code=415, detail="Unsupported media type")
|
||||
|
||||
if width == 0 or height == 0:
|
||||
raise HTTPException(status_code=415, detail="Could not read image dimensions")
|
||||
|
||||
if width * height > 40_000_000:
|
||||
raise HTTPException(status_code=413, detail="Image exceeds 40 million pixels limit")
|
||||
|
||||
@@ -569,7 +578,7 @@ async def upload_attachment(
|
||||
raise HTTPException(status_code=404, detail="Chat not found or inaccessible")
|
||||
conn.close()
|
||||
|
||||
if any(ord(c) < 0x20 or ord(c) == 0x7f for c in filename):
|
||||
if any(ord(c) < 0x20 or ord(c) == 0x7f for c in filename) or '/' in filename or '\\' in filename:
|
||||
raise HTTPException(400, "Invalid filename")
|
||||
|
||||
content_type = request.headers.get("content-type")
|
||||
@@ -577,7 +586,6 @@ async def upload_attachment(
|
||||
raise HTTPException(status_code=415, detail="Unsupported media type")
|
||||
|
||||
MAX_UPLOAD = 10 * 1024 * 1024
|
||||
|
||||
cl = request.headers.get("content-length")
|
||||
if cl is not None:
|
||||
try:
|
||||
@@ -595,12 +603,31 @@ async def upload_attachment(
|
||||
chunks.append(chunk)
|
||||
body_bytes = b"".join(chunks)
|
||||
|
||||
validate_image_and_get_dimensions(body_bytes, content_type)
|
||||
|
||||
size_bytes = len(body_bytes)
|
||||
sha256_hash = hashlib.sha256(body_bytes).hexdigest()
|
||||
attachment_id = str(uuid.uuid4())
|
||||
now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
s3_key = f"attachments/{chat_id_str}/{attachment_id}/{filename}"
|
||||
|
||||
conn = get_db_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, variants, error_code, created_at, updated_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'pending', '[]', NULL, %s, %s)
|
||||
""", (attachment_id, chat_id_str, user["id"], filename, content_type, size_bytes, sha256_hash, now, now))
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
conn.close()
|
||||
raise HTTPException(status_code=500, detail="Internal error initializing attachment")
|
||||
finally:
|
||||
if not conn.closed:
|
||||
conn.close()
|
||||
|
||||
try:
|
||||
s3_client.put_object(
|
||||
Bucket=S3_BUCKET,
|
||||
@@ -615,15 +642,15 @@ async def upload_attachment(
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, variants, error_code, created_at, updated_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'ready', '[]', NULL, %s, %s)
|
||||
""", (attachment_id, chat_id_str, user["id"], filename, content_type, size_bytes, sha256_hash, now, now))
|
||||
UPDATE attachments SET status = 'ready', updated_at = %s WHERE id = %s
|
||||
""", (now, attachment_id))
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise HTTPException(status_code=500, detail="Internal error saving attachment metadata")
|
||||
raise HTTPException(status_code=500, detail="Internal error finalizing attachment status")
|
||||
finally:
|
||||
conn.close()
|
||||
if not conn.closed:
|
||||
conn.close()
|
||||
|
||||
return {
|
||||
"id": attachment_id,
|
||||
|
||||
Reference in New Issue
Block a user