From 2d6c9ba5c93d31192a6e3265db50d3b1ee35315f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=91=D0=B0=D1=82-=D0=9E=D1=80=D1=88=D0=B8=D1=85?= <34618353+orshih6@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:20:41 +0000 Subject: [PATCH 1/2] fix(extensions): fall back to in-memory archive when the unlinked download file can't be written MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Бат-Орших <34618353+orshih6@users.noreply.github.com> --- src/specify_cli/extensions/_commands.py | 21 ++++-- .../test_command_add_path_traversal.py | 71 +++++++++++++++++++ 2 files changed, 88 insertions(+), 4 deletions(-) diff --git a/src/specify_cli/extensions/_commands.py b/src/specify_cli/extensions/_commands.py index 8019656fb1..4b1b984e69 100644 --- a/src/specify_cli/extensions/_commands.py +++ b/src/specify_cli/extensions/_commands.py @@ -8,6 +8,7 @@ from __future__ import annotations import errno +import io import os import stat from pathlib import Path @@ -235,10 +236,22 @@ def install_extension_from_url( download_file.write(archive_data) download_file.flush() download_file.seek(0) - except OSError as exc: - raise ExtensionError( - f"Could not safely write download file: {exc}" - ) from exc + except OSError: + # Some filesystems (e.g. gocryptfs/FUSE) reject writes to an + # already-unlinked inode. The archive is fully buffered in memory + # (bounded by ``read_response_limited``), so consume it from there. + if download_file is not None: + try: + download_file.close() + except OSError: + pass + elif download_fd >= 0: + try: + os.close(download_fd) + except OSError: + pass + download_fd = -1 + download_file = io.BytesIO(archive_data) format_source = ( final_url diff --git a/tests/specify_cli/extensions/test_command_add_path_traversal.py b/tests/specify_cli/extensions/test_command_add_path_traversal.py index c2243ec9f0..f5b5a4ef80 100644 --- a/tests/specify_cli/extensions/test_command_add_path_traversal.py +++ b/tests/specify_cli/extensions/test_command_add_path_traversal.py @@ -402,3 +402,74 @@ def _raise_collision(project_root, dir_, zip_filename): assert result.exit_code == 1 assert "Could not safely create download file" in result.output install_spy.assert_not_called() + + +def test_url_install_tolerates_fs_rejecting_writes_to_unlinked_file( + project_dir: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Filesystems such as gocryptfs (FUSE) fail with ``ENOENT`` when flushing + to an already-unlinked inode; the install must still succeed from the + in-memory archive instead of aborting.""" + captured: dict[str, object] = {} + + class FakeResponse(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + return False + + class UnlinkedInodeFile(io.FileIO): + def write(self, data): + raise FileNotFoundError(2, "No such file or directory") + + real_fdopen = os.fdopen + + def fake_fdopen(fd, mode="r", *args, **kwargs): + if mode == "w+b": + return UnlinkedInodeFile(fd, "r+") + return real_fdopen(fd, mode, *args, **kwargs) + + def fake_install( + self, + zip_path: Path, + speckit_version: str, + priority: int = 10, + force: bool = False, + *, + archive_file=None, + ): + captured["bytes"] = archive_file.read() + return SimpleNamespace( + id="test-ext", + name="Test Extension", + version="1.0.0", + description="", + warnings=[], + commands=[], + ) + + monkeypatch.setattr(os, "fdopen", fake_fdopen) + monkeypatch.setattr(typer, "confirm", lambda *args, **kwargs: True) + monkeypatch.setattr( + ExtensionCatalog, + "_open_url", + lambda *args, **kwargs: FakeResponse(_MINIMAL_ZIP_BYTES), + ) + monkeypatch.setattr(ExtensionManager, "install_from_zip", fake_install) + monkeypatch.setattr(_commands, "_refresh_events_and_warn", lambda root: None) + monkeypatch.setattr(_commands, "load_init_options", lambda root: {}) + + result = runner.invoke( + app, + [ + "extension", + "add", + "test-ext", + "--from", + "https://example.com/test-ext.zip", + ], + ) + + assert result.exit_code == 0, result.output + assert captured["bytes"] == _MINIMAL_ZIP_BYTES From 0ae1b61399f391a95c2a8d5d8783d0a01c588012 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=91=D0=B0=D1=82-=D0=9E=D1=80=D1=88=D0=B8=D1=85?= <34618353+orshih6@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:32:24 +0000 Subject: [PATCH 2/2] test(extensions): cover fdopen failure, buffered flush/close failure, and real install via in-memory fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Бат-Орших <34618353+orshih6@users.noreply.github.com> --- .../test_command_add_path_traversal.py | 146 ++++++++++++++---- 1 file changed, 115 insertions(+), 31 deletions(-) diff --git a/tests/specify_cli/extensions/test_command_add_path_traversal.py b/tests/specify_cli/extensions/test_command_add_path_traversal.py index f5b5a4ef80..761d19f3db 100644 --- a/tests/specify_cli/extensions/test_command_add_path_traversal.py +++ b/tests/specify_cli/extensions/test_command_add_path_traversal.py @@ -5,9 +5,11 @@ from __future__ import annotations +import errno import io import os import shutil +import zipfile from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock @@ -404,31 +406,68 @@ def _raise_collision(project_root, dir_, zip_filename): install_spy.assert_not_called() -def test_url_install_tolerates_fs_rejecting_writes_to_unlinked_file( - project_dir: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Filesystems such as gocryptfs (FUSE) fail with ``ENOENT`` when flushing - to an already-unlinked inode; the install must still succeed from the - in-memory archive instead of aborting.""" - captured: dict[str, object] = {} +class _FakeResponse(io.BytesIO): + def __enter__(self): + return self - class FakeResponse(io.BytesIO): - def __enter__(self): - return self + def __exit__(self, exc_type, exc, tb): + return False - def __exit__(self, exc_type, exc, tb): - return False - class UnlinkedInodeFile(io.FileIO): - def write(self, data): - raise FileNotFoundError(2, "No such file or directory") +class _UnlinkedInodeFile(io.BufferedRandom): + """Buffered stream whose flushes fail like gocryptfs does on an unlinked + inode; ``close()`` flushes too, so it fails as well.""" + + def flush(self): + raise FileNotFoundError(2, "No such file or directory") + + +def _fd_is_closed(fd: int) -> bool: + try: + os.fstat(fd) + except OSError: + return True + return False + +def _invoke_url_install(): + return runner.invoke( + app, + [ + "extension", + "add", + "test-ext", + "--from", + "https://example.com/test-ext.zip", + ], + ) + + +def _patch_fdopen(monkeypatch: pytest.MonkeyPatch, failure: str, opened: dict) -> None: + """Make the transient download file fail on ``fdopen`` or on flush.""" real_fdopen = os.fdopen def fake_fdopen(fd, mode="r", *args, **kwargs): - if mode == "w+b": - return UnlinkedInodeFile(fd, "r+") - return real_fdopen(fd, mode, *args, **kwargs) + if mode != "w+b": + return real_fdopen(fd, mode, *args, **kwargs) + opened["fd"] = fd + if failure == "fdopen": + raise OSError(errno.EIO, "fdopen failed") + opened["stream"] = _UnlinkedInodeFile(io.FileIO(fd, "r+")) + return opened["stream"] + + monkeypatch.setattr(os, "fdopen", fake_fdopen) + + +@pytest.mark.parametrize("failure", ["fdopen", "flush"]) +def test_url_install_tolerates_fs_rejecting_writes_to_unlinked_file( + project_dir: Path, monkeypatch: pytest.MonkeyPatch, failure: str +) -> None: + """Filesystems such as gocryptfs (FUSE) fail with ``ENOENT`` when flushing + to an already-unlinked inode; the install must still succeed from the + in-memory archive instead of aborting, without leaking the descriptor.""" + opened: dict[str, object] = {} + captured: dict[str, object] = {} def fake_install( self, @@ -439,6 +478,9 @@ def fake_install( *, archive_file=None, ): + captured["fd_closed"] = _fd_is_closed(opened["fd"]) + stream = opened.get("stream") + captured["stream_closed"] = stream is None or stream.closed captured["bytes"] = archive_file.read() return SimpleNamespace( id="test-ext", @@ -449,27 +491,69 @@ def fake_install( commands=[], ) - monkeypatch.setattr(os, "fdopen", fake_fdopen) + _patch_fdopen(monkeypatch, failure, opened) monkeypatch.setattr(typer, "confirm", lambda *args, **kwargs: True) monkeypatch.setattr( ExtensionCatalog, "_open_url", - lambda *args, **kwargs: FakeResponse(_MINIMAL_ZIP_BYTES), + lambda *args, **kwargs: _FakeResponse(_MINIMAL_ZIP_BYTES), ) monkeypatch.setattr(ExtensionManager, "install_from_zip", fake_install) monkeypatch.setattr(_commands, "_refresh_events_and_warn", lambda root: None) monkeypatch.setattr(_commands, "load_init_options", lambda root: {}) - result = runner.invoke( - app, - [ - "extension", - "add", - "test-ext", - "--from", - "https://example.com/test-ext.zip", - ], - ) + result = _invoke_url_install() assert result.exit_code == 0, result.output - assert captured["bytes"] == _MINIMAL_ZIP_BYTES + assert captured == { + "fd_closed": True, + "stream_closed": True, + "bytes": _MINIMAL_ZIP_BYTES, + } + + +def _zip_directory(source: Path, extra: dict[str, str] | None = None) -> bytes: + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + for path in sorted(source.rglob("*")): + if path.is_file(): + archive.write(path, path.relative_to(source).as_posix()) + for name, content in (extra or {}).items(): + archive.writestr(name, content) + return buffer.getvalue() + + +@pytest.mark.parametrize("unsafe", [False, True], ids=["valid", "path-traversal"]) +def test_url_install_fallback_uses_real_manager( + project_dir: Path, + extension_dir: Path, + monkeypatch: pytest.MonkeyPatch, + unsafe: bool, +) -> None: + """The in-memory fallback archive goes through the real installer: a valid + extension installs and an unsafe archive is still rejected.""" + extra = {"../escaped.txt": "pwned"} if unsafe else None + archive_bytes = _zip_directory(extension_dir, extra) + + _patch_fdopen(monkeypatch, "flush", {}) + monkeypatch.setattr(typer, "confirm", lambda *args, **kwargs: True) + monkeypatch.setattr( + ExtensionCatalog, + "_open_url", + lambda *args, **kwargs: _FakeResponse(archive_bytes), + ) + monkeypatch.setattr(_commands, "_refresh_events_and_warn", lambda root: None) + monkeypatch.setattr(_commands, "load_init_options", lambda root: {}) + + result = _invoke_url_install() + + installed = project_dir / ".specify" / "extensions" / "test-ext" + if unsafe: + assert result.exit_code == 1, result.output + assert "Unsafe path" in result.output + assert not installed.exists() + assert not (project_dir / ".specify" / "extensions" / "escaped.txt").exists() + else: + assert result.exit_code == 0, result.output + assert (installed / "extension.yml").is_file() + assert (installed / "commands" / "hello.md").is_file()