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 safe copy API (#885)

Call White41c434c16453
diff --git a/core/file_browser_service.py b/core/file_browser_service.py
index bdf520ed9..4a19f62bd 100644
--- a/core/file_browser_service.py
+++ b/core/file_browser_service.py
@@ -28,6 +28,7 @@ DELETE_UNDO_TTL_SECONDS = 3600
DELETE_UNDO_MAX_ENTRIES = 32
DELETE_UNDO_ENTRY_SIZE_CAP_BYTES = 512 * 1024 * 1024
DELETE_UNDO_TOTAL_SIZE_CAP_BYTES = 2 * 1024 * 1024 * 1024
+COPY_TOTAL_SIZE_CAP_BYTES = 2 * 1024 * 1024 * 1024
INLINE_SAFE_CONTENT_TYPES = {
"image/png",
@@ -65,6 +66,8 @@ _WRITE_LOCKS_MUTEX = threading.Lock()
_WRITE_LOCKS: dict[str, threading.Lock] = {}
_WRITE_TEMP_PREFIX = ".avibe-write-"
_UPLOAD_CHUNK_BYTES = 1024 * 1024
+_COPY_CHUNK_BYTES = 1024 * 1024
+_COPY_TEMP_PREFIX = ".avibe-copy-"
_NO_REPLACE_UNSUPPORTED_ERRNOS = {errno.ENOSYS, errno.EINVAL, errno.ENOTSUP, errno.EOPNOTSUPP}
_HARD_LINK_UNSUPPORTED_ERRNOS = {errno.EPERM, errno.EXDEV, errno.ENOTSUP, errno.EOPNOTSUPP}
_DELETE_UNDO_DIR_NAME = "files_undo"
@@ -79,6 +82,7 @@ _DELETE_UNDO_ENTRY_SIZE_CAP_ENV = "AVIBE_FILES_UNDO_SIZE_CAP_BYTES"
_DELETE_UNDO_TTL_ENV = "AVIBE_FILES_UNDO_TTL_SECONDS"
_DELETE_UNDO_MAX_ENTRIES_ENV = "AVIBE_FILES_UNDO_MAX_ENTRIES"
_DELETE_UNDO_TOTAL_SIZE_CAP_ENV = "AVIBE_FILES_UNDO_TOTAL_SIZE_CAP_BYTES"
+_COPY_TOTAL_SIZE_CAP_ENV = "AVIBE_FILES_COPY_SIZE_CAP_BYTES"
class FileBrowserError(Exception):
@@ -1162,6 +1166,99 @@ def move_path(raw_src: str, raw_dst: str, *, overwrite: bool = False) -> dict[st
return _run_mutation("move", source, _move, dst=str(target), overwrite=overwrite)
+def copy_path(raw_src: str, raw_dst: str, *, overwrite: bool = False) -> dict[str, Any]:
+ """Copy one entry while preserving modes; copied mtimes are not guaranteed.
+
+ Sources are measured before staging and copied without following symlinks.
+ The 2 GB default cap is configurable through
+ ``AVIBE_FILES_COPY_SIZE_CAP_BYTES``. The completed copy is published from a
+ sibling temporary entry, so the destination never exposes a partial tree.
+ """
+ source = _resolve_existing_entry_path(raw_src)
+ target = _resolve_entry_path(raw_dst)
+ _validate_new_name(_raw_final_component(raw_dst))
+ source_stat = _stat_existing(source, follow_symlinks=False)
+ source_is_dir = stat.S_ISDIR(source_stat.st_mode)
+ source_is_file = stat.S_ISREG(source_stat.st_mode)
+ source_is_symlink = stat.S_ISLNK(source_stat.st_mode)
+ if not (source_is_dir or source_is_file or source_is_symlink):
+ raise FileBrowserError("fs_error", "Unsupported source type", 400)
+ if source_is_dir and _entry_contains_no_follow(source, target):
+ raise FileBrowserError("invalid_path", "Cannot copy a folder into itself", 400)
+ if source_is_symlink:
+ try:
+ same_target = source.resolve() == target.resolve()
+ except (OSError, RuntimeError):
+ same_target = False
+ if same_target:
+ raise ConflictError("invalid_copy", "Cannot copy a symlink onto the file it points to")
+ if not target.parent.is_dir():
+ raise FileBrowserError("not_dir", "Destination parent is not a directory", 400)
+ _validate_copy_target(target, source_is_dir=source_is_dir, overwrite=overwrite)
+
+ source_fd: int | None = None
+ source_link: str | None = None
+ size_cap = _copy_total_size_cap_bytes()
+ try:
+ if source_is_dir and os.name == "posix":
+ source_fd = _open_copy_directory(source, source_stat)
+ scan_fd = _open_copy_directory(".", source_stat, dir_fd=source_fd)
+ try:
+ _measure_copy_directory_fd(scan_fd, size_cap)
+ finally:
+ os.close(scan_fd)
+ elif source_is_dir:
+ _measure_copy_directory_path(source, source_stat, size_cap)
+ elif source_is_file:
+ _add_copy_size(0, source_stat.st_size, size_cap)
+ source_fd = _open_copy_file(source, source_stat)
+ else:
+ source_link = os.readlink(source)
+
+ def _copy() -> dict[str, Any]:
+ with _write_lock_for(target):
+ _validate_copy_target(target, source_is_dir=source_is_dir, overwrite=overwrite)
+ stage: Path | None = None
+ try:
+ if source_is_dir:
+ stage = _new_copy_stage_path(target)
+ budget = [0]
+ if source_fd is not None:
+ copy_fd = _open_copy_directory(".", source_stat, dir_fd=source_fd)
+ try:
+ _copy_directory_from_fd(copy_fd, stage, budget, size_cap)
+ finally:
+ os.close(copy_fd)
+ else:
+ _copy_directory_from_path(source, source_stat, stage, budget, size_cap)
+ elif source_is_file:
+ stage = _new_copy_stage_path(target)
+ assert source_fd is not None
+ os.lseek(source_fd, 0, os.SEEK_SET)
+ _copy_file_from_fd(source_fd, stage, source_stat, budget=[0], size_cap=size_cap)
+ else:
+ assert source_link is not None
+ stage = _stage_copy_symlink(target, source_link)
+ _publish_staged_copy(stage, target, source_is_dir=source_is_dir, overwrite=overwrite)
+ stage = None
+ _fsync_dir(target.parent)
+ return {"ok": True, "path": str(target)}
+ finally:
+ if stage is not None:
+ _remove_copy_stage_best_effort(stage)
+
+ return _run_mutation("copy", source, _copy, dst=str(target), overwrite=overwrite)
+ except FileBrowserError:
+ raise
+ 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 source_fd is not None:
+ os.close(source_fd)
+
+
def _move_to_absent_target(
source: Path,
target: Path,
@@ -1284,6 +1381,297 @@ def _remove_path_if_exists_best_effort(path: Path) -> None:
logger.debug("Failed to remove move backup after preserving placed target", exc_info=True)
+def _copy_total_size_cap_bytes() -> int:
+ return _env_int(_COPY_TOTAL_SIZE_CAP_ENV, COPY_TOTAL_SIZE_CAP_BYTES)
+
+
+def _validate_copy_target(target: Path, *, source_is_dir: bool, overwrite: bool) -> None:
+ if not _exists_no_follow(target):
+ return
+ if not overwrite:
+ raise ConflictError("exists", "Destination already exists")
+ if _is_dir_no_follow(target) and not source_is_dir:
+ raise ConflictError("exists", "Cannot overwrite a directory with a non-directory")
+
+
+def _same_copy_entry(expected: os.stat_result, current: os.stat_result) -> bool:
+ return (expected.st_dev, expected.st_ino, stat.S_IFMT(expected.st_mode)) == (
+ current.st_dev,
+ current.st_ino,
+ stat.S_IFMT(current.st_mode),
+ )
+
+
+def _open_copy_directory(path: str | Path, expected: os.stat_result, *, dir_fd: int | None = None) -> int:
+ flags = os.O_RDONLY
+ if hasattr(os, "O_DIRECTORY"):
+ flags |= os.O_DIRECTORY
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ fd = os.open(path, flags, dir_fd=dir_fd)
+ current = os.fstat(fd)
+ if not stat.S_ISDIR(current.st_mode) or not _same_copy_entry(expected, current):
+ os.close(fd)
+ raise FileBrowserError("fs_error", "Source changed during copy", 400)
+ return fd
+
+
+def _open_copy_file(path: str | Path, expected: os.stat_result, *, dir_fd: int | None = None) -> int:
+ flags = os.O_RDONLY
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ fd = os.open(path, flags, dir_fd=dir_fd)
+ current = os.fstat(fd)
+ if not stat.S_ISREG(current.st_mode) or not _same_copy_entry(expected, current):
+ os.close(fd)
+ raise FileBrowserError("fs_error", "Source changed during copy", 400)
+ return fd
+
+
+def _add_copy_size(total: int, size: int, cap: int) -> int:
+ total += size
+ if total > cap:
+ raise FileBrowserError("too_large", "Copy is too large", 413)
+ return total
+
+
+def _measure_copy_directory_fd(dir_fd: int, cap: int) -> int:
+ total = 0
+ with os.scandir(dir_fd) as entries:
+ for entry in entries:
+ entry_stat = entry.stat(follow_symlinks=False)
+ if stat.S_ISREG(entry_stat.st_mode):
+ total = _add_copy_size(total, entry_stat.st_size, cap)
+ elif stat.S_ISDIR(entry_stat.st_mode):
+ child_fd = _open_copy_directory(entry.name, entry_stat, dir_fd=dir_fd)
+ try:
+ total = _add_copy_size(total, _measure_copy_directory_fd(child_fd, cap - total), cap)
+ finally:
+ os.close(child_fd)
+ elif not stat.S_ISLNK(entry_stat.st_mode):
+ raise FileBrowserError("fs_error", "Unsupported source type", 400)
+ return total
+
+
+def _measure_copy_directory_path(source: Path, expected: os.stat_result, cap: int) -> int:
+ current = source.lstat()
+ if not stat.S_ISDIR(current.st_mode) or not _same_copy_entry(expected, current):
+ raise FileBrowserError("fs_error", "Source changed during copy", 400)
+ total = 0
+ with os.scandir(source) as entries:
+ for entry in entries:
+ entry_stat = entry.stat(follow_symlinks=False)
+ child = source / entry.name
+ if stat.S_ISREG(entry_stat.st_mode):
+ total = _add_copy_size(total, entry_stat.st_size, cap)
+ elif stat.S_ISDIR(entry_stat.st_mode):
+ total = _add_copy_size(
+ total,
+ _measure_copy_directory_path(child, entry_stat, cap - total),
+ cap,
+ )
+ elif not stat.S_ISLNK(entry_stat.st_mode):
+ raise FileBrowserError("fs_error", "Unsupported source type", 400)
+ return total
+
+
+def _new_copy_stage_path(target: Path) -> Path:
+ for _ in range(100):
+ candidate = target.with_name(f"{_COPY_TEMP_PREFIX}{uuid.uuid4().hex}")
+ if not _exists_no_follow(candidate):
+ return candidate
+ raise FileBrowserError("fs_error", "Could not reserve copy temp path", 400)
+
+
+def _copy_file_from_fd(
+ source_fd: int,
+ target: Path,
+ source_stat: os.stat_result,
+ *,
+ budget: list[int] | None = None,
+ size_cap: int | None = None,
+) -> None:
+ flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ target_fd = os.open(target, flags, 0o600)
+ try:
+ with os.fdopen(target_fd, "wb") as handle:
+ target_fd = -1
+ while True:
+ chunk = os.read(source_fd, _COPY_CHUNK_BYTES)
+ if not chunk:
+ break
+ if budget is not None and size_cap is not None:
+ budget[0] = _add_copy_size(budget[0], len(chunk), size_cap)
+ handle.write(chunk)
+ handle.flush()
+ os.fsync(handle.fileno())
+ mode = stat.S_IMODE(source_stat.st_mode)
+ if hasattr(os, "fchmod"):
+ os.fchmod(handle.fileno(), mode)
+ else:
+ target.chmod(mode)
+ finally:
+ if target_fd >= 0:
+ os.close(target_fd)
+
+
+def _copy_symlink_from_fd(source_dir_fd: int, name: str, expected: os.stat_result, target: Path) -> None:
+ link_target = os.readlink(name, dir_fd=source_dir_fd)
+ current = os.stat(name, dir_fd=source_dir_fd, follow_symlinks=False)
+ if not stat.S_ISLNK(current.st_mode) or not _same_copy_entry(expected, current):
+ raise FileBrowserError("fs_error", "Source changed during copy", 400)
+ os.symlink(link_target, target)
+
+
+def _copy_directory_from_fd(dir_fd: int, target: Path, budget: list[int], size_cap: int) -> None:
+ directory_stat = os.fstat(dir_fd)
+ target.mkdir(mode=0o700)
+ with os.scandir(dir_fd) as entries:
+ for entry in entries:
+ entry_stat = entry.stat(follow_symlinks=False)
+ child_target = target / entry.name
+ if stat.S_ISDIR(entry_stat.st_mode):
+ child_fd = _open_copy_directory(entry.name, entry_stat, dir_fd=dir_fd)
+ try:
+ _copy_directory_from_fd(child_fd, child_target, budget, size_cap)
+ finally:
+ os.close(child_fd)
+ elif stat.S_ISREG(entry_stat.st_mode):
+ child_fd = _open_copy_file(entry.name, entry_stat, dir_fd=dir_fd)
+ try:
+ _copy_file_from_fd(child_fd, child_target, entry_stat, budget=budget, size_cap=size_cap)
+ finally:
+ os.close(child_fd)
+ elif stat.S_ISLNK(entry_stat.st_mode):
+ _copy_symlink_from_fd(dir_fd, entry.name, entry_stat, child_target)
+ else:
+ raise FileBrowserError("fs_error", "Unsupported source type", 400)
+ target.chmod(stat.S_IMODE(directory_stat.st_mode))
+
+
+def _copy_directory_from_path(
+ source: Path,
+ expected: os.stat_result,
+ target: Path,
+ budget: list[int],
+ size_cap: int,
+) -> None:
+ directory_stat = source.lstat()
+ if not stat.S_ISDIR(directory_stat.st_mode) or not _same_copy_entry(expected, directory_stat):
+ raise FileBrowserError("fs_error", "Source changed during copy", 400)
+ target.mkdir(mode=0o700)
+ with os.scandir(source) as entries:
+ for entry in entries:
+ entry_stat = entry.stat(follow_symlinks=False)
+ child_source = source / entry.name
+ child_target = target / entry.name
+ if stat.S_ISDIR(entry_stat.st_mode):
+ _copy_directory_from_path(child_source, entry_stat, child_target, budget, size_cap)
+ elif stat.S_ISREG(entry_stat.st_mode):
+ child_fd = _open_copy_file(child_source, entry_stat)
+ try:
+ _copy_file_from_fd(child_fd, child_target, entry_stat, budget=budget, size_cap=size_cap)
+ finally:
+ os.close(child_fd)
+ elif stat.S_ISLNK(entry_stat.st_mode):
+ link_target = os.readlink(child_source)
+ current_link = child_source.lstat()
+ if not stat.S_ISLNK(current_link.st_mode) or not _same_copy_entry(entry_stat, current_link):
+ raise FileBrowserError("fs_error", "Source changed during copy", 400)
+ os.symlink(link_target, child_target)
+ else:
+ raise FileBrowserError("fs_error", "Unsupported source type", 400)
+ target.chmod(stat.S_IMODE(directory_stat.st_mode))
+
+
+def _stage_copy_symlink(target: Path, link_target: str) -> Path:
+ for _ in range(100):
+ stage = _new_copy_stage_path(target)
+ try:
+ os.symlink(link_target, stage)
+ return stage
+ except FileExistsError:
+ continue
+ raise FileBrowserError("fs_error", "Could not reserve copy temp path", 400)
+
+
+def _publish_staged_copy(stage: Path, target: Path, *, source_is_dir: bool, overwrite: bool) -> None:
+ if not overwrite:
+ _os_rename_noreplace(stage, target)
+ return
+ if not _exists_no_follow(target):
+ _os_rename_noreplace(stage, target)
+ return
+ if not source_is_dir:
+ if _is_dir_no_follow(target):
+ raise ConflictError("exists", "Cannot overwrite a directory with a non-directory")
+ try:
+ os.replace(stage, target)
+ except (IsADirectoryError, NotADirectoryError) as exc:
+ raise ConflictError("exists", "Destination type changed during copy") from exc
+ return
+
+ backup = _reserve_backup_path(target)
+ _os_rename_noreplace(target, backup)
+ published = False
+ try:
+ _os_rename_noreplace(stage, target)
+ published = True
+ except Exception:
+ if not _exists_no_follow(target):
+ try:
+ _os_rename_noreplace(backup, target)
+ backup = None
+ except Exception:
+ logger.exception("Failed to restore copy overwrite backup")
+ raise
+ finally:
+ if published and backup is not None:
+ _remove_copy_stage_best_effort(backup)
+
+
+def _remove_copy_stage_best_effort(path: Path) -> None:
+ try:
+ if _is_dir_no_follow(path):
+ _make_copy_tree_removable(path)
+ shutil.rmtree(path)
+ else:
+ path.unlink()
+ except FileNotFoundError:
+ pass
+ except OSError:
+ logger.debug("Failed to remove copy staging path", exc_info=True)
+
+
+def _make_copy_tree_removable(root: Path) -> None:
+ stack = [(root, root.lstat())]
+ while stack:
+ directory, expected = stack.pop()
+ _make_copy_directory_writable(directory, expected)
+ with os.scandir(directory) as entries:
+ for entry in entries:
+ entry_stat = entry.stat(follow_symlinks=False)
+ if stat.S_ISDIR(entry_stat.st_mode):
+ stack.append((directory / entry.name, entry_stat))
+
+
+def _make_copy_directory_writable(path: Path, expected: os.stat_result) -> None:
+ mode = stat.S_IMODE(expected.st_mode) | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
+ if os.name == "posix":
+ fd = _open_copy_directory(path, expected)
+ try:
+ os.fchmod(fd, mode)
+ finally:
+ os.close(fd)
+ return
+ current = path.lstat()
+ if not stat.S_ISDIR(current.st_mode) or not _same_copy_entry(expected, current):
+ raise FileBrowserError("fs_error", "Copy staging tree changed during cleanup", 400)
+ path.chmod(mode)
+
+
def _delete_undo_remove_path(path: Path) -> bool:
try:
_remove_path_if_exists(path)
diff --git a/tests/test_file_browser_backend.py b/tests/test_file_browser_backend.py
index babd8707f..a51d3e39c 100644
--- a/tests/test_file_browser_backend.py
+++ b/tests/test_file_browser_backend.py
@@ -763,6 +763,222 @@ def test_upload_file_read_failure_leaves_no_partial_file(tmp_path):
assert not list(tmp_path.glob(f"{fs._WRITE_TEMP_PREFIX}*.tmp"))
+def test_copy_file_and_directory_preserve_content_and_modes(tmp_path):
+ source_file = tmp_path / "source.txt"
+ source_file.write_text("source", encoding="utf-8")
+ source_file.chmod(0o640)
+ copied_file = tmp_path / "copied.txt"
+
+ assert fs.copy_path(str(source_file), str(copied_file)) == {"ok": True, "path": str(copied_file)}
+ assert source_file.read_text(encoding="utf-8") == "source"
+ assert copied_file.read_text(encoding="utf-8") == "source"
+ assert copied_file.stat().st_mode & 0o777 == 0o640
+
+ source_dir = tmp_path / "source-dir"
+ nested = source_dir / "nested"
+ nested.mkdir(parents=True)
+ nested.chmod(0o750)
+ child = nested / "child.bin"
+ child.write_bytes(b"child")
+ child.chmod(0o600)
+ copied_dir = tmp_path / "copied-dir"
+
+ assert fs.copy_path(str(source_dir), str(copied_dir)) == {"ok": True, "path": str(copied_dir)}
+ assert (copied_dir / "nested" / "child.bin").read_bytes() == b"child"
+ assert (copied_dir / "nested").stat().st_mode & 0o777 == 0o750
+ assert (copied_dir / "nested" / "child.bin").stat().st_mode & 0o777 == 0o600
+
+
+def test_copy_conflict_without_overwrite_and_replaces_with_overwrite(tmp_path):
+ source = tmp_path / "source.txt"
+ destination = tmp_path / "destination.txt"
+ source.write_text("new", encoding="utf-8")
+ destination.write_text("old", encoding="utf-8")
+
+ with pytest.raises(ConflictError) as exc:
+ fs.copy_path(str(source), str(destination))
+
+ assert exc.value.code == "exists"
+ assert destination.read_text(encoding="utf-8") == "old"
+ assert fs.copy_path(str(source), str(destination), overwrite=True) == {
+ "ok": True,
+ "path": str(destination),
+ }
+ assert source.read_text(encoding="utf-8") == "new"
+ assert destination.read_text(encoding="utf-8") == "new"
+
+
+def test_copy_directory_overwrite_replaces_complete_tree(tmp_path):
+ source = tmp_path / "source"
+ (source / "nested").mkdir(parents=True)
+ (source / "nested" / "new.txt").write_text("new", encoding="utf-8")
+ destination = tmp_path / "destination"
+ destination.mkdir()
+ (destination / "old.txt").write_text("old", encoding="utf-8")
+
+ result = fs.copy_path(str(source), str(destination), overwrite=True)
+
+ assert result == {"ok": True, "path": str(destination)}
+ assert not (destination / "old.txt").exists()
+ assert (destination / "nested" / "new.txt").read_text(encoding="utf-8") == "new"
+ assert not list(tmp_path.glob(f"{fs._COPY_TEMP_PREFIX}*"))
+ assert not list(tmp_path.glob(".avibe-overwrite-*"))
+
+
+def test_copy_directory_rejects_own_subtree(tmp_path):
+ source = tmp_path / "source"
+ child = source / "child"
+ child.mkdir(parents=True)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.copy_path(str(source), str(child / "copy"))
+
+ assert exc.value.code == "invalid_path"
+ assert not (child / "copy").exists()
+
+
+def test_copy_symlinks_as_links_without_reading_targets(tmp_path, monkeypatch):
+ secret = tmp_path / "secret.txt"
+ secret.write_text("not copied", encoding="utf-8")
+ source_link = tmp_path / "source-link"
+ source_link.symlink_to(secret)
+ copied_link = tmp_path / "copied-link"
+
+ assert fs.copy_path(str(source_link), str(copied_link)) == {"ok": True, "path": str(copied_link)}
+ assert copied_link.is_symlink()
+ assert os.readlink(copied_link) == str(secret)
+
+ source_dir = tmp_path / "source-dir"
+ source_dir.mkdir()
+ (source_dir / "secret-link").symlink_to(secret)
+ copied_dir = tmp_path / "copied-dir"
+ monkeypatch.setenv(fs._COPY_TOTAL_SIZE_CAP_ENV, "0")
+
+ fs.copy_path(str(source_dir), str(copied_dir))
+
+ assert (copied_dir / "secret-link").is_symlink()
+ assert os.readlink(copied_dir / "secret-link") == str(secret)
+ assert secret.read_text(encoding="utf-8") == "not copied"
+
+
+def test_copy_directory_failure_cleans_partial_stage_and_destination(tmp_path, monkeypatch):
+ source = tmp_path / "source"
+ source.mkdir()
+ (source / "first.txt").write_text("first", encoding="utf-8")
+ (source / "second.txt").write_text("second", encoding="utf-8")
+ destination = tmp_path / "destination"
+ destination.mkdir()
+ (destination / "original.txt").write_text("original", encoding="utf-8")
+ real_copy = fs._copy_file_from_fd
+ calls = {"count": 0}
+
+ def fail_after_copy(*args, **kwargs):
+ real_copy(*args, **kwargs)
+ calls["count"] += 1
+ if calls["count"] == 1:
+ raise OSError(errno.EIO, "copy failed")
+
+ monkeypatch.setattr(fs, "_copy_file_from_fd", fail_after_copy)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.copy_path(str(source), str(destination), overwrite=True)
+
+ assert exc.value.code == "fs_error"
+ assert (destination / "original.txt").read_text(encoding="utf-8") == "original"
+ assert not (destination / "first.txt").exists()
+ assert not (destination / "second.txt").exists()
+ assert not list(tmp_path.glob(f"{fs._COPY_TEMP_PREFIX}*"))
+
+
+def test_copy_cleanup_never_chmods_symlink_target(tmp_path, monkeypatch):
+ external = tmp_path / "external.txt"
+ external.write_text("external", encoding="utf-8")
+ external.chmod(0o600)
+ source = tmp_path / "source"
+ locked = source / "locked"
+ locked.mkdir(parents=True)
+ (locked / "external-link").symlink_to(external)
+ locked.chmod(0o500)
+ destination = tmp_path / "destination"
+
+ def fail_publish(*_args, **_kwargs):
+ raise OSError(errno.EIO, "publish failed")
+
+ monkeypatch.setattr(fs, "_publish_staged_copy", fail_publish)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.copy_path(str(source), str(destination))
+
+ assert exc.value.code == "fs_error"
+ assert external.stat().st_mode & 0o777 == 0o600
+ assert not destination.exists()
+ assert not list(tmp_path.glob(f"{fs._COPY_TEMP_PREFIX}*"))
+
+
+def test_copy_file_size_cap_rejects_before_staging(tmp_path, monkeypatch):
+ source = tmp_path / "large.bin"
+ source.write_bytes(b"12345")
+ destination = tmp_path / "destination.bin"
+ monkeypatch.setenv(fs._COPY_TOTAL_SIZE_CAP_ENV, "4")
+ monkeypatch.setattr(
+ fs,
+ "_new_copy_stage_path",
+ lambda _target: (_ for _ in ()).throw(AssertionError("copy should reject before staging")),
+ )
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.copy_path(str(source), str(destination))
+
+ assert exc.value.status_code == 413
+ assert exc.value.code == "too_large"
+ assert not destination.exists()
+
+
+def test_copy_directory_size_cap_rejects_before_staging(tmp_path, monkeypatch):
+ source = tmp_path / "source"
+ source.mkdir()
+ (source / "large.bin").write_bytes(b"12345")
+ destination = tmp_path / "destination"
+ monkeypatch.setenv(fs._COPY_TOTAL_SIZE_CAP_ENV, "4")
+ monkeypatch.setattr(
+ fs,
+ "_new_copy_stage_path",
+ lambda _target: (_ for _ in ()).throw(AssertionError("copy should reject before staging")),
+ )
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.copy_path(str(source), str(destination))
+
+ assert exc.value.status_code == 413
+ assert exc.value.code == "too_large"
+ assert not destination.exists()
+ assert not list(tmp_path.glob(f"{fs._COPY_TEMP_PREFIX}*"))
+
+
+ ("src", "dst", "expected_code"),
+ [
+ ("relative-source", "/tmp/destination", "invalid_path"),
+ ("/tmp/source", "relative-destination", "invalid_path"),
+ ("/tmp/source", "/tmp/parent/..", "invalid_path"),
+ ("/tmp/source", "/tmp/bad\\name", "invalid_name"),
+ ],
+)
+def test_copy_rejects_traversal_and_invalid_names(tmp_path, src, dst, expected_code):
+ source = tmp_path / "source"
+ source.write_text("source", encoding="utf-8")
+ parent = tmp_path / "parent"
+ parent.mkdir()
+ src = str(source) if src == "/tmp/source" else src
+ dst = str(parent / "..") if dst == "/tmp/parent/.." else dst
+ dst = str(tmp_path / "bad\\name") if dst == "/tmp/bad\\name" else dst
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.copy_path(src, dst)
+
+ assert exc.value.code == expected_code
+
+
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"
@@ -1858,6 +2074,61 @@ def test_http_routes_return_contract_and_headers(tmp_path):
assert (tmp_path / "uploaded.bin").read_bytes() == b"upload"
+def test_http_copy_returns_contract_and_maps_name_clash(tmp_path):
+ source = tmp_path / "source.txt"
+ source.write_text("source", encoding="utf-8")
+ destination = tmp_path / "destination.txt"
+ client = app.test_client()
+ headers = csrf_headers(client)
+
+ response = client.post(
+ "/api/files/copy",
+ json={"src": str(source), "dst": str(destination)},
+ headers=headers,
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {"ok": True, "path": str(destination)}
+ assert destination.read_text(encoding="utf-8") == "source"
+
+ source.write_text("updated", encoding="utf-8")
+ conflict = client.post(
+ "/api/files/copy",
+ json={"src": str(source), "dst": str(destination), "overwrite": "false"},
+ headers=headers,
+ )
+ assert conflict.status_code == 409
+ assert conflict.get_json() == {
+ "ok": False,
+ "error": {"code": "exists", "message": "Destination already exists"},
+ }
+ assert destination.read_text(encoding="utf-8") == "source"
+
+ replaced = client.post(
+ "/api/files/copy",
+ json={"src": str(source), "dst": str(destination), "overwrite": True},
+ headers=headers,
+ )
+ assert replaced.status_code == 200
+ assert replaced.get_json() == {"ok": True, "path": str(destination)}
+ assert destination.read_text(encoding="utf-8") == "updated"
+
+
+def test_http_copy_enforces_csrf(tmp_path):
+ source = tmp_path / "source.txt"
+ destination = tmp_path / "destination.txt"
+ source.write_text("source", encoding="utf-8")
+ client = app.test_client()
+
+ response = client.post(
+ "/api/files/copy",
+ json={"src": str(source), "dst": str(destination)},
+ )
+
+ assert response.status_code == 403
+ assert not destination.exists()
+
+
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()
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 476cc1be9..59be3ea62 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6313,6 +6313,27 @@ async def files_move(starlette_request: FastAPIRequest):
return await _dispatch_native_ui_request(starlette_request, handler)
[email protected]("/api/files/copy", include_in_schema=False)
+async def files_copy(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ payload = request.json or {}
+ try:
+ return jsonify(
+ await asyncio.to_thread(
+ file_browser_service.copy_path,
+ payload.get("src") or "",
+ payload.get("dst") or "",
+ overwrite=_parse_explicit_bool(payload.get("overwrite")),
+ )
+ )
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
@app.post("/api/files/delete", include_in_schema=False)
async def files_delete(starlette_request: FastAPIRequest):
async def handler():