diff --git a/Structure_README.md b/Structure_README.md index 831b9f0..9ae5ada 100644 --- a/Structure_README.md +++ b/Structure_README.md @@ -1115,9 +1115,12 @@ The Local Share subsystem (`quota/local_share.py`, `web/share.html`, and the das - **Elimination of `python-multipart` Overhead**: Unlike standard form-data endpoints which require third-party C/Rust parsers or external libraries, file uploads leverage pure raw HTTP streaming via Starlette's `request.stream()`: - - Network bytes flow in 64 KB chunks directly from the incoming socket to disk (`data/local_share//`). - - Total process RAM usage remains $< 1\,\text{MB}$ regardless of whether transferring a small document or a 20 GB multi-file ISO/video. + - The application reads the request in chunks and writes directly to the gateway cache (`data/local_share//`). It does not buffer the entire file. - Raw client requests set the sanitized URI-encoded filename via `X-Filename: ` and standard `Content-Type`. +- **Storage limits**: + - Each uploaded file, uncompressed folder member, and generated ZIP is limited to 1 GiB. Stored files, concurrent uploads, in-progress folder archives, and temporary download bundles share a 4 GiB cache limit. Payload writes also stop when they would leave less than 256 MiB free on the cache filesystem. + - Limits are checked during streaming and ZIP creation, including the ZIP directory written at finalization. The API returns HTTP 413 and discards the rejected partial file or archive. After a folder upload fails, start a new folder session. + - Cache usage includes payload files already present at startup. Unfinished folder sessions held by the running process are discarded after 30 minutes of inactivity at the next cleanup pass. - **Atomic Index Persistence**: - Metadata is persisted in `data/local_share/index.json`. - Mutating operations (`save_file_stream`, `delete_file`, `save_text`, `cleanup_expired`) are synchronized behind an `asyncio.Lock()`. @@ -1134,7 +1137,7 @@ The Local Share subsystem (`quota/local_share.py`, `web/share.html`, and the das - Household devices connected to the router's Wi-Fi or Ethernet LAN can freely upload, download, and share notes without requiring administrative credentials or session tokens. - Requesters arriving from external WAN addresses (in Strong WAN mode) are automatically denied with `403 Forbidden` unless possessing a cryptographically signed HMAC admin session cookie (`COOKIE_NAME`). - **CSRF & WAF Immunity on LAN**: - - LAN requests bypass strict WAN WAF body-size caps, enabling full-bandwidth gigabit file transfers without triggering false-positive rate-limit bans. + - LAN requests bypass WAN WAF body-size checks. Local Share enforces its storage limits independently. ### 3. Client Experience & Standalone Web Portal @@ -1189,7 +1192,7 @@ The Local Share subsystem (`quota/local_share.py`, `web/share.html`, and the das - **`Content-Length` only for single files**: A multi-file/folder send is a ZIP the *sender* builds on the fly; it is larger than the sum of the announced file sizes. `GET /api/share/live/download/{id}` therefore omits `Content-Length` for names ending in `.zip` (chunked body); with a too-small length the server aborted the body and browsers reported a cancelled download. [`tests/test_local_share.py`] - **50 MB Live Direct Transfer Safety Clamp**: - To protect low-memory mobile browser engines from memory pressure or prolonged connection hangs during live Wi-Fi streaming, a strict $50\,\text{MB}$ payload limit is enforced. Both frontend interfaces (`initiateDashSendDirect`, `initiateSendDirect`, and multi-folder staging confirm) calculate total payload size upfront and immediately warn users via friendly toast notices if exceeded. The backend WebSocket relay endpoint (`/api/share/live/ws`) additionally enforces this ceiling on `transfer-request` messages, rejecting payloads $> 50\,\text{MB}$ with a descriptive `transfer-error` response. Larger files and folders are routed to standard Local Share upload. + To protect low-memory mobile browser engines from memory pressure or prolonged connection hangs during live Wi-Fi streaming, a strict $50\,\text{MB}$ payload limit is enforced. Both frontend interfaces (`initiateDashSendDirect`, `initiateSendDirect`, and multi-folder staging confirm) calculate total payload size upfront and immediately warn users via friendly toast notices if exceeded. The backend WebSocket relay endpoint (`/api/share/live/ws`) additionally enforces this ceiling on `transfer-request` messages, rejecting payloads $> 50\,\text{MB}$ with a descriptive `transfer-error` response. Larger files and folders are routed to standard Local Share upload, subject to its storage limits. --- diff --git a/api/app.py b/api/app.py index 4c23549..c3ba48e 100644 --- a/api/app.py +++ b/api/app.py @@ -79,7 +79,10 @@ from quota.history_analytics import get_history_analytics, get_live_traffic_analytics from quota.local_share import ( MAX_LIVE_DIRECT_BYTES, + FolderUploadBusy, + FolderUploadNotFound, LocalShareManager, + ShareLimitExceeded, detect_device_name, sanitize_filename, ) @@ -1183,14 +1186,25 @@ async def list_shared_items(request: Request) -> dict[str, Any]: data["server_host"] = request.headers.get("host") or request.url.netloc or "router.local" return data + @app.exception_handler(ShareLimitExceeded) + async def _local_share_limit(_request: Request, exc: ShareLimitExceeded) -> JSONResponse: + return JSONResponse({"detail": str(exc)}, status_code=413) + + @app.exception_handler(FolderUploadNotFound) + async def _local_share_missing_folder(_request: Request, exc: FolderUploadNotFound) -> JSONResponse: + return JSONResponse({"detail": str(exc)}, status_code=404) + + @app.exception_handler(FolderUploadBusy) + async def _local_share_busy_folder(_request: Request, exc: FolderUploadBusy) -> JSONResponse: + return JSONResponse({"detail": str(exc)}, status_code=409) + @app.post("/api/share/upload", dependencies=[Depends(_require_local_share_access)]) async def upload_share_file( request: Request, ttl: int = 7200, ) -> dict[str, Any]: """Stream an uploaded file to the local share cache with automatic TTL. - Uses pure request streaming — zero dependencies on python-multipart and - minimal memory overhead for multi-gigabyte transfers. + Upload limits apply to received bytes even without Content-Length. """ raw_name = request.headers.get("x-filename") or request.query_params.get("filename") or "shared_file" try: diff --git a/quota/local_share.py b/quota/local_share.py index c6e62ae..757f459 100644 --- a/quota/local_share.py +++ b/quota/local_share.py @@ -8,11 +8,13 @@ from __future__ import annotations import asyncio +import io import json import logging import re import secrets import shutil +import threading import time import zipfile from dataclasses import dataclass @@ -25,6 +27,88 @@ MAX_TEXT_ITEMS = 50 MAX_TEXT_LENGTH = 10000 MAX_LIVE_DIRECT_BYTES = 50 * 1024 * 1024 # 50 MB +MAX_FILE_BYTES = 1024 ** 3 # 1 GiB +MAX_STORAGE_BYTES = 4 * 1024 ** 3 # 4 GiB +MIN_DISK_FREE_BYTES = 256 * 1024 ** 2 # 256 MiB +FOLDER_IDLE_SECONDS = 1800 + + +class ShareLimitExceeded(ValueError): + """The incoming data exceeds a Local Share storage limit.""" + + +class FolderUploadNotFound(ValueError): + """The folder session no longer exists.""" + + +class FolderUploadBusy(ValueError): + """An entry is already being written to this folder.""" + + +async def _disk_call(func, *args): + """Finish disk I/O before a cancelled caller closes or removes the file.""" + task = asyncio.create_task(asyncio.to_thread(func, *args)) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + await asyncio.gather(task, return_exceptions=True) + raise + + +async def _copy_upload(stream: Any, dest, max_bytes: int) -> int: + """Check the received bytes before writing each chunk.""" + async def chunks(): + if hasattr(stream, "__aiter__"): + async for chunk in stream: + yield chunk + else: + while True: + if callable(stream): + chunk = await stream(65536) + else: + chunk = await _disk_call(stream.read, 65536) + if not chunk: + break + yield chunk + + total = 0 + async for chunk in chunks(): + if chunk: + total += len(chunk) + if total > max_bytes: + raise ShareLimitExceeded("File exceeds the Local Share per-file limit") + await _disk_call(dest.write, chunk) + return total + + +class _CacheFile(io.FileIO): + """Unbuffered file that charges actual growth, including ZIP metadata.""" + + def __init__(self, owner: LocalShareManager, path: Path) -> None: + super().__init__(path, "x") + self._owner = owner + self._path = path + + def write(self, data: bytes) -> int: + owner = self._owner + with owner._storage_lock: + size = owner._storage_sizes.get(self._path, 0) + end = self.tell() + len(data) + growth = end - size + if growth > 0: + if end > owner.max_file_bytes: + raise ShareLimitExceeded("File exceeds the Local Share per-file limit") + if owner._storage_bytes + growth > owner.max_storage_bytes: + raise ShareLimitExceeded("Local Share storage limit reached") + if shutil.disk_usage(owner.storage_dir).free - growth < MIN_DISK_FREE_BYTES: + raise ShareLimitExceeded("Not enough free disk space for Local Share") + written = super().write(data) + new_size = max(size, self.tell()) + owner._storage_sizes[self._path] = new_size + owner._storage_bytes += new_size - size + if written != len(data): + raise OSError("Incomplete Local Share disk write") + return written def sanitize_filename(filename: str) -> str: @@ -103,7 +187,34 @@ def __init__(self, storage_dir: Path | str) -> None: self.texts: list[SharedText] = [] self._folder_sessions: dict[str, dict[str, Any]] = {} self.live_hub = LiveShareHub() + self.max_file_bytes = MAX_FILE_BYTES + self.max_storage_bytes = MAX_STORAGE_BYTES self._load_index() + self._storage_lock = threading.Lock() + # Include scratch payloads left behind by a previous process. + self._storage_sizes = { + path: path.stat().st_size + for path in self.storage_dir.glob("*/*") + if not path.parent.is_symlink() and not path.is_symlink() and path.is_file() + } + self._storage_bytes = sum(self._storage_sizes.values()) + + def _remove_payload(self, path: Path, *, directory: bool = False) -> None: + """Release budget for files that are no longer on disk.""" + with self._storage_lock: + try: + if directory: + shutil.rmtree(path) + else: + path.unlink() + except OSError: + if path.exists(): + log.exception("Could not remove Local Share payload %s", path) + candidates = ([p for p in self._storage_sizes if p.parent == path] + if directory else [path]) + for candidate in candidates: + if not candidate.exists(): + self._storage_bytes -= self._storage_sizes.pop(candidate, 0) def _load_index(self) -> None: """Load persisted metadata from disk.""" @@ -171,52 +282,30 @@ async def save_file_stream( file_id = secrets.token_hex(6) safe_name = sanitize_filename(filename) dest_dir = self.storage_dir / file_id - dest_dir.mkdir(parents=True, exist_ok=True) + dest_dir.mkdir() dest_file = dest_dir / safe_name - total_bytes = 0 try: - with open(dest_file, "wb") as f: - if hasattr(stream, "__aiter__"): - async for chunk in stream: - if chunk: - f.write(chunk) - total_bytes += len(chunk) - elif callable(stream): - while True: - chunk = await stream(65536) - if not chunk: - break - f.write(chunk) - total_bytes += len(chunk) - elif hasattr(stream, "read"): - while True: - chunk = stream.read(65536) - if not chunk: - break - f.write(chunk) - total_bytes += len(chunk) + with _CacheFile(self, dest_file) as f: + total_bytes = await _copy_upload(stream, f, self.max_file_bytes) + + now = time.time() + sf = SharedFile( + id=file_id, + name=safe_name, + size=total_bytes, + content_type=content_type or "application/octet-stream", + uploaded_at=now, + expires_at=now + max(60, ttl_seconds), + sender_ip=sender_ip, + ) + async with self._lock: + self.files[file_id] = sf + self._save_index() except BaseException: - # client cancelled / connection dropped: leave no half-written file behind - shutil.rmtree(dest_dir, ignore_errors=True) + self._remove_payload(dest_dir, directory=True) raise - now = time.time() - sf = SharedFile( - id=file_id, - name=safe_name, - size=total_bytes, - content_type=content_type or "application/octet-stream", - uploaded_at=now, - expires_at=now + max(60, ttl_seconds), - sender_ip=sender_ip, - download_count=0, - ) - - async with self._lock: - self.files[file_id] = sf - self._save_index() - log.info("Local share: saved '%s' (%d bytes) from %s", safe_name, total_bytes, sender_ip) return sf @@ -235,22 +324,29 @@ async def init_folder_upload( clean_name = clean_base dest_dir = self.storage_dir / folder_id - dest_dir.mkdir(parents=True, exist_ok=True) zip_path = dest_dir / clean_name - # Create writable zip file - zf = zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) - now = time.time() - async with self._lock: + dest_dir.mkdir() + try: + payload = _CacheFile(self, zip_path) + try: + zf = zipfile.ZipFile(payload, "w", compression=zipfile.ZIP_DEFLATED) + except BaseException: + payload.close() + raise + except BaseException: + self._remove_payload(dest_dir, directory=True) + raise self._folder_sessions[folder_id] = { "folder_name": clean_name, "zip_path": zip_path, "zip_file": zf, + "payload": payload, "sender_ip": sender_ip, "ttl_seconds": max(60, ttl_seconds), - "created_at": now, - "file_count": 0, + "last_activity": time.monotonic(), + "busy": False, } log.info("Local share: initiated folder archive '%s' (%s) from %s", clean_name, folder_id, sender_ip) return folder_id @@ -262,53 +358,50 @@ async def append_folder_file( stream: Any, ) -> int: """Stream a single file into the active in-progress folder ZIP archive.""" - session = self._folder_sessions.get(folder_id) - if not session: - raise ValueError(f"Folder upload session '{folder_id}' not found or already finalized") - - zf: zipfile.ZipFile = session["zip_file"] - clean_rel = sanitize_relpath(relpath) - - total_bytes = 0 - with zf.open(clean_rel, "w") as out_f: - if hasattr(stream, "__aiter__"): - async for chunk in stream: - if chunk: - out_f.write(chunk) - total_bytes += len(chunk) - elif callable(stream): - while True: - chunk = await stream(65536) - if not chunk: - break - out_f.write(chunk) - total_bytes += len(chunk) - elif hasattr(stream, "read"): - while True: - chunk = stream.read(65536) - if not chunk: - break - out_f.write(chunk) - total_bytes += len(chunk) - - session["file_count"] += 1 + session = self._get_idle_folder(folder_id) + session["busy"] = True + try: + with session["zip_file"].open(sanitize_relpath(relpath), "w") as member: + total_bytes = await _copy_upload(stream, member, self.max_file_bytes) + except BaseException: + del self._folder_sessions[folder_id] + self._discard_folder(session) + raise + session["last_activity"] = time.monotonic() + session["busy"] = False return total_bytes + def _get_idle_folder(self, folder_id: str) -> dict[str, Any]: + session = self._folder_sessions.get(folder_id) + if session is None: + raise FolderUploadNotFound("Folder upload session no longer exists") + if session["busy"]: + raise FolderUploadBusy("A file is already uploading to this folder") + return session + + def _discard_folder(self, session: dict[str, Any]) -> None: + try: + session["zip_file"].close() + except (OSError, ShareLimitExceeded): + log.debug("Could not close discarded Local Share ZIP", exc_info=True) + finally: + session["payload"].close() + self._remove_payload(session["zip_path"].parent, directory=True) + async def finalize_folder_upload(self, folder_id: str) -> SharedFile: """Close the ZIP archive, record it as a shared file item, and save index.""" async with self._lock: - session = self._folder_sessions.pop(folder_id, None) - if not session: - raise ValueError(f"Folder session '{folder_id}' not found") - - zf: zipfile.ZipFile = session["zip_file"] + session = self._get_idle_folder(folder_id) + del self._folder_sessions[folder_id] + zip_path: Path = session["zip_path"] try: - zf.close() - except Exception as exc: - log.warning("Error closing folder zip '%s': %s", folder_id, exc) + with session["payload"]: + await _disk_call(session["zip_file"].close) + total_size = zip_path.stat().st_size + except BaseException: + self._remove_payload(zip_path.parent, directory=True) + raise - zip_path: Path = session["zip_path"] - total_size = zip_path.stat().st_size if zip_path.exists() else 0 now = time.time() ttl = session["ttl_seconds"] @@ -326,9 +419,8 @@ async def finalize_folder_upload(self, folder_id: str) -> SharedFile: self._save_index() log.info( - "Local share: finalized folder '%s' (%d files, %d bytes) from %s", + "Local share: finalized folder '%s' (%d bytes) from %s", sf.name, - session["file_count"], total_size, sf.sender_ip, ) @@ -350,24 +442,29 @@ async def create_batch_zip(self, file_ids: list[str]) -> Optional[tuple[Path, st bundles_dir = self.storage_dir / "bundles" bundles_dir.mkdir(parents=True, exist_ok=True) - bundle_name = f"LocalShare_Batch_{secrets.token_hex(4)}.zip" + bundle_name = f"LocalShare_Batch_{secrets.token_hex(8)}.zip" bundle_path = bundles_dir / bundle_name - seen_names: dict[str, int] = {} - with zipfile.ZipFile(bundle_path, "w", compression=zipfile.ZIP_DEFLATED) as zf: - for fpath, fname in valid_files: - arcname = fname - if arcname in seen_names: - seen_names[arcname] += 1 - stem = Path(fname).stem - ext = Path(fname).suffix - arcname = f"{stem}_{seen_names[fname]}{ext}" - else: - seen_names[arcname] = 0 - zf.write(fpath, arcname=arcname) - + try: + await _disk_call(self._write_bundle, bundle_path, valid_files) + except FileExistsError: + raise # This request does not own the existing bundle. + except BaseException: + self._remove_payload(bundle_path) + raise return bundle_path, "LocalShare_Bundle.zip" + def _write_bundle(self, bundle_path: Path, files: list[tuple[Path, str]]) -> None: + seen_names: dict[str, int] = {} + with _CacheFile(self, bundle_path) as payload, zipfile.ZipFile( + payload, "w", compression=zipfile.ZIP_DEFLATED, + ) as zf: + for path, name in files: + count = seen_names.get(name, 0) + seen_names[name] = count + 1 + arcname = f"{Path(name).stem}_{count}{Path(name).suffix}" if count else name + zf.write(path, arcname=arcname) + async def delete_batch(self, file_ids: list[str]) -> int: """Delete multiple files in one batch operation.""" async with self._lock: @@ -389,6 +486,7 @@ async def get_file(self, file_id: str) -> Optional[tuple[Path, str, str]]: file_path = self.storage_dir / sf.id / sf.name if not file_path.exists(): del self.files[file_id] + self._remove_payload(file_path) self._save_index() return None sf.download_count += 1 @@ -399,8 +497,7 @@ async def _delete_file_internal(self, file_id: str) -> bool: if file_id in self.files: sf = self.files.pop(file_id) target_dir = self.storage_dir / sf.id - if target_dir.exists(): - shutil.rmtree(target_dir, ignore_errors=True) + self._remove_payload(target_dir, directory=True) self._save_index() return True return False @@ -452,9 +549,14 @@ async def cleanup_expired(self) -> int: for b in bundles_dir.glob("*.zip"): try: if b.stat().st_mtime < now - 1800: - b.unlink() + self._remove_payload(b) except Exception: pass + idle_cutoff = time.monotonic() - FOLDER_IDLE_SECONDS + for folder_id, session in list(self._folder_sessions.items()): + if not session["busy"] and session["last_activity"] <= idle_cutoff: + del self._folder_sessions[folder_id] + self._discard_folder(session) return count async def clear_all(self) -> None: @@ -462,8 +564,7 @@ async def clear_all(self) -> None: async with self._lock: for sf in list(self.files.values()): target_dir = self.storage_dir / sf.id - if target_dir.exists(): - shutil.rmtree(target_dir, ignore_errors=True) + self._remove_payload(target_dir, directory=True) self.files.clear() self.texts.clear() self._save_index() diff --git a/tests/test_local_share.py b/tests/test_local_share.py index dd8db16..a99c5ba 100644 --- a/tests/test_local_share.py +++ b/tests/test_local_share.py @@ -4,15 +4,18 @@ import asyncio import io +import shutil import time import zipfile from datetime import datetime from zoneinfo import ZoneInfo +import httpx import pytest from fastapi.testclient import TestClient from api.app import create_app +from core.config import WafConfig from quota import db as _db from quota.engine import SnapshotHolder from quota.local_share import LocalShareManager, sanitize_filename @@ -126,6 +129,7 @@ async def _init(): service=service, holder=holder, local_share_manager=share_mgr, + waf_config=WafConfig(local_subnets=["192.168.1.0/24"]), ) with TestClient(app, client=("192.168.1.100", 50000)) as c: @@ -720,3 +724,207 @@ async def dropped(): assert [p for p in (tmp_path / "share_data").rglob("big.bin")] == [] asyncio.run(_test()) + + +def test_lan_upload_rejects_file_over_limit(share_client): + client, share = share_client + share.max_file_bytes = 8 + + response = client.post("/api/share/upload", content=b"123456789") + + assert response.status_code == 413 + assert list(share.storage_dir.iterdir()) == [] + assert client.post("/api/share/upload", content=b"12345678").status_code == 200 + + +def test_lan_upload_rejects_when_existing_files_fill_cache(share_client): + client, share = share_client + share.max_storage_bytes = 10 + first = client.post("/api/share/upload", content=b"12345678") + file_id = first.json()["file"]["id"] + + response = client.post("/api/share/upload", content=b"abc") + + assert response.status_code == 413 + assert client.get(f"/api/share/download/{file_id}").content == b"12345678" + assert {path.name for path in share.storage_dir.iterdir()} == {file_id, "index.json"} + assert client.delete(f"/api/share/files/{file_id}").status_code == 200 + assert client.post("/api/share/upload", content=b"abc").status_code == 200 + + +@pytest.mark.parametrize("limit", ["max_file_bytes", "max_storage_bytes"]) +def test_lan_stream_rejects_after_writing_first_chunk(share_client, limit): + client, share = share_client + setattr(share, limit, 8) + + # The ASGI transport delivers separate body events to the real middleware and route. + async def stream(): + yield b"12345" + partial, = share.storage_dir.glob("*/*") + assert partial.is_file() + yield b"6789" + + async def upload(): + transport = httpx.ASGITransport(app=client.app, client=("192.168.1.100", 50000)) + async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as lan: + request = lan.build_request("POST", "/api/share/upload", content=stream()) + assert "content-length" not in request.headers + return await lan.send(request) + + response = asyncio.run(upload()) + + assert response.status_code == 413 + assert list(share.storage_dir.iterdir()) == [] + assert client.post("/api/share/upload", content=b"12345678").status_code == 200 + + +def test_concurrent_uploads_share_the_same_budget(share_client): + client, share = share_client + share.max_storage_bytes = 8 + + async def upload(): + partial_ready = asyncio.Event() + finish_first = asyncio.Event() + + async def first_body(): + yield b"12345" + partial_ready.set() + await finish_first.wait() + yield b"678" + + transport = httpx.ASGITransport(app=client.app, client=("192.168.1.100", 50000)) + async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as lan: + first = asyncio.create_task(lan.post("/api/share/upload", content=first_body())) + try: + await partial_ready.wait() + second = await lan.post("/api/share/upload", content=b"abcd") + finally: + finish_first.set() + first_response = await first + return first_response, second + + first, second = asyncio.run(upload()) + + assert first.status_code == 200 + assert second.status_code == 413 + assert client.get("/api/share/list").json()["total_size"] == 8 + + +def test_folder_member_over_limit_discards_incomplete_archive(share_client): + client, share = share_client + share.max_file_bytes = 8 + folder_id = client.post("/api/share/folder/init", json={}).json()["folder_id"] + + response = client.post( + "/api/share/folder/file", + params={"folder_id": folder_id, "path": "file.txt"}, + content=b"123456789", + ) + + assert response.status_code == 413 + assert not (share.storage_dir / folder_id).exists() + assert client.get("/api/share/list").json()["files"] == [] + + +def test_folder_archive_over_budget_on_finalize_is_removed(share_client): + client, share = share_client + share.max_storage_bytes = 100 + folder_id = client.post("/api/share/folder/init", json={}).json()["folder_id"] + member = client.post( + "/api/share/folder/file", + params={"folder_id": folder_id, "path": "a.txt"}, + content=b"abc", + ) + assert member.status_code == 200 + + response = client.post("/api/share/folder/finalize", json={"folder_id": folder_id}) + + assert response.status_code == 413 + assert not (share.storage_dir / folder_id).exists() + assert client.get("/api/share/list").json()["files"] == [] + + +def test_batch_zip_respects_cache_budget(share_client): + client, share = share_client + share.max_storage_bytes = 20 + upload = client.post("/api/share/upload", content=b"12345678") + file_id = upload.json()["file"]["id"] + + response = client.get("/api/share/download-zip", params={"ids": file_id}) + + assert response.status_code == 413 + assert list((share.storage_dir / "bundles").glob("*.zip")) == [] + assert client.get(f"/api/share/download/{file_id}").content == b"12345678" + + +def test_existing_cache_payloads_count_after_restart(tmp_path): + existing = tmp_path / "restart" / "old-upload" + existing.mkdir(parents=True) + (existing / "file.bin").write_bytes(b"12345678") + reopened = LocalShareManager(existing.parent) + reopened.max_storage_bytes = 10 + stream = io.BytesIO(b"abc") + + with pytest.raises(ValueError, match="storage limit"): + asyncio.run(reopened.save_file_stream(stream, "new.bin", "application/octet-stream", "192.168.1.100")) + + assert list(existing.parent.iterdir()) == [existing] + + +def test_upload_rejects_when_it_would_use_reserved_disk_space(share_client, monkeypatch): + client, share = share_client + disk_usage = shutil.disk_usage(share.storage_dir) + available = 256 * 1024 ** 2 + 4 + monkeypatch.setattr( + "quota.local_share.shutil.disk_usage", + lambda _path: disk_usage._replace(free=available), + ) + + response = client.post("/api/share/upload", content=b"12345") + + assert response.status_code == 413 + assert list(share.storage_dir.iterdir()) == [] + + +def test_cancelled_stream_releases_partial_file_budget(tmp_path): + async def upload(): + share = LocalShareManager(tmp_path) + share.max_storage_bytes = 8 + partial_ready = asyncio.Event() + + async def stream(): + yield b"12345" + partial_ready.set() + await asyncio.Future() + + task = asyncio.create_task( + share.save_file_stream(stream(), "partial.bin", "application/octet-stream", "192.168.1.100") + ) + await partial_ready.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert list(tmp_path.iterdir()) == [] + + saved = await share.save_file_stream( + io.BytesIO(b"12345678"), "complete.bin", "application/octet-stream", "192.168.1.100" + ) + assert saved.size == 8 + + asyncio.run(upload()) + + +def test_cleanup_removes_abandoned_folder_archive(share_client, monkeypatch): + client, share = share_client + folder_id = client.post("/api/share/folder/init", json={}).json()["folder_id"] + member = client.post( + "/api/share/folder/file", + params={"folder_id": folder_id, "path": "a.txt"}, + content=b"abc", + ) + assert member.status_code == 200 + monkeypatch.setattr("quota.local_share.FOLDER_IDLE_SECONDS", 0, raising=False) + + assert client.get("/api/share/list").status_code == 200 + assert not (share.storage_dir / folder_id).exists() + assert client.post("/api/share/folder/finalize", json={"folder_id": folder_id}).status_code == 404