Stream uploads and downloads in 1 MB blocks so memory use does not grow with file size, under both WSGI and ASGI. - S3 multipart upload API (create, upload part, list parts, complete, abort), so boto3 upload_file works for files over 8 MB. - Browser uploader on the studio page: sends 16 MB parts three at a time with retries, and resumes when the same file is picked again. Uses session-authenticated, CSRF-protected JSON endpoints under /studio/<bucket>/uploads/. - Request bodies are checked against the signed X-Amz-Content-Sha256 instead of being read into memory; signed requests must include it. boto3's aws-chunked bodies with CRC32 trailers are decoded. - Objects are written to a temporary file and renamed into place, so a failed upload leaves the existing file intact. - Downloads stream with FileResponse, or an async iterator under ASGI. - SigV4 verification uses the encoded path, fixing keys with spaces. - cleanup_uploads command removes abandoned uploads and temp files. - DATA_UPLOAD_MAX_MEMORY_SIZE is capped at 10 MB again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
212 lines
8.2 KiB
Python
212 lines
8.2 KiB
Python
"""Read request bodies in bounded blocks, under both WSGI and ASGI."""
|
|
import base64
|
|
import binascii
|
|
import hashlib
|
|
import hmac
|
|
import re
|
|
from typing import Iterator, Optional
|
|
|
|
from django.core.handlers.wsgi import WSGIRequest
|
|
from django.http import UnreadablePostError
|
|
|
|
from privatestudio.studio.storage import BLOCK_SIZE, WriteResult
|
|
|
|
UNSIGNED = "UNSIGNED-PAYLOAD"
|
|
STREAMING_TRAILER = "STREAMING-UNSIGNED-PAYLOAD-TRAILER"
|
|
CRC32_HEADER = "x-amz-checksum-crc32"
|
|
MAX_LINE = 8192
|
|
|
|
|
|
class BodyError(Exception):
|
|
def __init__(self, status: int, code: str, message: str):
|
|
super().__init__(message)
|
|
self.status, self.code, self.message = status, code, message
|
|
|
|
|
|
def _incomplete() -> BodyError:
|
|
return BodyError(400, "IncompleteBody", "The request body ended early")
|
|
|
|
|
|
class RequestBody:
|
|
"""
|
|
Iterate over a request's payload, checking the integrity data sent with it.
|
|
|
|
Iterating raises BodyError for a truncated, oversized or mismatching body, so
|
|
consume it completely before publishing anything. ``verify_write`` checks the
|
|
CRC32, which is only computed by the code that writes the blocks.
|
|
"""
|
|
|
|
def __init__(self, request, max_bytes: Optional[int] = None, verify_hash: bool = True):
|
|
self.max_bytes = max_bytes
|
|
self._crc32: Optional[str] = request.headers.get(CRC32_HEADER)
|
|
self._trailer_expected = False
|
|
self._sha256: Optional[str] = None
|
|
|
|
payload = request.headers.get("x-amz-content-sha256") if verify_hash else None
|
|
encodings = [e.strip().lower() for e in request.headers.get("Content-Encoding", "").split(",")]
|
|
self._aws_chunked = payload == STREAMING_TRAILER or (
|
|
payload in (None, UNSIGNED) and "aws-chunked" in encodings
|
|
)
|
|
if self._aws_chunked:
|
|
trailer = request.headers.get("x-amz-trailer", "").strip().lower()
|
|
if trailer not in ("", CRC32_HEADER):
|
|
raise BodyError(501, "NotImplemented", f"Trailer {trailer} is not supported")
|
|
self._trailer_expected = bool(trailer)
|
|
elif payload and payload.startswith("STREAMING-"):
|
|
raise BodyError(501, "NotImplemented", f"{payload} is not supported")
|
|
elif payload and payload != UNSIGNED:
|
|
if not re.fullmatch(r"[0-9a-f]{64}", payload):
|
|
raise BodyError(400, "InvalidRequest", "Invalid X-Amz-Content-Sha256")
|
|
self._sha256 = payload
|
|
|
|
self._length = self._content_length(request)
|
|
self._decoded_length = None
|
|
if self._aws_chunked and "x-amz-decoded-content-length" in request.headers:
|
|
self._decoded_length = self._parse_length(request.headers["x-amz-decoded-content-length"])
|
|
declared = self._decoded_length if self._aws_chunked else self._length
|
|
if max_bytes is not None and declared is not None and declared > max_bytes:
|
|
raise self._too_large()
|
|
self._read = self._reader(request)
|
|
|
|
@staticmethod
|
|
def _parse_length(value: str) -> int:
|
|
if not re.fullmatch(r"[0-9]{1,19}", value):
|
|
raise BodyError(400, "InvalidRequest", "Invalid content length")
|
|
return int(value)
|
|
|
|
def _content_length(self, request) -> Optional[int]:
|
|
value = request.META.get("CONTENT_LENGTH")
|
|
if value not in (None, ""):
|
|
return self._parse_length(str(value))
|
|
if "chunked" in request.headers.get("Transfer-Encoding", "").lower():
|
|
return None
|
|
return 0
|
|
|
|
def _reader(self, request):
|
|
if self._length is None and isinstance(request, WSGIRequest):
|
|
# Django limits a WSGI stream without Content-Length to 0 bytes. Reading the
|
|
# raw input is only safe when the server guarantees that it ends.
|
|
if not request.environ.get("wsgi.input_terminated"):
|
|
raise BodyError(411, "MissingContentLength", "Content-Length is required")
|
|
return request.environ["wsgi.input"].read
|
|
return request.read
|
|
|
|
def _too_large(self) -> BodyError:
|
|
return BodyError(413, "EntityTooLarge", f"The body is larger than {self.max_bytes} bytes")
|
|
|
|
def _raw(self) -> Iterator[bytes]:
|
|
received = 0
|
|
while True:
|
|
try:
|
|
block = self._read(BLOCK_SIZE)
|
|
except UnreadablePostError as e:
|
|
raise _incomplete() from e
|
|
if not block:
|
|
break
|
|
received += len(block)
|
|
yield block
|
|
if self._length is not None and received != self._length:
|
|
raise _incomplete()
|
|
|
|
def _decoded(self) -> Iterator[bytes]:
|
|
"""Decode aws-chunked framing: ``size\\r\\n data\\r\\n ... 0\\r\\n trailers \\r\\n``."""
|
|
raw = self._raw()
|
|
buffer = bytearray()
|
|
|
|
def fill():
|
|
block = next(raw, None)
|
|
if block is None:
|
|
raise _incomplete()
|
|
buffer.extend(block)
|
|
|
|
def line() -> bytes:
|
|
while (end := buffer.find(b"\r\n")) < 0:
|
|
if len(buffer) > MAX_LINE:
|
|
raise BodyError(400, "InvalidRequest", "Malformed aws-chunked body")
|
|
fill()
|
|
value = bytes(buffer[:end])
|
|
del buffer[:end + 2]
|
|
return value
|
|
|
|
total = 0
|
|
while True:
|
|
size_text = line().split(b";")[0].strip()
|
|
if not re.fullmatch(rb"[0-9a-fA-F]{1,16}", size_text):
|
|
raise BodyError(400, "InvalidRequest", "Malformed aws-chunked body")
|
|
remaining = int(size_text, 16)
|
|
if remaining == 0:
|
|
break
|
|
while remaining:
|
|
if not buffer:
|
|
fill()
|
|
data = bytes(buffer[:remaining])
|
|
del buffer[:len(data)]
|
|
remaining -= len(data)
|
|
total += len(data)
|
|
yield data
|
|
if line():
|
|
raise BodyError(400, "InvalidRequest", "Malformed aws-chunked body")
|
|
|
|
found = False
|
|
while trailer := line():
|
|
name, _, value = trailer.partition(b":")
|
|
if name.strip().lower() == CRC32_HEADER.encode():
|
|
found = True
|
|
self._crc32 = value.strip().decode("ascii", "replace")
|
|
if self._trailer_expected and not found:
|
|
raise _incomplete()
|
|
for _ in raw: # Reach the end, which checks the length.
|
|
pass
|
|
if self._decoded_length is not None and total != self._decoded_length:
|
|
raise _incomplete()
|
|
|
|
def __iter__(self) -> Iterator[bytes]:
|
|
sha256 = hashlib.sha256() if self._sha256 else None
|
|
total = 0
|
|
for block in self._decoded() if self._aws_chunked else self._raw():
|
|
total += len(block)
|
|
if self.max_bytes is not None and total > self.max_bytes:
|
|
raise self._too_large()
|
|
if sha256:
|
|
sha256.update(block)
|
|
yield block
|
|
if sha256 and not hmac.compare_digest(sha256.hexdigest(), self._sha256):
|
|
raise BodyError(400, "XAmzContentSHA256Mismatch", "The body does not match X-Amz-Content-Sha256")
|
|
|
|
def verify_write(self, result: WriteResult) -> None:
|
|
if self._crc32 is None:
|
|
return
|
|
try:
|
|
expected = base64.b64decode(self._crc32, validate=True)
|
|
except (binascii.Error, ValueError):
|
|
expected = b""
|
|
if expected != result.crc32.to_bytes(4, "big"):
|
|
raise BodyError(400, "BadDigest", "The body does not match its CRC32 checksum")
|
|
|
|
|
|
class BodyReader:
|
|
"""Give a RequestBody the ``read(size)`` method that Django's form parser needs."""
|
|
|
|
def __init__(self, body: RequestBody):
|
|
self._blocks = iter(body)
|
|
self._buffer = b""
|
|
|
|
def read(self, size: int = BLOCK_SIZE) -> bytes:
|
|
while len(self._buffer) < size:
|
|
block = next(self._blocks, None)
|
|
if block is None:
|
|
break
|
|
self._buffer += block
|
|
data, self._buffer = self._buffer[:size], self._buffer[size:]
|
|
return data
|
|
|
|
def finish(self) -> None:
|
|
"""Consume what is left, so that the integrity checks run."""
|
|
self._buffer = b""
|
|
for _ in self._blocks:
|
|
pass
|
|
|
|
|
|
def read_small_body(request, limit: int) -> bytes:
|
|
return b"".join(RequestBody(request, max_bytes=limit))
|