From bc70198790648885b40dcff513b2c9c21982c8df Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:57:52 -0600 Subject: [PATCH] chore: migrate shared infrastructure writes to FileHelper Use atomic FileHelper writes for shared scripts, templates, and the managed gitignore while retaining caller-owned overwrite decisions and lifecycle hooks. Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 17 +++-- src/specify_cli/shared_infra.py | 19 +++--- tests/test_shared_infra_script_mode.py | 93 +++++++++++++++++++++++++- 3 files changed, 110 insertions(+), 19 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 58047983f7..b80823fb05 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -4,9 +4,11 @@ explicitly established root. Project-command boundaries now validate persisted policy, and init-options bootstrap I/O uses the helper. Other existing command filesystem operations are **not yet migrated**: loading policy alone does not -enforce symlink behavior on those operations. Shared infrastructure, registration, -managed storage, catalogs, scripts and runtime operations retain their existing -behavior until their dependent migration stages. +enforce symlink behavior on those operations. Shared infrastructure uses the +helper for atomic script, template, and managed `.gitignore` content writes; +other shared infrastructure operations, registration, managed storage, catalogs, +scripts and runtime operations retain their existing behavior until their +dependent migration stages. Only `specify init --allow-symlinks` exposes the setting; init defaults to deny and persists the literal JSON boolean `allow_symlinks` in @@ -462,10 +464,11 @@ can redirect those opens; they do not have the read path's parent-relative handle protection. The helper does not constrain subprocesses or third-party code. -Existing safe-write mechanisms informed this helper, but existing shared -infrastructure warning/skip behavior and development-mode link creation are -unchanged. Migrate one owned operation boundary at a time, carrying original -paths and an explicit root/policy into the helper before any early resolution. +Shared infrastructure content writes always use deny mode. The caller retains +its destination preflight, warning/skip decisions, script modes, and file-change +hooks. Development-mode link creation is unchanged. Migrate one owned operation +boundary at a time, carrying original paths and an explicit root/policy into +the helper before any early resolution. Linked command directories and development-mode registration remain dependent stages. Tree copying is deferred: install callers must retain selection of included entries and establish separate trusted source and destination diff --git a/src/specify_cli/shared_infra.py b/src/specify_cli/shared_infra.py index 5d1b8dff63..a74e5fa5b2 100644 --- a/src/specify_cli/shared_infra.py +++ b/src/specify_cli/shared_infra.py @@ -11,6 +11,7 @@ from pathlib import Path from typing import Any +from .file_helper import FileHelper, SymlinkDeniedError from .integrations.base import IntegrationBase from .integrations.manifest import IntegrationManifest @@ -351,18 +352,14 @@ def _write_shared_bytes( mode: int = 0o644, ) -> None: _ensure_safe_shared_destination(project_path, dest) - from .integrations._file_changes import ( - after_file_change, - atomic_write_bytes, - before_file_change, - ) + from .integrations._file_changes import changing_file - before_file_change(dest) - atomic_write_bytes( - dest, content, mode, exact=True, - before_replace=lambda: _ensure_safe_shared_destination(project_path, dest), - ) - after_file_change(dest) + # Shared infrastructure refuses links even in projects that opt in elsewhere. + with FileHelper(project_path) as files, changing_file(dest): + try: + files.write_bytes(_shared_relative_path(project_path, dest), content, mode=mode) + except SymlinkDeniedError as exc: + raise SymlinkedSharedPathError(str(exc)) from exc _BASH_FORMAT_COMMAND_RE = re.compile( diff --git a/tests/test_shared_infra_script_mode.py b/tests/test_shared_infra_script_mode.py index fa27121775..b5cf1fc6a4 100644 --- a/tests/test_shared_infra_script_mode.py +++ b/tests/test_shared_infra_script_mode.py @@ -1,12 +1,15 @@ -"""Unit tests for the mode shared scripts are written with.""" +"""Unit tests for shared infrastructure writes and script modes.""" from __future__ import annotations import os +import stat +from pathlib import Path import pytest from specify_cli import shared_infra +from specify_cli.integrations._file_changes import file_change_observer from specify_cli.shared_infra import _shared_script_mode SHEBANG = b"#!/usr/bin/env bash\necho hi\n" @@ -57,3 +60,91 @@ def test_windows_keeps_the_packaged_mode(tmp_path, monkeypatch): packaged = source.stat().st_mode & 0o777 monkeypatch.setattr(shared_infra.os, "name", "nt") assert _shared_script_mode(source, SHEBANG) == packaged + + +@pytest.mark.skipif(os.name == "nt", reason="Exercises POSIX mode and filename limits") +def test_shared_script_atomic_overwrite_with_relative_root(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + project = Path("project") + project.mkdir() + destination = project / ("s" * 252 + ".sh") + destination.write_bytes(b"old") + observations = [] + replace = os.replace + + def observe(path, before, removal): + assert path == destination + assert not removal + observations.append((before, path.read_bytes())) + + def check_publish(source, target): + assert Path(target).resolve() == destination.resolve() + assert Path(source).read_bytes() == SHEBANG + assert destination.read_bytes() == b"old" + assert stat.S_IMODE(Path(source).stat().st_mode) == 0o750 + replace(source, target) + + monkeypatch.setattr(os, "replace", check_publish) + token = file_change_observer.set(observe) + try: + shared_infra._write_shared_bytes(project, destination, SHEBANG, mode=0o750) + finally: + file_change_observer.reset(token) + + assert observations == [(True, b"old"), (False, SHEBANG)] + assert stat.S_IMODE(destination.stat().st_mode) == 0o750 + assert list(project.iterdir()) == [destination] + + +def test_failed_shared_text_publish_preserves_original_and_removes_stage(tmp_path, monkeypatch): + destination = tmp_path / "template.md" + destination.write_bytes(b"old") + content = "caf\u00e9\n" + observations = [] + + def refuse_publish(source, target): + assert Path(source).read_bytes() == content.encode("utf-8") + raise PermissionError("injected publish failure") + + monkeypatch.setattr(os, "replace", refuse_publish) + token = file_change_observer.set(lambda *change: observations.append(change)) + try: + with pytest.raises(PermissionError, match="injected publish failure"): + shared_infra._write_shared_text(tmp_path, destination, content) + finally: + file_change_observer.reset(token) + + assert observations == [(destination, True, False)] + assert destination.read_bytes() == b"old" + assert list(tmp_path.iterdir()) == [destination] + + +@pytest.mark.skipif(os.name == "nt", reason="Requires creating a symlink") +def test_shared_write_denies_link_introduced_after_snapshot(tmp_path, monkeypatch): + target = tmp_path / "custom.md" + target.write_bytes(b"custom") + destination = tmp_path / "template.md" + observations = [] + open_file = os.open + + def observe(path, before, removal): + observations.append((path, before, removal)) + if before: + path.symlink_to(target.name) + + def reject_staging(path, flags, *args, **kwargs): + assert not flags & os.O_CREAT, "A denied path must not create a staging file" + return open_file(path, flags, *args, **kwargs) + + monkeypatch.setattr(os, "open", reject_staging) + token = file_change_observer.set(observe) + try: + with pytest.raises(shared_infra.SymlinkedSharedPathError): + shared_infra._write_shared_text(tmp_path, destination, "replacement") + finally: + file_change_observer.reset(token) + + assert observations == [(destination, True, False)] + assert destination.is_symlink() + assert target.read_bytes() == b"custom" + assert set(tmp_path.iterdir()) == {destination, target}