Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(files): add file upload API (#801)

Call White7677ec11b4a9
diff --git a/core/file_browser_service.py b/core/file_browser_service.py
index 0c44fd36d..586b6e6d4 100644
--- a/core/file_browser_service.py
+++ b/core/file_browser_service.py
@@ -17,7 +17,7 @@ import time
import uuid
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Callable
+from typing import Any, BinaryIO, Callable
logger = logging.getLogger(__name__)
@@ -59,6 +59,9 @@ _RENAME_NOREPLACE_FALLBACK_WARNED = False
_WRITE_LOCKS_MUTEX = threading.Lock()
_WRITE_LOCKS: dict[str, threading.Lock] = {}
_WRITE_TEMP_PREFIX = ".avibe-write-"
+_UPLOAD_CHUNK_BYTES = 1024 * 1024
+_NO_REPLACE_UNSUPPORTED_ERRNOS = {errno.ENOSYS, errno.EINVAL, errno.ENOTSUP, errno.EOPNOTSUPP}
+_HARD_LINK_UNSUPPORTED_ERRNOS = {errno.EPERM, errno.EXDEV, errno.ENOTSUP, errno.EOPNOTSUPP}
class FileBrowserError(Exception):
@@ -273,6 +276,32 @@ def _remove_created_hard_link(target: Path, source: Path) -> None:
def _glibc_renameat2_noreplace(source: Path, target: Path) -> None:
+ _glibc_renameat2_noreplace_between(
+ _AT_FDCWD,
+ os.fsencode(source),
+ _AT_FDCWD,
+ os.fsencode(target),
+ str(target),
+ )
+
+
+def _glibc_renameat2_noreplace_at(dir_fd: int, source_name: str, target_name: str) -> None:
+ _glibc_renameat2_noreplace_between(
+ dir_fd,
+ os.fsencode(source_name),
+ dir_fd,
+ os.fsencode(target_name),
+ target_name,
+ )
+
+
+def _glibc_renameat2_noreplace_between(
+ source_dir_fd: int,
+ source_name: bytes,
+ target_dir_fd: int,
+ target_name: bytes,
+ target_for_error: str,
+) -> None:
if sys.platform != "linux":
raise AttributeError("renameat2 is only available on Linux")
libc = ctypes.CDLL(None, use_errno=True)
@@ -286,17 +315,17 @@ def _glibc_renameat2_noreplace(source: Path, target: Path) -> None:
]
renameat2.restype = ctypes.c_int
result = renameat2(
- _AT_FDCWD,
- os.fsencode(source),
- _AT_FDCWD,
- os.fsencode(target),
+ source_dir_fd,
+ source_name,
+ target_dir_fd,
+ target_name,
_RENAME_NOREPLACE,
)
if result != 0:
err = ctypes.get_errno()
if err == errno.EEXIST:
- raise FileExistsError(err, os.strerror(err), str(target))
- raise OSError(err, os.strerror(err), str(target))
+ raise FileExistsError(err, os.strerror(err), target_for_error)
+ raise OSError(err, os.strerror(err), target_for_error)
def _warn_rename_noreplace_fallback() -> None:
@@ -659,11 +688,267 @@ def _validate_new_name(new_name: str) -> str:
if not isinstance(new_name, str) or not new_name.strip():
raise FileBrowserError("invalid_name", "New name is required", 400)
name = new_name.strip()
- if name in {".", ".."} or "/" in name or "\\" in name or Path(name).name != name:
+ if "\x00" in name or name in {".", ".."} or "/" in name or "\\" in name or Path(name).name != name:
raise FileBrowserError("invalid_name", "New name must not contain path separators", 400)
return name
+def _resolve_upload_directory(raw_dir: str) -> Path:
+ try:
+ resolve_safe_path(raw_dir)
+ expanded = _expanded_absolute_path(raw_dir)
+ except FileBrowserError as exc:
+ raise NotFoundError("Destination directory not found") from exc
+
+ if expanded.parent == expanded:
+ directory = expanded
+ else:
+ if expanded.name in {"", ".", ".."} or _raw_final_component(raw_dir) in {".", ".."}:
+ raise NotFoundError("Destination directory not found")
+ try:
+ parent = expanded.parent.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise NotFoundError("Destination directory not found") from exc
+ except (OSError, RuntimeError, ValueError) as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ directory = parent / expanded.name
+
+ try:
+ stat_result = directory.lstat()
+ except FileNotFoundError as exc:
+ raise NotFoundError("Destination directory not found") from exc
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ if not stat.S_ISDIR(stat_result.st_mode):
+ raise FileBrowserError("not_dir", "Destination is not a directory", 400)
+ return directory
+
+
+def _open_stable_upload_directory(directory: Path) -> int | None:
+ """Pin the validated destination directory with an fd where the platform can.
+
+ The fd keeps the whole streaming window (validate → temp → publish) inside the
+ directory inode that was validated, so a writable-parent swap cannot redirect the
+ upload. On platforms that cannot open a directory fd (native Windows), return
+ ``None`` — the upload then operates path-based with no-follow re-checks, the same
+ stability level as the sibling list/write/rename mutations there.
+ """
+ try:
+ expected = directory.lstat()
+ except FileNotFoundError as exc:
+ raise NotFoundError("Destination directory not found") from exc
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ if not stat.S_ISDIR(expected.st_mode):
+ raise FileBrowserError("not_dir", "Destination is not a directory", 400)
+
+ if os.name != "posix":
+ return None
+
+ flags = os.O_RDONLY
+ if hasattr(os, "O_DIRECTORY"):
+ flags |= os.O_DIRECTORY
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ fd = -1
+ try:
+ fd = os.open(directory, flags)
+ current = os.fstat(fd)
+ if (
+ not stat.S_ISDIR(current.st_mode)
+ or (current.st_dev, current.st_ino) != (expected.st_dev, expected.st_ino)
+ ):
+ raise FileBrowserError("not_dir", "Destination is not a directory", 400)
+ return fd
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ if exc.errno in {errno.ELOOP, errno.ENOTDIR}:
+ raise FileBrowserError("not_dir", "Destination is not a directory", 400) from exc
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ except Exception:
+ if fd >= 0:
+ os.close(fd)
+ raise
+
+
+# Errnos meaning "this filesystem cannot hard-link" (FAT/exFAT, SMB/CIFS, some NFS):
+# fall back to the guarded non-atomic publish below. EPERM is included because CIFS
+# reports link refusal as EPERM; a genuine permission problem then surfaces from the
+# fallback's replace with the right error anyway.
+_LINK_UNSUPPORTED_ERRNOS = {errno.ENOSYS, errno.EINVAL, errno.ENOTSUP, errno.EOPNOTSUPP, errno.EPERM}
+
+
+def _upload_entry_ref(dir_fd: int | None, directory: Path, name: str) -> str:
+ """Name to pass to os.* alongside ``dir_fd``: relative when pinned, absolute when not."""
+ return name if dir_fd is not None else str(directory / name)
+
+
+def _validate_upload_target_at(dir_fd: int | None, directory: Path, target_name: str, *, overwrite: bool) -> int | None:
+ try:
+ stat_result = os.stat(_upload_entry_ref(dir_fd, directory, target_name), dir_fd=dir_fd, follow_symlinks=False)
+ except FileNotFoundError:
+ return None
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ if not overwrite or not stat.S_ISREG(stat_result.st_mode):
+ raise ConflictError("exists", "Destination already exists")
+ return stat.S_IMODE(stat_result.st_mode)
+
+
+def _create_upload_temp_at(dir_fd: int | None, directory: Path) -> tuple[int, str]:
+ flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ for _ in range(100):
+ temp_name = f"{_WRITE_TEMP_PREFIX}{uuid.uuid4().hex}.tmp"
+ try:
+ return os.open(_upload_entry_ref(dir_fd, directory, temp_name), flags, 0o666, dir_fd=dir_fd), temp_name
+ except FileExistsError:
+ continue
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ raise FileBrowserError("fs_error", "Could not reserve upload temp file", 400)
+
+
+def _publish_upload_temp_at(
+ dir_fd: int | None, directory: Path, temp_name: str, target_name: str, *, overwrite: bool
+) -> None:
+ temp_ref = _upload_entry_ref(dir_fd, directory, temp_name)
+ target_ref = _upload_entry_ref(dir_fd, directory, target_name)
+ if overwrite:
+ os.replace(temp_ref, target_ref, src_dir_fd=dir_fd, dst_dir_fd=dir_fd)
+ return
+ # Create-only publish ladder, mirroring _os_rename_noreplace's policy: hard link is
+ # the atomic no-replace primitive where the filesystem has one; where it doesn't
+ # (FAT/exFAT/SMB), degrade to a guarded check+replace with the same warning the
+ # rename fallback emits. renameat2(RENAME_NOREPLACE) is not a useful middle rung
+ # here: filesystems that refuse link() refuse its flags too.
+ try:
+ os.link(temp_ref, target_ref, src_dir_fd=dir_fd, dst_dir_fd=dir_fd, follow_symlinks=False)
+ except FileExistsError as exc:
+ raise ConflictError("exists", "Destination already exists") from exc
+ except OSError as exc:
+ if exc.errno not in _LINK_UNSUPPORTED_ERRNOS:
+ raise
+ _warn_rename_noreplace_fallback()
+ try:
+ os.stat(target_ref, dir_fd=dir_fd, follow_symlinks=False)
+ except FileNotFoundError:
+ pass
+ else:
+ raise ConflictError("exists", "Destination already exists") from exc
+ os.replace(temp_ref, target_ref, src_dir_fd=dir_fd, dst_dir_fd=dir_fd)
+ return
+ _unlink_upload_temp_after_link(dir_fd, directory, temp_name, target_name)
+
+
+def _unlink_upload_temp_after_link(dir_fd: int | None, directory: Path, temp_name: str, target_name: str) -> None:
+ try:
+ os.unlink(_upload_entry_ref(dir_fd, directory, temp_name), dir_fd=dir_fd)
+ except OSError:
+ _remove_created_upload_link_at(dir_fd, directory, temp_name, target_name)
+ raise
+
+
+def _remove_created_upload_link_at(dir_fd: int | None, directory: Path, temp_name: str, target_name: str) -> None:
+ try:
+ temp_stat = os.stat(_upload_entry_ref(dir_fd, directory, temp_name), dir_fd=dir_fd, follow_symlinks=False)
+ target_stat = os.stat(_upload_entry_ref(dir_fd, directory, target_name), dir_fd=dir_fd, follow_symlinks=False)
+ if (temp_stat.st_dev, temp_stat.st_ino) == (target_stat.st_dev, target_stat.st_ino):
+ os.unlink(_upload_entry_ref(dir_fd, directory, target_name), dir_fd=dir_fd)
+ except OSError:
+ logger.debug("Failed to remove rollback upload hard link after temp unlink failure", exc_info=True)
+
+
+def upload_file(
+ raw_dir: str,
+ source: BinaryIO,
+ *,
+ filename: str | None = None,
+ name: str | None = None,
+ overwrite: bool = False,
+) -> dict[str, Any]:
+ directory = _resolve_upload_directory(raw_dir)
+ target_name = _validate_new_name(name if name is not None and name.strip() else (filename or ""))
+ target = directory / target_name
+ dir_fd = _open_stable_upload_directory(directory)
+ try:
+ _validate_upload_target_at(dir_fd, directory, target_name, overwrite=overwrite)
+
+ def _upload() -> dict[str, Any]:
+ with _write_lock_for(target):
+ current_mode = _validate_upload_target_at(dir_fd, directory, target_name, overwrite=overwrite)
+ fd = -1
+ temp_name = ""
+ size = 0
+ try:
+ fd, temp_name = _create_upload_temp_at(dir_fd, directory)
+ if current_mode is not None and hasattr(os, "fchmod"):
+ os.fchmod(fd, current_mode)
+ with os.fdopen(fd, "wb") as handle:
+ fd = -1
+ while True:
+ chunk = source.read(_UPLOAD_CHUNK_BYTES)
+ if not chunk:
+ break
+ if not isinstance(chunk, bytes):
+ chunk = bytes(chunk)
+ if size + len(chunk) > MAX_FILE_BYTES:
+ raise FileBrowserError("too_large", "File is too large", 413)
+ handle.write(chunk)
+ size += len(chunk)
+ handle.flush()
+ os.fsync(handle.fileno())
+ _publish_upload_temp_at(dir_fd, directory, temp_name, target_name, overwrite=overwrite)
+ temp_name = ""
+ if dir_fd is not None:
+ try:
+ os.fsync(dir_fd)
+ except OSError:
+ pass
+ else:
+ _fsync_dir(directory)
+ stat_result = os.stat(
+ _upload_entry_ref(dir_fd, directory, target_name), dir_fd=dir_fd, follow_symlinks=False
+ )
+ return {
+ "name": target.name,
+ "path": str(target),
+ "size": stat_result.st_size,
+ "mtime": _mtime_seconds(stat_result),
+ }
+ except FileExistsError as exc:
+ raise ConflictError("exists", "Destination already exists") from exc
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ finally:
+ if fd >= 0:
+ os.close(fd)
+ if temp_name:
+ try:
+ os.unlink(_upload_entry_ref(dir_fd, directory, temp_name), dir_fd=dir_fd)
+ except FileNotFoundError:
+ pass
+ except OSError:
+ logger.debug("Failed to clean up upload temp file", exc_info=True)
+
+ return _run_mutation("upload", target, _upload, overwrite=overwrite)
+ finally:
+ if dir_fd is not None:
+ os.close(dir_fd)
+
+
def rename_path(raw_path: str, new_name: str) -> dict[str, Any]:
source = _resolve_existing_entry_path(raw_path)
name = _validate_new_name(new_name)
diff --git a/tests/test_file_browser_backend.py b/tests/test_file_browser_backend.py
index 7cd90c517..205abf23d 100644
--- a/tests/test_file_browser_backend.py
+++ b/tests/test_file_browser_backend.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import errno
+import io
import logging
import os
import sys
@@ -10,8 +11,9 @@ from pathlib import Path
import pytest
+from vibe import ui_server
from core import file_browser_service as fs
-from core.file_browser_service import FileBrowserError
+from core.file_browser_service import ConflictError, FileBrowserError
from tests.ui_server_test_helpers import csrf_headers
from vibe.ui_server import app
@@ -535,6 +537,217 @@ def test_write_serializes_expected_mtime_check_and_replace(tmp_path, monkeypatch
assert path.read_text(encoding="utf-8") == "first"
+def test_upload_file_happy_path_and_name_override(tmp_path):
+ result = fs.upload_file(str(tmp_path), io.BytesIO(b"hello"), filename="ignored.txt", name="saved.bin")
+
+ uploaded = tmp_path / "saved.bin"
+ assert result["name"] == "saved.bin"
+ assert result["path"] == str(uploaded)
+ assert result["size"] == 5
+ assert result["mtime"] == fs._mtime_seconds(uploaded.stat())
+ assert uploaded.read_bytes() == b"hello"
+
+
+def test_upload_file_conflict_without_overwrite_and_replaces_with_overwrite(tmp_path):
+ target = tmp_path / "report.bin"
+ target.write_bytes(b"old")
+ target.chmod(0o744)
+
+ with pytest.raises(FileBrowserError) as exists:
+ fs.upload_file(str(tmp_path), io.BytesIO(b"new"), filename="report.bin")
+ assert exists.value.code == "exists"
+ assert target.read_bytes() == b"old"
+
+ result = fs.upload_file(str(tmp_path), io.BytesIO(b"new"), filename="report.bin", overwrite=True)
+
+ assert result["name"] == "report.bin"
+ assert result["size"] == 3
+ assert target.read_bytes() == b"new"
+ assert target.stat().st_mode & 0o777 == 0o744
+
+
+def test_upload_new_file_does_not_bypass_restrictive_umask(tmp_path):
+ old_umask = os.umask(0o022)
+ try:
+ shared = fs.upload_file(str(tmp_path), io.BytesIO(b"shared"), filename="shared.bin")
+ finally:
+ os.umask(old_umask)
+
+ shared_upload = Path(shared["path"])
+ assert shared_upload.read_bytes() == b"shared"
+ assert shared_upload.stat().st_mode & 0o777 == 0o644
+
+ old_umask = os.umask(0o077)
+ try:
+ private = fs.upload_file(str(tmp_path), io.BytesIO(b"private"), filename="private.bin")
+ finally:
+ os.umask(old_umask)
+
+ private_upload = Path(private["path"])
+ assert private_upload.read_bytes() == b"private"
+ assert private_upload.stat().st_mode & 0o777 == 0o600
+
+
+def test_upload_uses_stable_directory_after_validation(tmp_path, monkeypatch):
+ upload_dir = tmp_path / "uploads"
+ upload_dir.mkdir()
+ attacker_dir = tmp_path / "attacker"
+ attacker_dir.mkdir()
+ moved_upload_dir = tmp_path / "uploads-original"
+ real_open_directory = fs._open_stable_upload_directory
+
+ def open_then_swap(directory: Path) -> int:
+ fd = real_open_directory(directory)
+ upload_dir.rename(moved_upload_dir)
+ upload_dir.symlink_to(attacker_dir, target_is_directory=True)
+ return fd
+
+ monkeypatch.setattr(fs, "_open_stable_upload_directory", open_then_swap)
+
+ result = fs.upload_file(str(upload_dir), io.BytesIO(b"safe"), filename="safe.bin")
+
+ assert result["path"] == str(upload_dir / "safe.bin")
+ assert (moved_upload_dir / "safe.bin").read_bytes() == b"safe"
+ assert not (attacker_dir / "safe.bin").exists()
+
+
+def test_upload_create_only_falls_back_when_hard_links_unsupported(tmp_path, monkeypatch):
+ # FAT/exFAT/SMB-style filesystems refuse os.link; create-only publish must degrade to
+ # the guarded replace instead of failing the upload outright.
+ def refuse_link(*args, **kwargs):
+ raise OSError(errno.EOPNOTSUPP, "Operation not supported")
+
+ monkeypatch.setattr(fs.os, "link", refuse_link)
+
+ result = fs.upload_file(str(tmp_path), io.BytesIO(b"payload"), filename="fallback.bin")
+ uploaded = tmp_path / "fallback.bin"
+ assert result["path"] == str(uploaded)
+ assert uploaded.read_bytes() == b"payload"
+ assert not list(tmp_path.glob(f"{fs._WRITE_TEMP_PREFIX}*.tmp"))
+
+ # The fallback still refuses to replace an existing target (create-only contract).
+ with pytest.raises(ConflictError) as exc:
+ fs.upload_file(str(tmp_path), io.BytesIO(b"other"), filename="fallback.bin")
+ assert exc.value.code == "exists"
+ assert uploaded.read_bytes() == b"payload"
+ assert not list(tmp_path.glob(f"{fs._WRITE_TEMP_PREFIX}*.tmp"))
+
+
[email protected](os.name != "posix" or os.geteuid() == 0, reason="requires POSIX non-root permissions")
+def test_upload_permission_denied_maps_to_403(tmp_path):
+ read_only = tmp_path / "readonly"
+ read_only.mkdir()
+ read_only.chmod(0o555)
+ try:
+ with pytest.raises(FileBrowserError) as exc:
+ fs.upload_file(str(read_only), io.BytesIO(b"x"), filename="denied.bin")
+ assert exc.value.code == "permission_denied"
+ assert exc.value.status_code == 403
+ assert list(read_only.iterdir()) == []
+ finally:
+ read_only.chmod(0o755)
+
+
+def test_upload_works_without_directory_fd(tmp_path, monkeypatch):
+ # Platforms that cannot open a directory fd (native Windows) degrade to path-based
+ # operation; the upload and its create-only contract must still work there.
+ monkeypatch.setattr(fs, "_open_stable_upload_directory", lambda directory: None)
+
+ result = fs.upload_file(str(tmp_path), io.BytesIO(b"portable"), filename="nofd.bin")
+ uploaded = tmp_path / "nofd.bin"
+ assert result["path"] == str(uploaded)
+ assert uploaded.read_bytes() == b"portable"
+ assert result["mtime"] == fs._mtime_seconds(uploaded.stat())
+
+ with pytest.raises(ConflictError) as exc:
+ fs.upload_file(str(tmp_path), io.BytesIO(b"clash"), filename="nofd.bin")
+ assert exc.value.code == "exists"
+
+ replaced = fs.upload_file(str(tmp_path), io.BytesIO(b"replaced"), filename="nofd.bin", overwrite=True)
+ assert replaced["size"] == len(b"replaced")
+ assert uploaded.read_bytes() == b"replaced"
+ assert not list(tmp_path.glob(f"{fs._WRITE_TEMP_PREFIX}*.tmp"))
+
+
+def test_upload_file_size_cap_cleans_temp_and_target(tmp_path, monkeypatch):
+ monkeypatch.setattr(fs, "MAX_FILE_BYTES", 4)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.upload_file(str(tmp_path), io.BytesIO(b"12345"), filename="large.bin")
+
+ assert exc.value.code == "too_large"
+ assert exc.value.status_code == 413
+ assert not (tmp_path / "large.bin").exists()
+ assert not list(tmp_path.glob(f"{fs._WRITE_TEMP_PREFIX}*.tmp"))
+
+
+ "bad_name",
+ ["../escape.txt", "nested/file.txt", "nested\\file.txt", ".", "..", "", "nul\x00byte.txt"],
+)
+def test_upload_file_rejects_invalid_names(tmp_path, bad_name):
+ with pytest.raises(FileBrowserError) as exc:
+ fs.upload_file(str(tmp_path), io.BytesIO(b"x"), filename=bad_name)
+
+ assert exc.value.code == "invalid_name"
+ assert list(tmp_path.iterdir()) == []
+
+
+def test_upload_file_rejects_bad_destination_dir(tmp_path):
+ missing = tmp_path / "missing"
+ with pytest.raises(FileBrowserError) as missing_exc:
+ fs.upload_file(str(missing), io.BytesIO(b"x"), filename="upload.bin")
+ assert missing_exc.value.code == "not_found"
+
+ destination_file = tmp_path / "not-a-dir"
+ destination_file.write_text("x", encoding="utf-8")
+ with pytest.raises(FileBrowserError) as file_exc:
+ fs.upload_file(str(destination_file), io.BytesIO(b"x"), filename="upload.bin")
+ assert file_exc.value.code == "not_dir"
+
+
+def test_upload_file_refuses_symlinked_dir_and_target_symlink(tmp_path):
+ real_dir = tmp_path / "real"
+ real_dir.mkdir()
+ link_dir = tmp_path / "link-dir"
+ link_dir.symlink_to(real_dir, target_is_directory=True)
+
+ with pytest.raises(FileBrowserError) as dir_exc:
+ fs.upload_file(str(link_dir), io.BytesIO(b"x"), filename="upload.bin")
+ assert dir_exc.value.code == "not_dir"
+ assert not (real_dir / "upload.bin").exists()
+
+ target = tmp_path / "target.bin"
+ target.write_bytes(b"target")
+ link = tmp_path / "link.bin"
+ link.symlink_to(target)
+
+ with pytest.raises(FileBrowserError) as target_exc:
+ fs.upload_file(str(tmp_path), io.BytesIO(b"new"), filename="link.bin", overwrite=True)
+ assert target_exc.value.code == "exists"
+ assert link.is_symlink()
+ assert target.read_bytes() == b"target"
+
+
+def test_upload_file_read_failure_leaves_no_partial_file(tmp_path):
+ class FailingStream:
+ def __init__(self) -> None:
+ self.calls = 0
+
+ def read(self, _size: int) -> bytes:
+ self.calls += 1
+ if self.calls == 1:
+ return b"partial"
+ raise OSError("read failed")
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.upload_file(str(tmp_path), FailingStream(), filename="partial.bin")
+
+ assert exc.value.code == "fs_error"
+ assert not (tmp_path / "partial.bin").exists()
+ assert not list(tmp_path.glob(f"{fs._WRITE_TEMP_PREFIX}*.tmp"))
+
+
def test_mutating_ops_mkdir_rename_move_delete(tmp_path, caplog):
caplog.set_level(logging.INFO, logger="core.file_browser_service")
folder = tmp_path / "folder"
@@ -1152,6 +1365,119 @@ def test_http_routes_return_contract_and_headers(tmp_path):
download_response = client.get(f"/api/files/content?path={file_path}&download=1")
assert download_response.headers["Content-Disposition"].startswith("attachment;")
+ upload_response = client.post(
+ "/api/files/upload",
+ data={"dir": str(tmp_path), "name": "uploaded.bin"},
+ files={"file": ("browser-name.bin", b"upload", "application/octet-stream")},
+ headers=csrf_headers(client),
+ )
+ assert upload_response.status_code == 200
+ upload_body = upload_response.get_json()
+ assert set(upload_body) == {"name", "path", "size", "mtime"}
+ assert upload_body["name"] == "uploaded.bin"
+ assert upload_body["size"] == 6
+ assert (tmp_path / "uploaded.bin").read_bytes() == b"upload"
+
+
+def test_http_upload_maps_too_large_and_leaves_no_partial(tmp_path, monkeypatch):
+ monkeypatch.setattr(fs, "MAX_FILE_BYTES", 4)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/files/upload",
+ data={"dir": str(tmp_path)},
+ files={"file": ("large.bin", b"12345", "application/octet-stream")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 413
+ assert response.get_json() == {
+ "ok": False,
+ "error": {"code": "too_large", "message": "File is too large"},
+ }
+ assert not (tmp_path / "large.bin").exists()
+ assert not list(tmp_path.glob(f"{fs._WRITE_TEMP_PREFIX}*.tmp"))
+
+
+def test_http_upload_rejects_oversized_content_length_before_parsing(tmp_path, monkeypatch):
+ monkeypatch.setattr(fs, "MAX_FILE_BYTES", 4)
+ monkeypatch.setattr(ui_server, "_FILE_UPLOAD_MULTIPART_OVERHEAD_BYTES", 0)
+
+ def boom_upload(*_args, **_kwargs):
+ raise AssertionError("oversized upload should be rejected before form parsing")
+
+ monkeypatch.setattr(fs, "upload_file", boom_upload)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/files/upload",
+ data={"dir": str(tmp_path)},
+ files={"file": ("large.bin", b"12345", "application/octet-stream")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 413
+ assert response.get_json()["error"]["code"] == "too_large"
+ assert not (tmp_path / "large.bin").exists()
+
+
+def test_http_upload_allows_missing_content_length():
+ ui_server._validate_file_upload_content_length({}, 4)
+
+
+def test_http_upload_parser_caps_file_part_before_service(tmp_path, monkeypatch):
+ monkeypatch.setattr(fs, "MAX_FILE_BYTES", 4)
+
+ def boom_upload(*_args, **_kwargs):
+ raise AssertionError("oversized multipart file should be rejected before service write")
+
+ monkeypatch.setattr(fs, "upload_file", boom_upload)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/files/upload",
+ data={"dir": str(tmp_path)},
+ files={"file": ("large.bin", b"12345", "application/octet-stream")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 413
+ assert response.get_json()["error"]["code"] == "too_large"
+ assert not (tmp_path / "large.bin").exists()
+
+
+def test_http_upload_missing_file_part_returns_structured_error(tmp_path):
+ client = app.test_client()
+
+ response = client.post(
+ "/api/files/upload",
+ data={"dir": str(tmp_path)},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json() == {
+ "ok": False,
+ "error": {"code": "invalid_name", "message": "File is required"},
+ }
+
+
+def test_http_upload_overwrite_string_true_replaces_target(tmp_path):
+ target = tmp_path / "replace.bin"
+ target.write_bytes(b"old")
+ client = app.test_client()
+
+ response = client.post(
+ "/api/files/upload",
+ data={"dir": str(tmp_path), "overwrite": "true"},
+ files={"file": ("replace.bin", b"new", "application/octet-stream")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert response.get_json()["name"] == "replace.bin"
+ assert target.read_bytes() == b"new"
+
def test_http_routes_map_structured_errors_and_enforce_csrf(tmp_path):
client = app.test_client()
@@ -1166,6 +1492,15 @@ def test_http_routes_map_structured_errors_and_enforce_csrf(tmp_path):
blocked = client.put("/api/files/write", json={"path": str(write_path), "content": "x"})
assert blocked.status_code == 403
+ upload_path = tmp_path / "blocked-upload.bin"
+ blocked_upload = client.post(
+ "/api/files/upload",
+ data={"dir": str(tmp_path)},
+ files={"file": ("blocked-upload.bin", b"x", "application/octet-stream")},
+ )
+ assert blocked_upload.status_code == 403
+ assert not upload_path.exists()
+
ok = client.put(
"/api/files/write",
json={"path": str(write_path), "content": "x"},
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 1d60e43b1..96db76e43 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4,6 +4,7 @@ import gzip
import hashlib
import hmac
import html
+import inspect
import ipaddress
import json
import logging
@@ -28,6 +29,9 @@ import psutil
from aiohttp import ClientSession, WSMsgType
from fastapi import Request as FastAPIRequest, WebSocket, WebSocketDisconnect
from fastapi.responses import Response as FastAPIResponse
+from starlette.datastructures import UploadFile as StarletteUploadFile
+from starlette.exceptions import HTTPException as StarletteHTTPException
+from starlette.formparsers import MultiPartException, MultiPartParser
from vibe.ui_compat import CompatApp, Response, TEST_REMOTE_ADDR_HEADER, g, jsonify, redirect, request, send_file
@@ -5807,6 +5811,74 @@ def _file_browser_error_response(exc: Exception):
return jsonify({"ok": False, "error": {"code": "internal_error", "message": "Internal server error"}}), 500
+_FILE_UPLOAD_MULTIPART_OVERHEAD_BYTES = 1024 * 1024
+_FILE_UPLOAD_FIELD_MAX_BYTES = 4096
+
+
+def _validate_file_upload_content_length(headers: Any, max_file_bytes: int) -> None:
+ from core.file_browser_service import FileBrowserError
+
+ raw_length = headers.get("content-length")
+ if raw_length is None:
+ return
+ try:
+ length = int(raw_length)
+ except (TypeError, ValueError) as exc:
+ raise FileBrowserError("fs_error", "Invalid Content-Length", 400) from exc
+ if length < 0:
+ raise FileBrowserError("fs_error", "Invalid Content-Length", 400)
+ if length > max_file_bytes + _FILE_UPLOAD_MULTIPART_OVERHEAD_BYTES:
+ raise FileBrowserError("too_large", "File is too large", 413)
+
+
+class _FileUploadMultiPartParser(MultiPartParser):
+ def __init__(
+ self,
+ *args: Any,
+ max_file_bytes: int,
+ max_field_bytes: int,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self._max_file_bytes = max_file_bytes
+ self._max_field_bytes = max_field_bytes
+ self._current_file_bytes = 0
+
+ def on_part_begin(self) -> None:
+ self._current_file_bytes = 0
+ super().on_part_begin()
+
+ def on_part_data(self, data: bytes, start: int, end: int) -> None:
+ chunk_len = end - start
+ if self._current_part.file is None:
+ if len(self._current_part.data) + chunk_len > self._max_field_bytes:
+ raise MultiPartException("Form field is too large.")
+ else:
+ self._current_file_bytes += chunk_len
+ if self._current_file_bytes > self._max_file_bytes:
+ raise MultiPartException("File is too large.")
+ super().on_part_data(data, start, end)
+
+
+async def _parse_file_upload_form(starlette_request: FastAPIRequest, *, max_file_bytes: int):
+ content_type = starlette_request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
+ if content_type != "multipart/form-data":
+ from core.file_browser_service import FileBrowserError
+
+ raise FileBrowserError("invalid_name", "File is required", 400)
+ parser_kwargs: dict[str, Any] = {"max_files": 1, "max_fields": 3}
+ if "max_part_size" in inspect.signature(MultiPartParser).parameters:
+ parser_kwargs["max_part_size"] = _FILE_UPLOAD_FIELD_MAX_BYTES
+ parser = _FileUploadMultiPartParser(
+ starlette_request.headers,
+ starlette_request.stream(),
+ max_file_bytes=max_file_bytes,
+ max_field_bytes=_FILE_UPLOAD_FIELD_MAX_BYTES,
+ **parser_kwargs,
+ )
+ return await parser.parse()
+
+
async def _dispatch_native_ui_request(starlette_request: FastAPIRequest, handler: Callable[[], Any]):
return await app.dispatch_native_request(starlette_request, handler)
@@ -5892,6 +5964,50 @@ async def files_write(starlette_request: FastAPIRequest):
return await _dispatch_native_ui_request(starlette_request, handler)
[email protected]("/api/files/upload", include_in_schema=False)
+async def files_upload(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ try:
+ _validate_file_upload_content_length(starlette_request.headers, file_browser_service.MAX_FILE_BYTES)
+ form = await _parse_file_upload_form(starlette_request, max_file_bytes=file_browser_service.MAX_FILE_BYTES)
+ try:
+ upload = form.get("file")
+ if not isinstance(upload, StarletteUploadFile):
+ raise file_browser_service.FileBrowserError("invalid_name", "File is required", 400)
+ name_value = form.get("name")
+ dir_value = form.get("dir")
+ await upload.seek(0)
+ return jsonify(
+ await asyncio.to_thread(
+ file_browser_service.upload_file,
+ str(dir_value or ""),
+ upload.file,
+ filename=upload.filename,
+ name=name_value if isinstance(name_value, str) else None,
+ overwrite=_parse_explicit_bool(form.get("overwrite")),
+ )
+ )
+ finally:
+ await form.close()
+ except MultiPartException as exc:
+ message = str(exc)
+ if "too large" in message.lower():
+ return _file_browser_error_response(
+ file_browser_service.FileBrowserError("too_large", "File is too large", 413)
+ )
+ return _file_browser_error_response(file_browser_service.FileBrowserError("fs_error", message, 400))
+ except StarletteHTTPException as exc:
+ return _file_browser_error_response(
+ file_browser_service.FileBrowserError("fs_error", str(exc.detail), 400)
+ )
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
@app.post("/api/files/mkdir", include_in_schema=False)
async def files_mkdir(starlette_request: FastAPIRequest):
async def handler():