diff --git a/README.md b/README.md index 94c528b..c54b37f 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,9 @@ Settings live in the `privatestudio.settings` package. Choose one with `DJANGO_S |---|---|---| | `STORAGE_PATH` | all | File storage root (default `/storage`) | | `S3_CREDENTIAL_TTL_HOURS` | all | Lifetime of `/api/s3keys` credentials (default `1`) | +| `UPLOAD_PART_SIZE_MB` | all | Part size for browser uploads (default `16`). Files that would need over 10,000 parts use larger parts | +| `UPLOAD_MAX_SIZE` | all | Largest multipart upload in bytes (default `0`, no limit) | +| `UPLOAD_EXPIRY_DAYS` | all | `cleanup_uploads` removes unfinished uploads idle for this many days (default `7`) | | `DJANGO_TIME_ZONE` | all | Time zone (default `UTC`) | | `SECRET_KEY` | production | Django secret key | | `ALLOWED_HOSTS` | production | Comma-separated host names | @@ -82,6 +85,11 @@ All endpoints except `/health` need `Authorization: Bearer `. The S3 en | Method | Path | Description | |---|---|---| | PUT | `/s3/{bucket}/{key}` | Upload: either a raw body, or multipart with a `file` field | +| POST | `/s3/{bucket}/{key}?uploads` | Start a multipart upload | +| PUT | `/s3/{bucket}/{key}?partNumber=N&uploadId=ID` | Upload a part | +| GET | `/s3/{bucket}/{key}?uploadId=ID` | List received parts | +| POST | `/s3/{bucket}/{key}?uploadId=ID` | Complete a multipart upload | +| DELETE | `/s3/{bucket}/{key}?uploadId=ID` | Abort a multipart upload | | GET | `/s3/{bucket}/{key}` | Download | | HEAD | `/s3/{bucket}/{key}` | Object size | | DELETE | `/s3/{bucket}/{key}` | Delete | @@ -108,6 +116,22 @@ s3 = boto3.client("s3", endpoint_url="http://localhost:8000/s3", s3.upload_file("video.mp4", "demo", "videos/video.mp4") ``` +`upload_file` sends files over 8 MB as a multipart upload. Uploads and downloads are streamed in 1 MB blocks, so memory use does not grow with file size. Signed requests must include `X-Amz-Content-Sha256` in their signed headers (boto3 and other S3 SDKs do), and the body is checked against it. boto3's `aws-chunked` uploads with CRC32 trailers are supported; the `STREAMING-AWS4-HMAC-SHA256-PAYLOAD` signing mode is not. + +### Browser uploads + +The studio page (`/studio/{bucket}/`) has an uploader for signed-in users. It sends files in parts, three at a time, and retries failed parts. If an upload is interrupted, picking the same file again (same name, size and modification time) sends only the missing parts. It uses these session-authenticated JSON endpoints, which need the `X-CSRFToken` header: + +| Method | Path | Description | +|---|---|---| +| POST | `/studio/{bucket}/uploads/` | Start: `{"filename", "folder", "size", "last_modified", "overwrite"}` | +| GET | `/studio/{bucket}/uploads/{id}/` | Status and received part numbers | +| PUT | `/studio/{bucket}/uploads/{id}/parts/{n}/` | A part as the raw request body | +| POST | `/studio/{bucket}/uploads/{id}/complete/` | Join the parts (`{"overwrite": true}` to replace a file created meanwhile) | +| DELETE | `/studio/{bucket}/uploads/{id}/` | Cancel | + +Parts are kept in `STORAGE_PATH/.multipart/` until the upload completes, so a file temporarily needs twice its size in free space. Run `python manage.py cleanup_uploads` daily to remove abandoned uploads (see [README_SERVE.md](README_SERVE.md)). + ### Transcode profiles and jobs (per studio) | Method | Path | Body | diff --git a/README_SERVE.md b/README_SERVE.md index 0e7dc9f..b6ce543 100644 --- a/README_SERVE.md +++ b/README_SERVE.md @@ -53,6 +53,23 @@ python manage.py runserver 0.0.0.0:8000 In production, set `DJANGO_SETTINGS_MODULE=privatestudio.settings.production` and serve `privatestudio.wsgi:application` or `privatestudio.asgi:application` with your WSGI/ASGI server of choice. See the configuration table in [README.md](README.md). +### cleanup_uploads + +```bash +python manage.py cleanup_uploads [--days 7] [--dry-run] +``` + +This removes unfinished uploads with no activity for `--days` (default `UPLOAD_EXPIRY_DAYS`), part directories without an active upload, and temporary files older than a day. Run it daily, for example from cron. + +## Serving large uploads + +Uploads and downloads are streamed, but the server in front of Django must allow them: + +- **WSGI** (e.g. gunicorn): request bodies are read straight from the socket. A slow upload occupies a worker thread, so use threaded workers (`-k gthread --threads 8`) and a `--timeout` longer than the slowest part and the final join of a large file. A chunked request without `Content-Length` (boto3 over HTTPS) needs a server that sets `wsgi.input_terminated`, as gunicorn does; otherwise it is refused with 411. +- **ASGI** (e.g. uvicorn): Django writes each request body to a temporary file before the view runs. Point `TMPDIR` at a disk with room for the largest single upload. Browser parts are 16 MB, but a plain S3 `PUT` of a whole file needs its full size. +- **nginx**: set `client_max_body_size` above the part size (or `0` for large single PUTs), use `proxy_request_buffering off` for WSGI so bodies are not buffered twice, and raise `proxy_read_timeout` so completing a large upload is not cut off. +- **Locking** uses `flock` on files in `STORAGE_PATH`. Run all app servers on the host that owns the storage, or on a filesystem where `flock` works across hosts. + ## Typical Workflow ```bash diff --git a/privatestudio/settings/base.py b/privatestudio/settings/base.py index 791aa27..22a2fdb 100644 --- a/privatestudio/settings/base.py +++ b/privatestudio/settings/base.py @@ -126,12 +126,18 @@ STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" -# Uploads: S3 PUT requests read the full raw request body (video files), so -# don't cap the in-memory body size. -DATA_UPLOAD_MAX_MEMORY_SIZE = None +# Object bodies are streamed, so this only limits API and form bodies. +DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024 # Private Studio configuration PRIVATESTUDIO_STORAGE_PATH = os.environ.get("STORAGE_PATH", os.path.join(BASE_DIR, "storage")) PRIVATESTUDIO_S3_CREDENTIAL_TTL_HOURS = int(os.environ.get("S3_CREDENTIAL_TTL_HOURS", "1")) + +# Size of the parts the browser uploader sends. Larger parts are used for files that need over 10,000. +PRIVATESTUDIO_UPLOAD_PART_SIZE = int(os.environ.get("UPLOAD_PART_SIZE_MB", "16")) * 1024 * 1024 +# Largest multipart upload in bytes. 0 means no limit. +PRIVATESTUDIO_UPLOAD_MAX_SIZE = int(os.environ.get("UPLOAD_MAX_SIZE", "0")) +# cleanup_uploads removes unfinished uploads without activity for this long. +PRIVATESTUDIO_UPLOAD_EXPIRY_DAYS = int(os.environ.get("UPLOAD_EXPIRY_DAYS", "7")) diff --git a/privatestudio/studio/admin.py b/privatestudio/studio/admin.py index 43f81da..bbad6f2 100644 --- a/privatestudio/studio/admin.py +++ b/privatestudio/studio/admin.py @@ -53,6 +53,18 @@ class UploadedAssetAdmin(admin.ModelAdmin): list_filter = ("studio",) +@admin.register(models.MultipartUpload) +class MultipartUploadAdmin(admin.ModelAdmin): + list_display = ("key", "studio", "status", "total_size", "created_by", "created_at") + list_filter = ("status", "studio") + readonly_fields = ("upload_id",) + + +@admin.register(models.UploadPart) +class UploadPartAdmin(admin.ModelAdmin): + list_display = ("upload", "part_number", "size", "uploaded_at") + + @admin.register(models.TranscodeProfile) class TranscodeProfileAdmin(admin.ModelAdmin): list_display = ("name", "studio", "created_by", "created_at") diff --git a/privatestudio/studio/auth.py b/privatestudio/studio/auth.py index a7d4990..de8e66a 100644 --- a/privatestudio/studio/auth.py +++ b/privatestudio/studio/auth.py @@ -112,7 +112,6 @@ def authenticate_s3_request(request): request.path, request.META.get("QUERY_STRING", ""), headers, - request.body, credential.secret_key, ): user = get_user_model().objects.filter(pk=credential.user_id, is_active=True).first() diff --git a/privatestudio/studio/management/commands/cleanup_uploads.py b/privatestudio/studio/management/commands/cleanup_uploads.py new file mode 100644 index 0000000..3849d47 --- /dev/null +++ b/privatestudio/studio/management/commands/cleanup_uploads.py @@ -0,0 +1,79 @@ +import time +import uuid +from datetime import timedelta + +from django.conf import settings +from django.core.management.base import BaseCommand +from django.db.models import Max +from django.db.models.functions import Coalesce, Greatest +from django.utils import timezone + +from privatestudio.studio import uploads +from privatestudio.studio.models import MultipartUpload, UploadStatus +from privatestudio.studio.storage import LockBusy, UploadGone, get_storage + +TEMP_AGE_SECONDS = 24 * 3600 + + +class Command(BaseCommand): + help = "Remove abandoned uploads, orphaned part directories and old temporary files." + + def add_arguments(self, parser): + parser.add_argument("--days", type=int, default=settings.PRIVATESTUDIO_UPLOAD_EXPIRY_DAYS, + help="Remove uploads without activity for this many days (default %(default)s)") + parser.add_argument("--dry-run", action="store_true", help="Only report what would be removed") + + def handle(self, *args, days, dry_run, **options): + storage = get_storage() + cutoff = timezone.now() - timedelta(days=days) + verb = "Would remove" if dry_run else "Removed" + + expired = MultipartUpload.objects.annotate( + last_activity=Greatest("created_at", Coalesce(Max("parts__uploaded_at"), "created_at")), + ).filter(last_activity__lt=cutoff) + for upload in expired: + if not dry_run: + if upload.status == UploadStatus.ACTIVE: + try: + uploads.abort(upload) + except uploads.UploadError as e: + self.stdout.write(f"Skipped {upload}: {e.message}") + continue + storage.remove_upload(upload.upload_id) + upload.delete() + self.stdout.write(f"{verb} upload {upload.upload_id} {upload}") + + old = time.time() - TEMP_AGE_SECONDS + for path in self.children(storage.multipart_path): + try: + upload_id = uuid.UUID(path.name) + except ValueError: + continue + if path.stat().st_mtime > old: + continue + if MultipartUpload.objects.filter(upload_id=upload_id, status=UploadStatus.ACTIVE).exists(): + continue + if not dry_run: + try: + with storage.lock_upload(upload_id, timeout=0): + storage.remove_upload(upload_id) + except LockBusy: + continue + except UploadGone: + storage.remove_upload(upload_id) + self.stdout.write(f"{verb} directory {path.name}") + + # Writes move a file's mtime, so an upload in progress is never this old. + for path in [*self.children(storage.temp_path), *storage.multipart_path.glob("*/*.tmp")]: + try: + stale = path.stat().st_mtime < old + if stale and not dry_run: + path.unlink() + except FileNotFoundError: + continue + if stale: + self.stdout.write(f"{verb} temporary file {path.name}") + + @staticmethod + def children(directory): + return list(directory.iterdir()) if directory.is_dir() else [] diff --git a/privatestudio/studio/migrations/0002_multipart_uploads.py b/privatestudio/studio/migrations/0002_multipart_uploads.py new file mode 100644 index 0000000..fe72c1e --- /dev/null +++ b/privatestudio/studio/migrations/0002_multipart_uploads.py @@ -0,0 +1,51 @@ +# Generated by Django 6.1.3 on 2026-12-01 23:59 + +import django.db.models.deletion +import django.utils.timezone +import uuid +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('studio', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='MultipartUpload', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('upload_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), + ('key', models.TextField()), + ('filename', models.TextField()), + ('total_size', models.BigIntegerField(blank=True, null=True)), + ('part_size', models.BigIntegerField(blank=True, null=True)), + ('last_modified', models.BigIntegerField(blank=True, null=True)), + ('overwrite', models.BooleanField(default=True)), + ('status', models.CharField(choices=[('active', 'Active'), ('completed', 'Completed'), ('aborted', 'Aborted')], default='active', max_length=20)), + ('etag', models.CharField(blank=True, default='', max_length=64)), + ('created_at', models.DateTimeField(default=django.utils.timezone.now)), + ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='multipart_uploads', to=settings.AUTH_USER_MODEL)), + ('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='multipart_uploads', to='studio.studio')), + ], + ), + migrations.CreateModel( + name='UploadPart', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('part_number', models.PositiveIntegerField()), + ('size', models.BigIntegerField()), + ('etag', models.CharField(max_length=32)), + ('uploaded_at', models.DateTimeField(default=django.utils.timezone.now)), + ('upload', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parts', to='studio.multipartupload')), + ], + options={ + 'ordering': ['part_number'], + 'constraints': [models.UniqueConstraint(fields=('upload', 'part_number'), name='unique_part_per_upload')], + }, + ), + ] diff --git a/privatestudio/studio/models.py b/privatestudio/studio/models.py index fd1cd8c..b10d520 100644 --- a/privatestudio/studio/models.py +++ b/privatestudio/studio/models.py @@ -1,4 +1,6 @@ """Django models for the video transcoding service.""" +import uuid + from django.conf import settings from django.contrib.auth.models import Group from django.db import models @@ -91,6 +93,52 @@ class UploadedAsset(models.Model): return f"{self.studio.bucket_name}/{self.s3_path}" +class UploadStatus(models.TextChoices): + ACTIVE = "active", "Active" + COMPLETED = "completed", "Completed" + ABORTED = "aborted", "Aborted" + + +class MultipartUpload(models.Model): + """An upload sent in parts, from an S3 client or the browser.""" + upload_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) + studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="multipart_uploads") + created_by = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="multipart_uploads", + ) + key = models.TextField() + filename = models.TextField() + # Browser uploads declare these. S3 clients don't, so they are null for those. + total_size = models.BigIntegerField(null=True, blank=True) + part_size = models.BigIntegerField(null=True, blank=True) + last_modified = models.BigIntegerField(null=True, blank=True) + overwrite = models.BooleanField(default=True) + status = models.CharField(max_length=20, choices=UploadStatus.choices, default=UploadStatus.ACTIVE) + etag = models.CharField(max_length=64, blank=True, default="") + created_at = models.DateTimeField(default=timezone.now) + + def __str__(self): + return f"{self.studio.bucket_name}/{self.key} ({self.status})" + + +class UploadPart(models.Model): + """A received part of a multipart upload.""" + upload = models.ForeignKey(MultipartUpload, on_delete=models.CASCADE, related_name="parts") + part_number = models.PositiveIntegerField() + size = models.BigIntegerField() + etag = models.CharField(max_length=32) + uploaded_at = models.DateTimeField(default=timezone.now) + + class Meta: + ordering = ["part_number"] + constraints = [ + models.UniqueConstraint(fields=["upload", "part_number"], name="unique_part_per_upload"), + ] + + def __str__(self): + return f"Part {self.part_number} of {self.upload_id}" + + class TranscodeProfile(models.Model): """Named encoding profile (YAML definition) belonging to a studio.""" studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="transcode_profiles") diff --git a/privatestudio/studio/request_body.py b/privatestudio/studio/request_body.py new file mode 100644 index 0000000..eca2f55 --- /dev/null +++ b/privatestudio/studio/request_body.py @@ -0,0 +1,211 @@ +"""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)) diff --git a/privatestudio/studio/s3_credentials.py b/privatestudio/studio/s3_credentials.py index 856e096..da428e2 100644 --- a/privatestudio/studio/s3_credentials.py +++ b/privatestudio/studio/s3_credentials.py @@ -5,6 +5,7 @@ import logging import secrets from datetime import timedelta from typing import Optional +from urllib.parse import quote from django.conf import settings from django.utils import timezone @@ -73,19 +74,20 @@ def verify_aws_v4_signature( path: str, query_string: str, headers: dict, - body: bytes, secret_key: str, ) -> bool: """ Verify an AWS v4 signature. - + + The payload is covered by the signed X-Amz-Content-Sha256 header. The code + that reads the body must check the body against it (see request_body.py). + Args: auth_header: The Authorization header value method: HTTP method (GET, PUT, POST, DELETE) - path: Request path + path: Decoded request path query_string: Query string headers: Request headers dict - body: Request body bytes secret_key: The secret key to verify against Returns: @@ -132,7 +134,6 @@ def verify_aws_v4_signature( query_string, headers, signed_headers_part, - body, ) # Create string to sign with the full timestamp from X-Amz-Date @@ -152,6 +153,10 @@ def verify_aws_v4_signature( # Compare signatures using constant-time comparison return hmac.compare_digest(calculated_signature, signature) + except ValueError as e: + logger.warning("Rejected v4 signature: %s", e) + return False + except Exception as e: logger.exception(f"Error verifying v4 signature: {e}") return False @@ -163,7 +168,6 @@ def _build_canonical_request( query_string: str, headers: dict, signed_headers: str, - body: bytes, ) -> str: """Build the canonical request for AWS v4 signing.""" # Canonical request format: @@ -184,20 +188,15 @@ def _build_canonical_request( # Build canonical headers canonical_headers = _build_canonical_headers(headers, signed_headers) - # Get the hashed payload from X-Amz-Content-Sha256 header - # This header is already computed by boto3/AWS SDK and is part of SignedHeaders - # Use it directly to avoid hashing large files in memory + # The body hash is declared by the client. It must be signed, or it proves nothing. body_hash = None for key, value in headers.items(): if key.lower() == "x-amz-content-sha256": body_hash = value break - - # If X-Amz-Content-Sha256 is not present (e.g., for small requests or backward compatibility), - # compute it from the body - if not body_hash: - body_hash = hashlib.sha256(body).hexdigest() - + if not body_hash or "x-amz-content-sha256" not in signed_headers.lower().split(";"): + raise ValueError("X-Amz-Content-Sha256 must be present and signed") + canonical_request = ( f"{method}\n" f"{canonical_uri}\n" @@ -217,7 +216,8 @@ def _normalize_path(path: str) -> str: path = "/" elif not path.startswith("/"): path = "/" + path - return path + # Clients sign the percent-encoded path, but WSGI and ASGI decode it. + return quote(path, safe="/~") def _normalize_query_string(query_string: str) -> str: diff --git a/privatestudio/studio/s3_views.py b/privatestudio/studio/s3_views.py index 17695e9..5ab9a1f 100644 --- a/privatestudio/studio/s3_views.py +++ b/privatestudio/studio/s3_views.py @@ -1,20 +1,28 @@ """S3-compatible object upload/download/delete/list views.""" -import hashlib -import io +import errno import logging +import uuid +import xml.etree.ElementTree as ET -from django.http import HttpResponse, JsonResponse -from django.utils import timezone +from asgiref.sync import sync_to_async +from django.core.handlers.asgi import ASGIRequest +from django.http import FileResponse, HttpResponse, JsonResponse, StreamingHttpResponse from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.csrf import csrf_exempt +from privatestudio.studio import uploads from privatestudio.studio.auth import authenticate_s3_request, is_s3_v4_request -from privatestudio.studio.models import Studio, UploadedAsset -from privatestudio.studio.storage import get_storage +from privatestudio.studio.models import MultipartUpload, Studio +from privatestudio.studio.request_body import BodyError, BodyReader, RequestBody, read_small_body +from privatestudio.studio.storage import BLOCK_SIZE, get_storage +from privatestudio.studio.uploads import UploadError logger = logging.getLogger(__name__) +XMLNS = "http://s3.amazonaws.com/doc/2006-03-01/" +MAX_COMPLETE_BODY = 4 * 1024 * 1024 + def _error(status: int, detail: str, **headers) -> JsonResponse: response = JsonResponse({"detail": detail}, status=status) @@ -23,6 +31,51 @@ def _error(status: int, detail: str, **headers) -> JsonResponse: return response +def _xml(root: ET.Element, status: int = 200) -> HttpResponse: + body = ET.tostring(root, encoding="utf-8", xml_declaration=True) + return HttpResponse(body, status=status, content_type="application/xml") + + +def _xml_result(name: str, fields: dict) -> ET.Element: + root = ET.Element(name, xmlns=XMLNS) + for tag, value in fields.items(): + ET.SubElement(root, tag).text = str(value) + return root + + +def _xml_error(status: int, code: str, message: str) -> HttpResponse: + root = ET.Element("Error") + ET.SubElement(root, "Code").text = code + ET.SubElement(root, "Message").text = message + return _xml(root, status) + + +def _is_multipart_call(request) -> bool: + return "uploads" in request.GET or "uploadId" in request.GET + + +def _file_response(request, f): + """Stream an open file in blocks, closing it at the end.""" + if not isinstance(request, ASGIRequest): + return FileResponse(f, content_type="application/octet-stream") + + # Under ASGI, Django reads a synchronous iterator into a list before sending it. + async def blocks(): + try: + while block := await sync_to_async(f.read, thread_sensitive=False)(BLOCK_SIZE): + yield block + finally: + f.close() + + f.seek(0, 2) + size = f.tell() + f.seek(0) + response = StreamingHttpResponse(blocks(), content_type="application/octet-stream") + response["Content-Length"] = str(size) + response._resource_closers.append(f.close) + return response + + @method_decorator(csrf_exempt, name="dispatch") class S3BaseView(View): """Authenticate the request and resolve the bucket to a Studio the user can access.""" @@ -47,60 +100,85 @@ class S3BaseView(View): self.storage = get_storage() try: return super().dispatch(request, *args, **kwargs) + except (UploadError, BodyError) as e: + return self.failure(request, e.status, e.code, e.message) except ValueError as e: - return _error(400, str(e)) + return self.failure(request, 400, "InvalidArgument", str(e)) + except OSError as e: + if e.errno not in (errno.ENOSPC, errno.EDQUOT): + raise + logger.error("Storage is full: %s", e) + return self.failure(request, 507, "InsufficientStorage", "The server has run out of storage") + + @staticmethod + def failure(request, status, code, message): + if _is_multipart_call(request): + return _xml_error(status, code, message) + return _error(status, message) class ObjectView(S3BaseView): - """PUT/GET/DELETE a single object: /s3//.""" + """ + A single object: /s3//. + + Multipart uploads use the same URL with ``uploads`` or ``uploadId`` parameters. + """ + + http_method_names = ["get", "put", "post", "delete", "head"] def put(self, request, bucket, key): - upload = None + if "uploadId" in request.GET: + return self.upload_part(request, key) + + filename = key.split("/")[-1] if request.content_type == "multipart/form-data": - # Django only parses multipart bodies for POST, so parse PUT bodies here. - _, files = request.parse_file_upload(request.META, io.BytesIO(request.body)) - upload = files.get("file") - if upload is not None: # Multipart form upload (backward compatibility) - content = upload.read() - filename = upload.name or key.split("/")[-1] + result, filename = self.put_form(request, key, filename) else: # Raw binary upload (boto3 / AWS v4 signature compatibility) - content = request.body - filename = key.split("/")[-1] + body = RequestBody(request) + result = self.storage.put_stream(self.studio.bucket_name, key, body, body.verify_write) - self.storage.put_object(self.studio.bucket_name, key, content) - - asset, _ = UploadedAsset.objects.update_or_create( - studio=self.studio, - s3_path=key, - defaults={ - "uploaded_by": self.user, - "filename": filename, - "size": len(content), - "upload_timestamp": timezone.now(), - }, - ) + asset = uploads.record_asset(self.studio, self.user, key, filename, result.size) if is_s3_v4_request(request): # S3 PutObject response: 200 with ETag header and an empty body response = HttpResponse(status=200) - response["ETag"] = f'"{hashlib.md5(content).hexdigest()}"' + response["ETag"] = f'"{result.md5}"' response["x-amz-version-id"] = str(asset.id) return response return JsonResponse({ "object_id": asset.id, "key": key, - "size": len(content), + "size": result.size, "filename": asset.filename, }) + def put_form(self, request, key, filename): + # Django only parses multipart bodies for POST, so parse PUT bodies here. Large + # files are spooled to a temporary file. + reader = BodyReader(RequestBody(request)) + _, files = request.parse_file_upload(request.META, reader) + upload = files.get("file") + try: + reader.finish() + if upload is None: + raise UploadError(400, "InvalidRequest", "The form has no 'file' field") + result = self.storage.put_stream(self.studio.bucket_name, key, upload.chunks(BLOCK_SIZE)) + return result, upload.name or filename + finally: + for _, values in files.lists(): + for value in values: + value.close() + def get(self, request, bucket, key): - content = self.storage.get_object(self.studio.bucket_name, key) - if content is None: + if "uploadId" in request.GET: + return self.list_parts(request, key) + f = self.storage.open_object(self.studio.bucket_name, key) + if f is None: return _error(404, "Object not found") - return HttpResponse(content, content_type="application/octet-stream") + return _file_response(request, f) def head(self, request, bucket, key): size = self.storage.get_object_size(self.studio.bucket_name, key) @@ -111,11 +189,88 @@ class ObjectView(S3BaseView): return response def delete(self, request, bucket, key): + if "uploadId" in request.GET: + uploads.abort(self.get_upload(request, key)) + return HttpResponse(status=204) if not self.storage.delete_object(self.studio.bucket_name, key): return _error(404, "Object not found") - UploadedAsset.objects.filter(studio=self.studio, s3_path=key).delete() + self.studio.uploaded_assets.filter(s3_path=key).delete() return JsonResponse({"message": "Object deleted"}) + # Multipart uploads + + def post(self, request, bucket, key): + if "uploads" in request.GET: + upload = uploads.create(self.studio, self.user, key) + return _xml(_xml_result("InitiateMultipartUploadResult", { + "Bucket": bucket, "Key": key, "UploadId": upload.upload_id, + })) + if "uploadId" in request.GET: + return self.complete_upload(request, bucket, key) + return _error(400, "POST needs an 'uploads' or 'uploadId' parameter") + + def get_upload(self, request, key) -> MultipartUpload: + try: + upload_id = uuid.UUID(request.GET["uploadId"]) + except ValueError: + upload_id = None + upload = MultipartUpload.objects.filter(studio=self.studio, key=key, upload_id=upload_id).first() + if upload_id is None or upload is None: + raise UploadError(404, "NoSuchUpload", "The upload does not exist") + return upload + + def upload_part(self, request, key): + upload = self.get_upload(request, key) + try: + number = int(request.GET.get("partNumber", "")) + except ValueError: + raise UploadError(400, "InvalidArgument", "partNumber must be a number") from None + if "x-amz-copy-source" in request.headers: + raise UploadError(501, "NotImplemented", "UploadPartCopy is not supported") + response = HttpResponse(status=200) + response["ETag"] = f'"{uploads.put_part(upload, number, request)}"' + return response + + def list_parts(self, request, key): + upload = self.get_upload(request, key) + if upload.status != "active": + raise UploadError(404, "NoSuchUpload", "The upload is no longer active") + root = _xml_result("ListPartsResult", { + "Bucket": self.studio.bucket_name, "Key": key, "UploadId": upload.upload_id, "IsTruncated": "false", + }) + for part in upload.parts.all(): + element = ET.SubElement(root, "Part") + ET.SubElement(element, "PartNumber").text = str(part.part_number) + ET.SubElement(element, "LastModified").text = part.uploaded_at.isoformat() + ET.SubElement(element, "ETag").text = f'"{part.etag}"' + ET.SubElement(element, "Size").text = str(part.size) + return _xml(root) + + def complete_upload(self, request, bucket, key): + upload = self.get_upload(request, key) + parts = _parse_complete(read_small_body(request, MAX_COMPLETE_BODY)) + upload = uploads.complete(upload, parts) + return _xml(_xml_result("CompleteMultipartUploadResult", { + "Location": request.build_absolute_uri(request.path), + "Bucket": bucket, "Key": key, "ETag": f'"{upload.etag}"', + })) + + +def _parse_complete(body: bytes) -> list[tuple[int, str]]: + malformed = UploadError(400, "MalformedXML", "The request body is not a valid CompleteMultipartUpload") + try: + text = body.decode("utf-8") + # Refuse declarations, so no entity can be expanded. + if ".""" diff --git a/privatestudio/studio/storage.py b/privatestudio/studio/storage.py index 1b3331e..931c38a 100644 --- a/privatestudio/studio/storage.py +++ b/privatestudio/studio/storage.py @@ -1,17 +1,63 @@ """S3-compatible local file storage, organised per studio bucket.""" +import fcntl +import hashlib +import os +import shutil +import time +import uuid +import zlib +from contextlib import contextmanager +from dataclasses import dataclass from pathlib import Path -from typing import Optional +from typing import BinaryIO, Callable, Iterable, Optional from django.conf import settings +BLOCK_SIZE = 1024 * 1024 + + +class InvalidKey(ValueError): + """The object key cannot be stored.""" + + +class LockBusy(Exception): + """Another request is holding the upload's lock.""" + + +class UploadGone(Exception): + """The upload's working directory no longer exists.""" + + +@dataclass +class WriteResult: + size: int + md5: str + crc32: int + class S3FileStorage: - """Local file storage backend with an S3-like interface.""" + """ + Local file storage backend with an S3-like interface. + + Data is written in bounded blocks to a work directory on the same filesystem + as the buckets, then renamed into place. Work directory names start with a + dot, which bucket names (slugs) cannot contain. + """ def __init__(self, base_path): self.base_path = Path(base_path) self.base_path.mkdir(parents=True, exist_ok=True) + # Paths + + @property + def temp_path(self) -> Path: + return self.base_path / ".tmp" + + @property + def multipart_path(self) -> Path: + return self.base_path / ".multipart" + def _get_bucket_path(self, bucket: str) -> Path: bucket_path = self.base_path / bucket bucket_path.mkdir(parents=True, exist_ok=True) @@ -22,18 +68,170 @@ class S3FileStorage: bucket_path = self._get_bucket_path(bucket).resolve() file_path = (bucket_path / key).resolve() if file_path != bucket_path and bucket_path not in file_path.parents: - raise ValueError(f"Invalid key: {key}") + raise InvalidKey(f"Invalid key: {key}") return file_path - def put_object(self, bucket: str, key: str, data: bytes) -> None: + def validate_key(self, bucket: str, key: str) -> Path: + """Return the path to write ``key`` to, or raise InvalidKey.""" + segments = key.split("/") + if any(s in ("", ".", "..") for s in segments): + raise InvalidKey(f"Invalid key: {key}") + if any(len(s.encode("utf-8", "surrogatepass")) > 255 for s in segments): + raise InvalidKey("Invalid key: a path segment is longer than 255 bytes") + if any(ord(c) < 32 or ord(c) == 127 for c in key): + raise InvalidKey("Invalid key: control characters are not allowed") file_path = self._get_file_path(bucket, key) - file_path.parent.mkdir(parents=True, exist_ok=True) - file_path.write_bytes(data) + if file_path.is_dir(): + raise InvalidKey(f"Key conflicts with an existing folder: {key}") + bucket_path = self._get_bucket_path(bucket).resolve() + for parent in file_path.parents: + if parent == bucket_path: + break + if parent.exists() and not parent.is_dir(): + raise InvalidKey(f"Key conflicts with an existing file: {key}") + return file_path - def get_object(self, bucket: str, key: str) -> Optional[bytes]: + def _upload_path(self, upload_id) -> Path: + return self.multipart_path / str(uuid.UUID(str(upload_id))) + + # Writing + + @staticmethod + def _write_file(path: Path, chunks: Iterable[bytes]) -> WriteResult: + """Write chunks to a new file. The caller removes the file on failure.""" + md5 = hashlib.md5(usedforsecurity=False) + crc = size = 0 + # Not mkstemp: that would leave the published file with mode 0600. + with open(path, "xb") as f: + for chunk in chunks: + f.write(chunk) + md5.update(chunk) + crc = zlib.crc32(chunk, crc) + size += len(chunk) + f.flush() + os.fsync(f.fileno()) + return WriteResult(size, md5.hexdigest(), crc) + + def _publish(self, temp: Path, bucket: str, key: str) -> None: + file_path = self.validate_key(bucket, key) + try: + file_path.parent.mkdir(parents=True, exist_ok=True) + os.replace(temp, file_path) + except (FileExistsError, NotADirectoryError, IsADirectoryError) as e: + raise InvalidKey(f"Key conflicts with an existing file or folder: {key}") from e + + def put_stream( + self, bucket: str, key: str, chunks: Iterable[bytes], + verify: Optional[Callable[[WriteResult], None]] = None, + ) -> WriteResult: + """ + Store an object from an iterable of byte blocks. + + An exception from ``chunks`` or ``verify`` leaves any existing object untouched. + """ + self.validate_key(bucket, key) + self.temp_path.mkdir(exist_ok=True) + temp = self.temp_path / uuid.uuid4().hex + try: + result = self._write_file(temp, chunks) + if verify: + verify(result) + self._publish(temp, bucket, key) + finally: + temp.unlink(missing_ok=True) + return result + + # Multipart uploads + + def create_upload(self, upload_id) -> None: + self._upload_path(upload_id).mkdir(parents=True) + + @contextmanager + def lock_upload(self, upload_id, timeout: float = 30): + """ + Hold an exclusive lock on an upload. + + flock is released by the kernel if the worker dies. It only works while a + single host (or a filesystem with working flock) serves the storage. + """ + try: + f = open(self._upload_path(upload_id) / "lock", "ab") + except FileNotFoundError: + raise UploadGone() from None + with f: + deadline = time.monotonic() + timeout + while True: + try: + fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= deadline: + raise LockBusy() from None + time.sleep(0.05) + yield + + def stage_part(self, upload_id, chunks: Iterable[bytes]) -> tuple[Path, WriteResult]: + """Write part data to a staging file. The caller publishes or removes it.""" + temp = self._upload_path(upload_id) / f"{uuid.uuid4().hex}.tmp" + try: + return temp, self._write_file(temp, chunks) + except FileNotFoundError: + raise UploadGone() from None + except BaseException: + temp.unlink(missing_ok=True) + raise + + def _part_path(self, upload_id, part_number: int, etag: str) -> Path: + # The name includes the ETag, so a database row always identifies exact content. + return self._upload_path(upload_id) / f"{part_number:05d}.{etag}.part" + + def publish_part(self, upload_id, part_number: int, etag: str, staged: Path) -> None: + """Name a staged part. Call with the upload's lock held.""" + os.replace(staged, self._part_path(upload_id, part_number, etag)) + + def remove_replaced_parts(self, upload_id, part_number: int, etag: str) -> None: + current = self._part_path(upload_id, part_number, etag) + for path in current.parent.glob(f"{part_number:05d}.*.part"): + if path != current: + path.unlink(missing_ok=True) + + def assemble(self, upload_id, parts: Iterable[tuple[int, str, int]], bucket: str, key: str) -> int: + """ + Join ``(part_number, etag, size)`` parts in order into the final object. + + Call with the upload's lock held. Parts are kept, so a failed join can be + retried. Returns the object size. + """ + self.validate_key(bucket, key) + temp = self._upload_path(upload_id) / f"{uuid.uuid4().hex}.tmp" + total = 0 + try: + with open(temp, "xb") as out: + for number, etag, size in parts: + with open(self._part_path(upload_id, number, etag), "rb") as part: + shutil.copyfileobj(part, out, BLOCK_SIZE) + total += size + if out.tell() != total: + raise ValueError(f"Part {number} has the wrong size on disk") + out.flush() + os.fsync(out.fileno()) + self._publish(temp, bucket, key) + finally: + temp.unlink(missing_ok=True) + return total + + def remove_upload(self, upload_id) -> None: + shutil.rmtree(self._upload_path(upload_id), ignore_errors=True) + + def free_space(self) -> int: + return shutil.disk_usage(self.base_path).free + + # Reading, deleting and listing + + def open_object(self, bucket: str, key: str) -> Optional[BinaryIO]: file_path = self._get_file_path(bucket, key) if file_path.is_file(): - return file_path.read_bytes() + return open(file_path, "rb") return None def delete_object(self, bucket: str, key: str) -> bool: diff --git a/privatestudio/studio/templates/privatestudio/_file_uploader.html b/privatestudio/studio/templates/privatestudio/_file_uploader.html new file mode 100644 index 0000000..286c7d8 --- /dev/null +++ b/privatestudio/studio/templates/privatestudio/_file_uploader.html @@ -0,0 +1,28 @@ +
+
+

Upload files

+
+ {% csrf_token %} +
+
+ + +
+
+ + +
+
+ {# Enabled by the uploader script, so the form can't be submitted without it. #} + +
+
+

+ Large files upload in parts. If an upload stops, pick the same file again to continue where it left off. +

+
    +
    +
    +
    diff --git a/privatestudio/studio/templates/privatestudio/studio_detail.html b/privatestudio/studio/templates/privatestudio/studio_detail.html index 0adaf49..579dcdb 100644 --- a/privatestudio/studio/templates/privatestudio/studio_detail.html +++ b/privatestudio/studio/templates/privatestudio/studio_detail.html @@ -4,8 +4,11 @@

    {{ studio.name }}

    Bucket Name: {{ studio.bucket_name }}

    Group: {{ studio.group.name }}

    -
    + +

    Loading uploaded assets...

    + {% include "privatestudio/_file_uploader.html" %} + {% endblock %} diff --git a/privatestudio/studio/tests/test_s3.py b/privatestudio/studio/tests/test_s3.py index 3f90b37..21f4f33 100644 --- a/privatestudio/studio/tests/test_s3.py +++ b/privatestudio/studio/tests/test_s3.py @@ -34,7 +34,7 @@ class S3InterfaceTests(StudioTestCase): self.upload("test.mp4") response = self.client.get("/s3/demo/test.mp4", headers=self.auth()) self.assertEqual(response.status_code, 200) - self.assertEqual(response.content, b"test file content") + self.assertEqual(response.getvalue(), b"test file content") def test_delete_file(self): self.upload("test.mp4") @@ -85,12 +85,12 @@ class S3InterfaceTests(StudioTestCase): class S3SignatureTests(StudioTestCase): def signed_put(self, url_path, data, access_key, secret_key): - from botocore.auth import SigV4Auth + from botocore.auth import S3SigV4Auth from botocore.awsrequest import AWSRequest from botocore.credentials import Credentials request = AWSRequest(method="PUT", url=f"http://testserver{url_path}", data=data) - SigV4Auth(Credentials(access_key, secret_key), "s3", "us-east-1").add_auth(request) + S3SigV4Auth(Credentials(access_key, secret_key), "s3", "us-east-1").add_auth(request) return self.client.put( url_path, data=data, content_type="", headers={ diff --git a/privatestudio/studio/tests/test_uploads.py b/privatestudio/studio/tests/test_uploads.py new file mode 100644 index 0000000..675dba1 --- /dev/null +++ b/privatestudio/studio/tests/test_uploads.py @@ -0,0 +1,417 @@ +import base64 +import hashlib +import io +import json +import os +import time +import zlib +from pathlib import Path +from unittest import mock + +from django.contrib.auth.models import User +from django.core.management import call_command +from django.test import Client, RequestFactory, override_settings + +from privatestudio.studio import uploads +from privatestudio.studio.models import MultipartUpload, UploadedAsset, UploadPart, UploadStatus +from privatestudio.studio.request_body import BodyError, RequestBody +from privatestudio.studio.tests.base import StudioTestCase + +MIB = 1024 * 1024 + + +def aws_chunked(data: bytes, chunk=4, trailer=True) -> bytes: + out = b"" + for i in range(0, len(data), chunk): + piece = data[i:i + chunk] + out += f"{len(piece):x}\r\n".encode() + piece + b"\r\n" + out += b"0\r\n" + if trailer: + crc = base64.b64encode(zlib.crc32(data).to_bytes(4, "big")).decode() + out += f"x-amz-checksum-crc32:{crc}\r\n".encode() + return out + b"\r\n" + + +class RequestBodyTests(StudioTestCase): + factory = RequestFactory() + + def put(self, data, **headers): + return self.factory.put("/", data=data, content_type="application/octet-stream", headers=headers) + + def read(self, request, **kwargs): + return b"".join(RequestBody(request, **kwargs)) + + def test_sha256_checked(self): + data = b"hello world" + self.assertEqual(self.read(self.put(data, **{"X-Amz-Content-Sha256": hashlib.sha256(data).hexdigest()})), data) + with self.assertRaises(BodyError) as cm: + self.read(self.put(data, **{"X-Amz-Content-Sha256": "0" * 64})) + self.assertEqual(cm.exception.code, "XAmzContentSHA256Mismatch") + + def test_aws_chunked_decoded_and_crc_checked(self): + data = os.urandom(50) + request = self.put(aws_chunked(data), **{ + "X-Amz-Content-Sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "Content-Encoding": "aws-chunked", + "X-Amz-Trailer": "x-amz-checksum-crc32", "X-Amz-Decoded-Content-Length": str(len(data)), + }) + body = RequestBody(request) + self.assertEqual(b"".join(body), data) + result = mock.Mock(crc32=zlib.crc32(data)) + body.verify_write(result) + result.crc32 ^= 1 + with self.assertRaises(BodyError): + body.verify_write(result) + + def test_aws_chunked_missing_trailer_and_wrong_length(self): + headers = {"X-Amz-Content-Sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER", + "X-Amz-Trailer": "x-amz-checksum-crc32"} + with self.assertRaises(BodyError): + self.read(self.put(aws_chunked(b"abcdef", trailer=False), **headers)) + with self.assertRaises(BodyError): + self.read(self.put(aws_chunked(b"abcdef"), **headers, **{"X-Amz-Decoded-Content-Length": "7"})) + with self.assertRaises(BodyError): + self.read(self.put(aws_chunked(b"abcdef")[:-8], **headers)) + + def test_signed_streaming_rejected(self): + with self.assertRaises(BodyError) as cm: + RequestBody(self.put(b"x", **{"X-Amz-Content-Sha256": "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"})) + self.assertEqual(cm.exception.status, 501) + + def test_size_limit(self): + with self.assertRaises(BodyError) as cm: + RequestBody(self.put(b"x" * 10), max_bytes=5) + self.assertEqual(cm.exception.status, 413) + + def test_truncated_body(self): + from django.core.handlers.wsgi import LimitedStream + + request = self.put(b"short") + request.META["CONTENT_LENGTH"] = "10" + request._stream = LimitedStream(io.BytesIO(b"short"), 10) + with self.assertRaises(BodyError) as cm: + self.read(request) + self.assertEqual(cm.exception.code, "IncompleteBody") + + def test_chunked_wsgi_input(self): + request = self.put(b"") + request.META.pop("CONTENT_LENGTH", None) + request.META["HTTP_TRANSFER_ENCODING"] = "chunked" + request.environ["wsgi.input"] = io.BytesIO(b"streamed without a length") + with self.assertRaises(BodyError) as cm: + RequestBody(request) + self.assertEqual(cm.exception.status, 411) + request.environ["wsgi.input_terminated"] = True + self.assertEqual(self.read(request), b"streamed without a length") + + +class S3MultipartTests(StudioTestCase): + """The S3 multipart calls, as made by boto3 through its HTTP layer.""" + + def setUp(self): + super().setUp() + import boto3 + from botocore.config import Config + + creds = self.client.post("/api/s3keys", headers=self.auth()).json() + self.s3 = boto3.client( + "s3", endpoint_url="http://testserver/s3", region_name="us-east-1", + aws_access_key_id=creds["access_key"], aws_secret_access_key=creds["secret_key"], + config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 0}), + ) + self.s3.meta.events.register("before-send", self.send_with_test_client) + + def send_with_test_client(self, request, **kwargs): + """Route boto3's prepared request through Django's test client.""" + from botocore.awsrequest import AWSResponse + + body = request.body + if hasattr(body, "read"): + body = body.read() + url = request.url.split("testserver", 1)[1] + headers = {k: v.decode() if isinstance(v, bytes) else v for k, v in request.headers.items()} + content_type = headers.pop("Content-Type", "") + headers.pop("Content-Length", None) + response = self.client.generic( + request.method, url, data=body or b"", content_type=content_type, headers=headers, + ) + content = response.getvalue() if response.streaming else response.content + raw = mock.Mock() + raw.stream.return_value = iter([content]) + return AWSResponse(request.url, response.status_code, dict(response.items()), raw) + + def test_boto3_upload_file_uses_multipart(self): + from boto3.s3.transfer import TransferConfig + + data = os.urandom(12 * MIB + 123) + config = TransferConfig(multipart_threshold=5 * MIB, multipart_chunksize=5 * MIB, use_threads=False) + self.s3.upload_fileobj(io.BytesIO(data), "demo", "big dir/clip one.mp4", Config=config) + + stored = Path(self.storage_dir, "demo", "big dir", "clip one.mp4") + self.assertEqual(hashlib.sha256(stored.read_bytes()).digest(), hashlib.sha256(data).digest()) + upload = MultipartUpload.objects.get() + self.assertEqual(upload.status, UploadStatus.COMPLETED) + self.assertTrue(upload.etag.endswith("-3")) + self.assertEqual(UploadedAsset.objects.get(s3_path="big dir/clip one.mp4").size, len(data)) + self.assertFalse(Path(self.storage_dir, ".multipart", str(upload.upload_id)).exists()) + response = self.client.get("/s3/demo/big%20dir/clip%20one.mp4", headers=self.auth()) + self.assertEqual(b"".join(response.streaming_content), data) + + def test_parts_out_of_order_replaced_listed_and_completed(self): + upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"] + etags = {} + for number, data in ((2, b"second"), (1, b"wrong"), (1, b"first-")): + etags[number] = self.s3.upload_part( + Bucket="demo", Key="v.bin", UploadId=upload_id, PartNumber=number, Body=data)["ETag"] + listed = self.s3.list_parts(Bucket="demo", Key="v.bin", UploadId=upload_id)["Parts"] + self.assertEqual([(p["PartNumber"], p["Size"]) for p in listed], [(1, 6), (2, 6)]) + self.assertEqual(len(list(Path(self.storage_dir, ".multipart", upload_id).glob("*.part"))), 2) + + parts = [{"PartNumber": n, "ETag": etags[n]} for n in (1, 2)] + result = self.s3.complete_multipart_upload( + Bucket="demo", Key="v.bin", UploadId=upload_id, MultipartUpload={"Parts": parts}) + self.assertEqual(Path(self.storage_dir, "demo", "v.bin").read_bytes(), b"first-second") + # Completing again returns the same result. + again = self.s3.complete_multipart_upload( + Bucket="demo", Key="v.bin", UploadId=upload_id, MultipartUpload={"Parts": parts}) + self.assertEqual(result["ETag"], again["ETag"]) + + def test_complete_rejects_bad_parts(self): + from botocore.exceptions import ClientError + + upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"] + etag = self.s3.upload_part(Bucket="demo", Key="v.bin", UploadId=upload_id, PartNumber=1, Body=b"x")["ETag"] + for parts, code in ( + ([{"PartNumber": 1, "ETag": '"' + "0" * 32 + '"'}], "InvalidPart"), + ([{"PartNumber": 2, "ETag": etag}], "InvalidPart"), + ([{"PartNumber": 1, "ETag": etag}, {"PartNumber": 1, "ETag": etag}], "InvalidPartOrder"), + ): + with self.assertRaises(ClientError) as cm: + self.s3.complete_multipart_upload( + Bucket="demo", Key="v.bin", UploadId=upload_id, MultipartUpload={"Parts": parts}) + self.assertEqual(cm.exception.response["Error"]["Code"], code) + self.assertFalse(Path(self.storage_dir, "demo", "v.bin").exists()) + + def test_abort(self): + from botocore.exceptions import ClientError + + upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"] + self.s3.upload_part(Bucket="demo", Key="v.bin", UploadId=upload_id, PartNumber=1, Body=b"x") + self.s3.abort_multipart_upload(Bucket="demo", Key="v.bin", UploadId=upload_id) + self.assertFalse(Path(self.storage_dir, ".multipart", upload_id).exists()) + with self.assertRaises(ClientError) as cm: + self.s3.upload_part(Bucket="demo", Key="v.bin", UploadId=upload_id, PartNumber=2, Body=b"x") + self.assertEqual(cm.exception.response["Error"]["Code"], "NoSuchUpload") + + def test_upload_id_scoped_to_key(self): + from botocore.exceptions import ClientError + + upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"] + with self.assertRaises(ClientError) as cm: + self.s3.upload_part(Bucket="demo", Key="other.bin", UploadId=upload_id, PartNumber=1, Body=b"x") + self.assertEqual(cm.exception.response["Error"]["Code"], "NoSuchUpload") + + def test_put_object_aws_chunked_with_trailer(self): + """boto3 sends this over HTTPS: aws-chunked framing with a CRC32 trailer.""" + data = os.urandom(3000) + response = self.client.put( + "/s3/demo/chunked.bin", data=aws_chunked(data, chunk=1000), content_type="", + headers={**self.auth(), "Content-Encoding": "aws-chunked", "X-Amz-Trailer": "x-amz-checksum-crc32", + "X-Amz-Decoded-Content-Length": str(len(data))}, + ) + self.assertEqual(response.status_code, 200, response.content) + self.assertEqual(Path(self.storage_dir, "demo", "chunked.bin").read_bytes(), data) + + def test_failed_put_keeps_existing_object(self): + self.client.put("/s3/demo/keep.bin", data=b"original", content_type="", headers=self.auth()) + response = self.client.put( + "/s3/demo/keep.bin", data=b"replacement", content_type="", + headers={**self.auth(), "x-amz-checksum-crc32": base64.b64encode(b"\0\0\0\0").decode()}, + ) + self.assertEqual(response.status_code, 400) + self.assertEqual(Path(self.storage_dir, "demo", "keep.bin").read_bytes(), b"original") + self.assertEqual(list(Path(self.storage_dir, ".tmp").iterdir()), []) + + def test_unsigned_content_hash_rejected(self): + from botocore.auth import S3SigV4Auth + from botocore.awsrequest import AWSRequest + from botocore.credentials import Credentials + + creds = self.client.post("/api/s3keys", headers=self.auth()).json() + request = AWSRequest(method="PUT", url="http://testserver/s3/demo/x.bin", data=b"signed") + S3SigV4Auth(Credentials(creds["access_key"], creds["secret_key"]), "s3", "us-east-1").add_auth(request) + headers = {"Authorization": request.headers["Authorization"], "X-Amz-Date": request.headers["X-Amz-Date"]} + # Signed, but the body hash header is removed: the payload would be unprotected. + response = self.client.put("/s3/demo/x.bin", data=b"signed", content_type="", headers=headers) + self.assertEqual(response.status_code, 401) + # Signed with the hash, but a different body is sent. + headers["X-Amz-Content-Sha256"] = request.headers["X-Amz-Content-Sha256"] + response = self.client.put("/s3/demo/x.bin", data=b"tampered", content_type="", headers=headers) + self.assertEqual(response.status_code, 400) + self.assertFalse(Path(self.storage_dir, "demo", "x.bin").exists()) + + def test_complete_xml_with_entities_rejected(self): + upload_id = self.s3.create_multipart_upload(Bucket="demo", Key="v.bin")["UploadId"] + body = b']>' + response = self.client.post(f"/s3/demo/v.bin?uploadId={upload_id}", data=body, + content_type="application/xml", headers=self.auth()) + self.assertEqual(response.status_code, 400) + self.assertIn(b"MalformedXML", response.content) + + def test_key_conflicting_with_folder(self): + self.client.put("/s3/demo/a/b.bin", data=b"x", content_type="", headers=self.auth()) + response = self.client.put("/s3/demo/a", data=b"x", content_type="", headers=self.auth()) + self.assertEqual(response.status_code, 400) + response = self.client.put("/s3/demo/a/b.bin/c", data=b"x", content_type="", headers=self.auth()) + self.assertEqual(response.status_code, 400) + + +@override_settings(PRIVATESTUDIO_UPLOAD_PART_SIZE=4) +class BrowserUploadTests(StudioTestCase): + def setUp(self): + super().setUp() + self.client = Client(enforce_csrf_checks=True) + self.client.force_login(self.user) + self.client.get("/studio/demo/") + self.csrf = self.client.cookies["csrftoken"].value + self.base = "/studio/demo/uploads/" + + def call(self, method, url, data=b"", content_type="application/octet-stream", client=None, csrf=True): + if isinstance(data, dict): + data, content_type = json.dumps(data), "application/json" + headers = {"X-CSRFToken": self.csrf} if csrf else {} + return (client or self.client).generic(method, url, data=data, content_type=content_type, headers=headers) + + def create(self, size, filename="movie.mp4", folder="raw", **extra): + response = self.call("POST", self.base, {"filename": filename, "folder": folder, "size": size, **extra}) + self.assertEqual(response.status_code, 201, response.content) + return response.json() + + def test_resumable_upload(self): + data = b"0123456789" + upload = self.create(len(data)) + self.assertEqual((upload["part_size"], upload["part_count"], upload["key"]), (4, 3, "raw/movie.mp4")) + + for n in (3, 1): + chunk = data[(n - 1) * 4:n * 4] + self.assertEqual(self.call("PUT", f"{upload['url']}parts/{n}/", chunk).status_code, 200) + status = self.call("GET", upload["url"]).json() + self.assertEqual(sorted(status["received"]), [1, 3]) + + response = self.call("POST", f"{upload['url']}complete/", {}) + self.assertEqual(response.status_code, 400) + self.assertIn("missing", response.json()["detail"]) + + self.call("PUT", f"{upload['url']}parts/2/", data[4:8]) + response = self.call("POST", f"{upload['url']}complete/", {}) + self.assertEqual(response.json()["status"], "completed") + self.assertEqual(Path(self.storage_dir, "demo", "raw", "movie.mp4").read_bytes(), data) + self.assertEqual(UploadedAsset.objects.get().uploaded_by, self.user) + self.assertEqual(self.call("POST", f"{upload['url']}complete/", {}).status_code, 200) + + def test_part_sizes_enforced(self): + upload = self.create(10) + self.assertEqual(self.call("PUT", f"{upload['url']}parts/1/", b"012").status_code, 400) + self.assertEqual(self.call("PUT", f"{upload['url']}parts/1/", b"01234").status_code, 413) + self.assertEqual(self.call("PUT", f"{upload['url']}parts/3/", b"89").status_code, 200) + self.assertEqual(self.call("PUT", f"{upload['url']}parts/4/", b"x").status_code, 400) + self.assertEqual(UploadPart.objects.count(), 1) + + def test_empty_file(self): + upload = self.create(0) + self.call("PUT", f"{upload['url']}parts/1/", b"") + self.assertEqual(self.call("POST", f"{upload['url']}complete/", {}).status_code, 200) + self.assertEqual(Path(self.storage_dir, "demo", "raw", "movie.mp4").read_bytes(), b"") + + def test_csrf_required(self): + response = self.call("POST", self.base, {"filename": "a", "size": 1}, csrf=False) + self.assertEqual(response.status_code, 403) + + def test_existing_file_needs_overwrite(self): + Path(self.storage_dir, "demo", "raw").mkdir(parents=True) + Path(self.storage_dir, "demo", "raw", "movie.mp4").write_bytes(b"old") + response = self.call("POST", self.base, {"filename": "movie.mp4", "folder": "raw", "size": 1}) + self.assertEqual((response.status_code, response.json()["code"]), (409, "ObjectExists")) + self.create(1, overwrite=True) + + def test_file_created_meanwhile_needs_overwrite_at_complete(self): + upload = self.create(1) + self.call("PUT", f"{upload['url']}parts/1/", b"n") + Path(self.storage_dir, "demo", "raw").mkdir(parents=True) + Path(self.storage_dir, "demo", "raw", "movie.mp4").write_bytes(b"other") + response = self.call("POST", f"{upload['url']}complete/", {}) + self.assertEqual(response.json()["code"], "ObjectExists") + self.assertEqual(self.call("POST", f"{upload['url']}complete/", {"overwrite": True}).status_code, 200) + self.assertEqual(Path(self.storage_dir, "demo", "raw", "movie.mp4").read_bytes(), b"n") + + def test_invalid_names(self): + for body in ({"filename": "../x", "size": 1}, {"filename": "a", "folder": "../..", "size": 1}, + {"filename": "a", "folder": "x//y", "size": 1}, {"filename": "a", "size": -1}, + {"filename": "a", "size": True}, {"filename": "", "size": 1}): + self.assertEqual(self.call("POST", self.base, body).status_code, 400, body) + + def test_other_users_cannot_see_upload(self): + upload = self.create(4) + member = User.objects.create_user("member") + member.groups.add(self.group) + other = Client() + other.force_login(member) + self.assertEqual(other.get(upload["url"]).status_code, 404) + + outsider = Client() + outsider.force_login(User.objects.create_user("outsider")) + response = outsider.get(upload["url"]) + self.assertEqual((response.status_code, response.json()["code"]), (403, "AccessDenied")) + self.assertEqual(Client().get(upload["url"]).status_code, 401) + + def test_cancel(self): + upload = self.create(4) + self.assertEqual(self.call("DELETE", upload["url"]).status_code, 204) + self.assertEqual(self.call("PUT", f"{upload['url']}parts/1/", b"0123").status_code, 404) + self.assertEqual(self.call("GET", upload["url"]).json()["status"], "aborted") + + def test_not_enough_disk_space(self): + with mock.patch("privatestudio.studio.storage.S3FileStorage.free_space", return_value=10): + response = self.call("POST", self.base, {"filename": "a", "size": 6}) + self.assertEqual(response.status_code, 507) + + def test_busy_complete(self): + upload = self.create(4) + self.call("PUT", f"{upload['url']}parts/1/", b"0123") + from privatestudio.studio.storage import get_storage + with get_storage().lock_upload(upload["id"]): + response = self.call("POST", f"{upload['url']}complete/", {}) + self.assertEqual((response.status_code, response.json()["code"]), (409, "Busy")) + + def test_large_files_use_bigger_parts(self): + self.assertEqual(uploads.choose_part_size(100), 4) + self.assertEqual(uploads.choose_part_size(50_000 * MIB), 5 * MIB) + + +class CleanupTests(StudioTestCase): + def test_removes_expired_and_orphaned(self): + from datetime import timedelta + from django.utils import timezone + from privatestudio.studio.storage import get_storage + + storage = get_storage() + fresh = uploads.create(self.studio, self.user, "fresh.bin", total_size=1) + old = uploads.create(self.studio, self.user, "old.bin", total_size=1) + MultipartUpload.objects.filter(pk=old.pk).update(created_at=timezone.now() - timedelta(days=30)) + orphan = storage.multipart_path / "00000000-0000-0000-0000-000000000001" + orphan.mkdir() + stale_temp = storage.temp_path / "stale" + storage.temp_path.mkdir() + stale_temp.write_bytes(b"x") + long_ago = time.time() - 3 * 86400 + for path in (orphan, stale_temp): + os.utime(path, (long_ago, long_ago)) + + call_command("cleanup_uploads", "--dry-run", stdout=io.StringIO()) + self.assertTrue(orphan.exists()) + call_command("cleanup_uploads", stdout=io.StringIO()) + + self.assertEqual(list(MultipartUpload.objects.values_list("key", flat=True)), ["fresh.bin"]) + self.assertFalse((storage.multipart_path / str(old.upload_id)).exists()) + self.assertTrue((storage.multipart_path / str(fresh.upload_id)).exists()) + self.assertFalse(orphan.exists()) + self.assertFalse(stale_temp.exists()) diff --git a/privatestudio/studio/uploads.py b/privatestudio/studio/uploads.py new file mode 100644 index 0000000..2c460d5 --- /dev/null +++ b/privatestudio/studio/uploads.py @@ -0,0 +1,234 @@ +"""Multipart uploads, shared by the S3 API and the browser uploader.""" +import hashlib +import math +import uuid +from typing import Iterable, Optional + +from django.conf import settings +from django.db import transaction +from django.utils import timezone + +from privatestudio.studio.models import MultipartUpload, UploadedAsset, UploadPart, UploadStatus +from privatestudio.studio.request_body import RequestBody +from privatestudio.studio.storage import LockBusy, UploadGone, get_storage + +MIB = 1024 * 1024 +MAX_PARTS = 10_000 +MAX_PART_SIZE = 5 * 1024 * MIB + + +class UploadError(Exception): + def __init__(self, status: int, code: str, message: str): + super().__init__(message) + self.status, self.code, self.message = status, code, message + + +def _no_such_upload() -> UploadError: + return UploadError(404, "NoSuchUpload", "The upload does not exist or is no longer active") + + +def _busy() -> UploadError: + return UploadError(503, "SlowDown", "The upload is being completed by another request") + + +def record_asset(studio, user, key: str, filename: str, size: int) -> UploadedAsset: + asset, _ = UploadedAsset.objects.update_or_create( + studio=studio, + s3_path=key, + defaults={ + "uploaded_by": user, + "filename": filename, + "size": size, + "upload_timestamp": timezone.now(), + }, + ) + return asset + + +def choose_part_size(total_size: int) -> int: + """The configured part size, or the whole MiB size that fits into MAX_PARTS.""" + configured = settings.PRIVATESTUDIO_UPLOAD_PART_SIZE + if total_size <= configured * MAX_PARTS: + return configured + return math.ceil(total_size / MAX_PARTS / MIB) * MIB + + +def part_count(upload: MultipartUpload) -> int: + return max(1, math.ceil(upload.total_size / upload.part_size)) + + +def expected_part_size(upload: MultipartUpload, number: int) -> int: + if number < part_count(upload): + return upload.part_size + return upload.total_size - (number - 1) * upload.part_size + + +def create( + studio, user, key: str, total_size: Optional[int] = None, + last_modified: Optional[int] = None, overwrite: bool = True, +) -> MultipartUpload: + """Start an upload. ``total_size`` is known for browser uploads only.""" + storage = get_storage() + storage.validate_key(studio.bucket_name, key) + part_size = None + if total_size is not None: + limit = settings.PRIVATESTUDIO_UPLOAD_MAX_SIZE + if (limit and total_size > limit) or total_size > MAX_PARTS * MAX_PART_SIZE: + raise UploadError(413, "EntityTooLarge", "The file is larger than the allowed size") + # The parts and the joined file exist together for a while. + if storage.free_space() < 2 * total_size: + raise UploadError(507, "InsufficientStorage", "There is not enough free disk space for this file") + part_size = choose_part_size(total_size) + if not overwrite and storage.object_exists(studio.bucket_name, key): + raise UploadError(409, "ObjectExists", "A file with this name already exists") + + upload_id = uuid.uuid4() + storage.create_upload(upload_id) + try: + return MultipartUpload.objects.create( + upload_id=upload_id, studio=studio, created_by=user, key=key, + filename=key.rsplit("/", 1)[-1], total_size=total_size, part_size=part_size, + last_modified=last_modified, overwrite=overwrite, + ) + except BaseException: + storage.remove_upload(upload_id) + raise + + +def put_part(upload: MultipartUpload, number: int, request) -> str: + """Stream the request body into a part and return its ETag. Sending a part again replaces it.""" + if not 1 <= number <= MAX_PARTS: + raise UploadError(400, "InvalidArgument", f"Part number must be between 1 and {MAX_PARTS}") + if upload.status != UploadStatus.ACTIVE: + raise _no_such_upload() + expected = None + if upload.total_size is not None: + if number > part_count(upload): + raise UploadError(400, "InvalidArgument", "Part number is past the end of the file") + expected = expected_part_size(upload, number) + + storage = get_storage() + body = RequestBody(request, max_bytes=MAX_PART_SIZE if expected is None else expected) + try: + staged, result = storage.stage_part(upload.upload_id, body) + try: + body.verify_write(result) + if expected is not None and result.size != expected: + raise UploadError(400, "IncompleteBody", f"Part {number} must be {expected} bytes") + with storage.lock_upload(upload.upload_id): + upload.refresh_from_db() + if upload.status != UploadStatus.ACTIVE: + raise _no_such_upload() + storage.publish_part(upload.upload_id, number, result.md5, staged) + # A single upsert: update_or_create's read-then-write can hit SQLite + # lock errors when several parts arrive at once. + UploadPart.objects.bulk_create( + [UploadPart(upload=upload, part_number=number, size=result.size, etag=result.md5)], + update_conflicts=True, + unique_fields=["upload", "part_number"], + update_fields=["size", "etag", "uploaded_at"], + ) + storage.remove_replaced_parts(upload.upload_id, number, result.md5) + finally: + staged.unlink(missing_ok=True) + except (UploadGone, MultipartUpload.DoesNotExist): + raise _no_such_upload() from None + except LockBusy: + raise _busy() from None + return result.md5 + + +def _select_parts(upload: MultipartUpload, requested: Optional[Iterable[tuple[int, str]]]) -> list[UploadPart]: + stored = {p.part_number: p for p in upload.parts.all()} + if upload.total_size is not None: + missing = [n for n in range(1, part_count(upload) + 1) if n not in stored] + if missing: + raise UploadError(400, "InvalidPart", f"{len(missing)} parts are missing, first: {missing[0]}") + if requested is None: + return [stored[n] for n in sorted(stored)] + + requested = list(requested) + if not requested: + raise UploadError(400, "MalformedXML", "No parts were listed") + selected, previous = [], 0 + for number, etag in requested: + if number <= previous: + raise UploadError(400, "InvalidPartOrder", "Parts must be listed in ascending order") + previous = number + part = stored.get(number) + if part is None or part.etag != etag.strip().strip('"').lower(): + raise UploadError(400, "InvalidPart", f"Part {number} is missing or its ETag does not match") + selected.append(part) + return selected + + +def complete( + upload: MultipartUpload, requested: Optional[Iterable[tuple[int, str]]] = None, overwrite: bool = False, +) -> MultipartUpload: + """ + Join the parts into the final object. Completing a completed upload returns it again. + + ``requested`` lists ``(part_number, etag)``. None means every stored part. + """ + if upload.status == UploadStatus.COMPLETED: + return upload + storage = get_storage() + studio = upload.studio + try: + # Long enough to wait out a part being published, but not another join. + with storage.lock_upload(upload.upload_id, timeout=2): + upload.refresh_from_db() + if upload.status == UploadStatus.COMPLETED: + return upload + if upload.status != UploadStatus.ACTIVE: + raise _no_such_upload() + parts = _select_parts(upload, requested) + size = sum(p.size for p in parts) + if upload.total_size is not None and size != upload.total_size: + raise UploadError(400, "InvalidPart", "The parts do not add up to the file size") + limit = settings.PRIVATESTUDIO_UPLOAD_MAX_SIZE + if limit and size > limit: + raise UploadError(413, "EntityTooLarge", "The file is larger than the allowed size") + if not (overwrite or upload.overwrite) and storage.object_exists(studio.bucket_name, upload.key): + raise UploadError(409, "ObjectExists", "A file with this name already exists") + + storage.assemble( + upload.upload_id, [(p.part_number, p.etag, p.size) for p in parts], + studio.bucket_name, upload.key, + ) + digests = b"".join(bytes.fromhex(p.etag) for p in parts) + etag = f"{hashlib.md5(digests, usedforsecurity=False).hexdigest()}-{len(parts)}" + with transaction.atomic(): + upload.status = UploadStatus.COMPLETED + upload.etag = etag + upload.save(update_fields=["status", "etag"]) + record_asset(studio, upload.created_by, upload.key, upload.filename, size) + storage.remove_upload(upload.upload_id) + except (UploadGone, MultipartUpload.DoesNotExist): + # Another request may have completed it between our two checks. + current = MultipartUpload.objects.filter(pk=upload.pk).first() + if current and current.status == UploadStatus.COMPLETED: + return current + raise _no_such_upload() from None + except LockBusy: + raise _busy() from None + return upload + + +def abort(upload: MultipartUpload) -> None: + if upload.status != UploadStatus.ACTIVE: + raise _no_such_upload() + storage = get_storage() + try: + with storage.lock_upload(upload.upload_id, timeout=5): + upload.refresh_from_db() + if upload.status != UploadStatus.ACTIVE: + raise _no_such_upload() + upload.status = UploadStatus.ABORTED + upload.save(update_fields=["status"]) + upload.parts.all().delete() + storage.remove_upload(upload.upload_id) + except LockBusy: + raise _busy() from None + except UploadGone: + MultipartUpload.objects.filter(pk=upload.pk, status=UploadStatus.ACTIVE).update(status=UploadStatus.ABORTED) diff --git a/privatestudio/studio/urls.py b/privatestudio/studio/urls.py index 5f12587..0eafc33 100644 --- a/privatestudio/studio/urls.py +++ b/privatestudio/studio/urls.py @@ -10,6 +10,12 @@ studio_patterns = [ path("", views.StudioListView.as_view(), name="list"), path("/", views.StudioDetailView.as_view(), name="detail"), path("/hx/uploaded_assets/", views.UploadedAssetsView.as_view(), name="uploaded_assets"), + path("/uploads/", views.UploadCreateView.as_view(), name="upload_create"), + path("/uploads//", views.UploadView.as_view(), name="upload"), + path("/uploads//parts//", views.UploadPartView.as_view(), + name="upload_part"), + path("/uploads//complete/", views.UploadCompleteView.as_view(), + name="upload_complete"), ] urlpatterns = [ diff --git a/privatestudio/studio/views.py b/privatestudio/studio/views.py index b65536f..2ea0932 100644 --- a/privatestudio/studio/views.py +++ b/privatestudio/studio/views.py @@ -1,7 +1,20 @@ +import errno +import json +import logging + +from django.http import HttpResponse, JsonResponse +from django.urls import reverse +from django.views import View from django.views.generic import ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin -from privatestudio.studio.models import Studio, UploadedAsset, TranscodeProfile +from privatestudio.studio import uploads +from privatestudio.studio.models import MultipartUpload, Studio, UploadedAsset +from privatestudio.studio.request_body import BodyError, read_small_body +from privatestudio.studio.storage import InvalidKey +from privatestudio.studio.uploads import UploadError + +logger = logging.getLogger(__name__) class StudioMixin(AccessMixin): @@ -45,6 +58,7 @@ class StudioDetailView(StudioMixin, DetailView): user_groups = self.request.user.groups.all() return super().get_queryset().filter(group__in=user_groups) + class UploadedAssetsView(StudioMixin, ListView): model = UploadedAsset template_name = "privatestudio/hx_uploaded_assets.html" @@ -52,4 +66,109 @@ class UploadedAssetsView(StudioMixin, ListView): def get_queryset(self): # Filter uploaded assets based on the user's group memberships - return super().get_queryset().filter(studio=self.studio) \ No newline at end of file + return super().get_queryset().filter(studio=self.studio) + + +class UploadApiView(StudioMixin, View): + """JSON endpoints for the browser uploader. Uses the session, with normal CSRF protection.""" + + def handle_no_permission(self): + if not self.request.user.is_authenticated: + return _json_error(401, "NotAuthenticated", "Sign in again to continue") + return _json_error(403, "AccessDenied", "You don't have access to this studio") + + def dispatch(self, request, *args, **kwargs): + try: + return super().dispatch(request, *args, **kwargs) + except (UploadError, BodyError) as e: + return _json_error(e.status, e.code, e.message) + except InvalidKey as e: + return _json_error(400, "InvalidKey", str(e)) + except OSError as e: + if e.errno not in (errno.ENOSPC, errno.EDQUOT): + raise + logger.error("Storage is full: %s", e) + return _json_error(507, "InsufficientStorage", "The server has run out of storage") + + def get_upload(self, upload_id) -> MultipartUpload: + # Browser uploads only: total_size is null for those started by S3 clients. + upload = MultipartUpload.objects.filter( + studio=self.studio, created_by=self.request.user, upload_id=upload_id, total_size__isnull=False, + ).first() + if upload is None: + raise UploadError(404, "NoSuchUpload", "The upload does not exist") + return upload + + def get_json(self) -> dict: + try: + data = json.loads(read_small_body(self.request, 64 * 1024) or b"{}") + except ValueError: + data = None + if not isinstance(data, dict): + raise UploadError(400, "InvalidRequest", "The body must be a JSON object") + return data + + def upload_response(self, upload, status=200): + return JsonResponse({ + "id": str(upload.upload_id), + "url": reverse("studio:upload", args=[self.studio.bucket_name, upload.upload_id]), + "key": upload.key, + "status": upload.status, + "size": upload.total_size, + "part_size": upload.part_size, + "part_count": uploads.part_count(upload), + "received": list(upload.parts.values_list("part_number", flat=True)), + "etag": upload.etag, + }, status=status) + + +def _json_error(status, code, message): + return JsonResponse({"code": code, "detail": message}, status=status) + + +def _is_size(value) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and 0 <= value < 2**63 + + +class UploadCreateView(UploadApiView): + def post(self, request, bucket_name): + data = self.get_json() + filename, folder = data.get("filename"), data.get("folder", "") + size, last_modified = data.get("size"), data.get("last_modified") + if not isinstance(filename, str) or not filename or "/" in filename or not isinstance(folder, str): + raise UploadError(400, "InvalidRequest", "A file name is required and the folder must be text") + if not _is_size(size) or not (last_modified is None or _is_size(last_modified)): + raise UploadError(400, "InvalidRequest", "The size and modification time must be whole numbers") + folder = folder.strip().strip("/") + upload = uploads.create( + self.studio, request.user, f"{folder}/{filename}" if folder else filename, + total_size=size, last_modified=last_modified, overwrite=data.get("overwrite") is True, + ) + return self.upload_response(upload, status=201) + + +class UploadView(UploadApiView): + def get(self, request, bucket_name, upload_id): + return self.upload_response(self.get_upload(upload_id)) + + def delete(self, request, bucket_name, upload_id): + uploads.abort(self.get_upload(upload_id)) + return HttpResponse(status=204) + + +class UploadPartView(UploadApiView): + def put(self, request, bucket_name, upload_id, number): + etag = uploads.put_part(self.get_upload(upload_id), number, request) + return JsonResponse({"part": number, "etag": etag}) + + +class UploadCompleteView(UploadApiView): + def post(self, request, bucket_name, upload_id): + overwrite = self.get_json().get("overwrite") is True + try: + upload = uploads.complete(self.get_upload(upload_id), overwrite=overwrite) + except UploadError as e: + if e.code == "SlowDown": + return _json_error(409, "Busy", e.message) + raise + return self.upload_response(upload) diff --git a/src/js/main.js b/src/js/main.js index 2a2517a..d26cace 100644 --- a/src/js/main.js +++ b/src/js/main.js @@ -5,3 +5,7 @@ import * as bootstrap from 'bootstrap' const jquery = require('jquery') window.$ = jquery window.jQuery = jquery + +import { initUploaders } from './uploader' + +document.addEventListener('DOMContentLoaded', initUploaders) diff --git a/src/js/uploader.js b/src/js/uploader.js new file mode 100644 index 0000000..b7cdddb --- /dev/null +++ b/src/js/uploader.js @@ -0,0 +1,375 @@ +// Resumable chunked uploads for the studio page. +// +// Each file is sent in parts with File.slice(), so the browser never reads a whole +// file into memory. Upload ids are remembered in localStorage: after a reload, +// picking the same file again sends only the missing parts. + +const CONCURRENCY = 3 +const MAX_ATTEMPTS = 8 +const STALL_MS = 120000 +const STORE_PREFIX = 'privatestudio.upload.' + +class FatalError extends Error {} + +class HttpError extends Error { + constructor (status, data) { + super((data && data.detail) || `The server returned HTTP ${status}`) + this.status = status + this.code = data && data.code + } +} + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +const retryable = (error) => + !(error instanceof FatalError) && + (!(error instanceof HttpError) || [0, 408, 429, 500, 502, 503, 504].includes(error.status)) + +function store (action, key, value) { + try { + if (action === 'get') return JSON.parse(window.localStorage.getItem(STORE_PREFIX + key)) + if (action === 'set') window.localStorage.setItem(STORE_PREFIX + key, JSON.stringify(value)) + if (action === 'remove') window.localStorage.removeItem(STORE_PREFIX + key) + } catch (e) { + // Storage can be unavailable (private windows, blocked site data). Resuming then + // starts over, which is still correct. + } + return null +} + +function formatBytes (bytes) { + const units = ['B', 'KB', 'MB', 'GB', 'TB'] + let i = 0 + while (bytes >= 1024 && i < units.length - 1) { bytes /= 1024; i++ } + return `${bytes.toFixed(i ? 1 : 0)} ${units[i]}` +} + +// One XMLHttpRequest. XHR is used because fetch() has no portable upload progress. +function request (method, url, { body = null, csrf, onProgress, xhrs } = {}) { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest() + let stallTimer + const stalled = () => { + clearTimeout(stallTimer) + stallTimer = setTimeout(() => xhr.abort(), STALL_MS) + } + const finish = () => { clearTimeout(stallTimer); if (xhrs) xhrs.delete(xhr) } + + xhr.open(method, url) + xhr.setRequestHeader('X-CSRFToken', csrf) + xhr.setRequestHeader('Accept', 'application/json') + if (body !== null && !(body instanceof Blob)) xhr.setRequestHeader('Content-Type', 'application/json') + xhr.upload.onprogress = (event) => { stalled(); if (onProgress) onProgress(event.loaded) } + xhr.onload = () => { + finish() + let data = null + try { data = xhr.responseText ? JSON.parse(xhr.responseText) : null } catch (e) { data = null } + if (xhr.status >= 200 && xhr.status < 300) resolve(data) + else reject(new HttpError(xhr.status, data)) + } + xhr.onerror = xhr.onabort = () => { finish(); reject(new HttpError(0, { detail: 'The connection failed' })) } + if (xhrs) xhrs.add(xhr) + stalled() + xhr.send(body === null || body instanceof Blob ? body : JSON.stringify(body)) + }) +} + +class FileUpload { + constructor (uploader, file, folder) { + this.uploader = uploader + this.file = file + this.folder = folder + this.cancelled = false + this.xhrs = new Set() + this.inFlight = new Map() + this.done = 0 + this.storeKey = [uploader.userId, uploader.bucket, folder, file.name, file.size, file.lastModified].join('|') + this.renderRow() + } + + renderRow () { + const row = document.createElement('li') + row.className = 'list-group-item' + row.innerHTML = ` +
    + + + + + +
    +
    +
    +
    + ` + row.querySelector('.fw-semibold').textContent = this.folder ? `${this.folder}/${this.file.name}` : this.file.name + this.row = row + this.bar = row.querySelector('.progress-bar') + this.status = row.querySelector('small') + this.retryButton = row.querySelector('[data-action=retry]') + this.cancelButton = row.querySelector('[data-action=cancel]') + this.retryButton.addEventListener('click', () => this.uploader.enqueue(this)) + this.cancelButton.addEventListener('click', () => this.cancel()) + this.uploader.list.prepend(row) + this.setStatus('Waiting') + } + + setStatus (text, style = '') { + this.status.textContent = text + this.status.className = style ? `text-${style}` : 'text-body-secondary' + } + + setProgress (bytes) { + const percent = this.file.size ? Math.min(100, (bytes / this.file.size) * 100) : 100 + this.bar.style.width = `${percent}%` + this.bar.parentElement.setAttribute('aria-valuenow', Math.round(percent)) + } + + call (method, url, options = {}) { + if (this.cancelled) return Promise.reject(new FatalError('Cancelled')) + return request(method, url, { csrf: this.uploader.csrf, xhrs: this.xhrs, ...options }) + } + + // Retry network failures and server errors with exponential backoff. + async withRetry (action) { + for (let attempt = 1; ; attempt++) { + try { + return await action() + } catch (error) { + if (this.cancelled) throw new FatalError('Cancelled') + if (!retryable(error) || attempt >= MAX_ATTEMPTS) throw error + await sleep(Math.min(30000, 1000 * 2 ** (attempt - 1)) * (0.5 + Math.random() / 2)) + } + } + } + + async run () { + this.retryButton.classList.add('d-none') + this.bar.classList.remove('bg-danger', 'bg-success') + this.cancelButton.disabled = false + this.cancelled = false + try { + const upload = await this.start() + if (upload.status !== 'completed') { + await this.sendParts(upload) + await this.complete(upload) + } + store('remove', this.storeKey) + this.setProgress(this.file.size) + this.bar.classList.add('bg-success') + this.setStatus(`Uploaded ${formatBytes(this.file.size)}`, 'success') + this.cancelButton.classList.add('d-none') + document.body.dispatchEvent(new CustomEvent('assets-changed')) + } catch (error) { + if (this.cancelled) return + this.bar.classList.add('bg-danger') + let message = error.message + if (error instanceof HttpError && error.status === 403) { + message += '. If you signed in again in another tab, reload this page and pick the file again to resume.' + } + this.setStatus(message, 'danger') + this.retryButton.classList.remove('d-none') + } + } + + // Resume a remembered upload of this file, or start a new one. + async start () { + const remembered = store('get', this.storeKey) + if (remembered) { + try { + const upload = await this.withRetry(() => this.call('GET', remembered.url)) + if (upload.status === 'active' || upload.status === 'completed') return upload + } catch (error) { + if (!(error instanceof HttpError) || error.status !== 404) throw error + } + store('remove', this.storeKey) + } + + const body = { + filename: this.file.name, + folder: this.folder, + size: this.file.size, + last_modified: this.file.lastModified, + overwrite: false + } + let upload + try { + upload = await this.withRetry(() => this.call('POST', this.uploader.createUrl, { body })) + } catch (error) { + if (!(error instanceof HttpError) || error.code !== 'ObjectExists') throw error + if (!window.confirm(`${body.folder ? body.folder + '/' : ''}${this.file.name} already exists. Replace it?`)) { + throw new FatalError('Not uploaded: a file with this name already exists') + } + body.overwrite = true + upload = await this.withRetry(() => this.call('POST', this.uploader.createUrl, { body })) + } + store('set', this.storeKey, { url: upload.url }) + return upload + } + + async sendParts (upload) { + const received = new Set(upload.received) + const pending = [] + for (let n = 1; n <= upload.part_count; n++) { + if (!received.has(n)) pending.push(n) + } + const partBytes = (n) => Math.min(upload.part_size, this.file.size - (n - 1) * upload.part_size) + this.done = this.file.size - pending.reduce((sum, n) => sum + partBytes(n), 0) + this.inFlight.clear() + const started = Date.now() + const doneAtStart = this.done + + const showProgress = () => { + let sending = 0 + for (const bytes of this.inFlight.values()) sending += bytes + const sent = this.done + sending + this.setProgress(sent) + const seconds = (Date.now() - started) / 1000 + const rate = seconds > 1 ? (sent - doneAtStart) / seconds : 0 + const speed = rate ? `, ${formatBytes(rate)}/s` : '' + this.setStatus(`${formatBytes(sent)} of ${formatBytes(this.file.size)}${speed}`) + } + showProgress() + + const worker = async () => { + while (pending.length) { + const n = pending.shift() + const start = (n - 1) * upload.part_size + const blob = this.file.slice(start, start + partBytes(n)) + await this.withRetry(() => { + this.inFlight.set(n, 0) + return this.call('PUT', `${upload.url}parts/${n}/`, { + body: blob, + onProgress: (loaded) => { this.inFlight.set(n, loaded); showProgress() } + }) + }) + this.inFlight.delete(n) + this.done += blob.size + showProgress() + } + } + // If one worker fails, stop the others so the failure is reported once. + try { + await Promise.all(Array.from({ length: Math.min(CONCURRENCY, pending.length) }, worker)) + } catch (error) { + pending.length = 0 + for (const xhr of this.xhrs) xhr.abort() + throw error + } + } + + // Joining a large file takes time. If the request is cut off, check the + // upload's status, then ask again. + async complete (upload) { + this.setStatus('Finalizing…') + this.bar.classList.add('progress-bar-striped', 'progress-bar-animated') + let overwrite = false + let failures = 0 + const deadline = Date.now() + 60 * 60 * 1000 + try { + while (true) { + try { + return await this.call('POST', `${upload.url}complete/`, { body: { overwrite } }) + } catch (error) { + if (this.cancelled) throw new FatalError('Cancelled') + if (error.code === 'ObjectExists' && !overwrite) { + if (!window.confirm(`${upload.key} was created by someone else meanwhile. Replace it?`)) { + throw new FatalError('Not uploaded: a file with this name already exists. Retry to choose again.') + } + overwrite = true + continue + } + const busy = error.status === 409 && error.code === 'Busy' + if (!busy && (!retryable(error) || ++failures >= MAX_ATTEMPTS)) throw error + if (Date.now() > deadline) throw error + await sleep(3000) + try { + const current = await this.call('GET', upload.url) + if (current.status === 'completed') return current + } catch (e) { + // Try completing again below. + } + } + } + } finally { + this.bar.classList.remove('progress-bar-striped', 'progress-bar-animated') + } + } + + async cancel () { + this.cancelled = true + for (const xhr of this.xhrs) xhr.abort() + this.uploader.dequeue(this) + this.cancelButton.disabled = true + this.retryButton.classList.add('d-none') + this.setStatus('Cancelling…') + const remembered = store('get', this.storeKey) + store('remove', this.storeKey) + if (remembered) { + try { + await request('DELETE', remembered.url, { csrf: this.uploader.csrf }) + } catch (error) { + // The server removes abandoned uploads later. + } + } + this.setStatus('Cancelled', 'warning') + this.bar.classList.add('bg-secondary') + } +} + +// Files upload one after another; each sends several parts at once. +class Uploader { + constructor (form) { + this.form = form + this.createUrl = form.dataset.createUrl + this.bucket = form.dataset.bucket + this.userId = form.dataset.userId + this.csrf = form.querySelector('[name=csrfmiddlewaretoken]').value + this.list = form.querySelector('[data-upload-list]') + this.fileInput = form.querySelector('input[type=file]') + this.folderInput = form.querySelector('[name=folder]') + this.queue = [] + this.active = null + form.querySelector('button[type=submit]').disabled = false + + form.addEventListener('submit', (event) => { + event.preventDefault() + const folder = this.folderInput.value.trim().replace(/^\/+|\/+$/g, '') + for (const file of this.fileInput.files) this.enqueue(new FileUpload(this, file, folder)) + this.fileInput.value = '' + }) + window.addEventListener('beforeunload', (event) => { + if (this.active || this.queue.length) { + event.preventDefault() + event.returnValue = '' + } + }) + } + + enqueue (upload) { + if (!this.queue.includes(upload) && this.active !== upload) { + upload.setStatus('Waiting') + this.queue.push(upload) + } + this.next() + } + + dequeue (upload) { + this.queue = this.queue.filter((item) => item !== upload) + } + + async next () { + if (this.active || !this.queue.length) return + this.active = this.queue.shift() + try { + await this.active.run() + } finally { + this.active = null + this.next() + } + } +} + +export function initUploaders () { + for (const form of document.querySelectorAll('form[data-uploader]')) new Uploader(form) // eslint-disable-line no-new +}