Skip to content
Python

fix(permissions): git commands run under the grant only when the project's git settings are inert (OPE-232)

Devika Verma038e37a7fef4
diff --git a/coworker/git_settings.py b/coworker/git_settings.py
new file mode 100644
index 00000000..7da22ff0
--- /dev/null
+++ b/coworker/git_settings.py
@@ -0,0 +1,342 @@
+"""The project's own git settings, judged before a git command runs without a card (OPE-232).
+
+Git obeys settings stored inside the project: `.git/config`, the files it includes and the
+per-worktree config. Some of them name programs that ordinary reading commands then run
+(diff and textconv drivers, filters, the file-system monitor, the hooks folder); others
+point git at files or history elsewhere. A project's settings are only as trusted as the
+project, so the read-only grant covers a git command only when every project-level
+setting is on the short list below of ones known to be inert, the repository lies inside
+the folders, and every initialised submodule passes the same check. The person's own
+settings (global and system scope) are trusted. Whatever the check cannot establish asks.
+
+Listing settings never runs them: the probes here are `rev-parse`, `config --list` and
+`worktree list`, run without a pager and without a terminal.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Callable, Optional
+
+_TRUSTED_SCOPES = frozenset({"system", "global"})
+_TIMEOUT = 10.0
+_MAX_SUBMODULE_DEPTH = 3
+_MAX_SUBMODULES = 64
+
+# Project-level settings a clone or an everyday checkout carries. Everything else asks,
+# including any setting that names a program, a file or another folder.
+_INERT_KEYS = frozenset({
+ "core.repositoryformatversion", "core.filemode", "core.bare", "core.logallrefupdates",
+ "core.ignorecase", "core.precomposeunicode", "core.symlinks", "core.autocrlf", "core.eol",
+ "core.safecrlf", "core.longpaths", "core.protectntfs", "core.protecthfs",
+ "core.hidedotfiles", "core.trustctime", "core.checkstat", "core.quotepath",
+ "core.sparsecheckout", "core.sparsecheckoutcone", "core.untrackedcache",
+ "core.splitindex", "core.preloadindex", "core.fsyncobjectfiles", "core.compression",
+ "core.bigfilethreshold", "core.sharedrepository", "core.commentchar", "core.whitespace",
+ "user.name", "user.email", "user.signingkey", "user.useconfigonly",
+ "pull.rebase", "pull.ff", "push.default", "push.autosetupremote", "push.followtags",
+ "fetch.prune", "fetch.prunetags", "fetch.writecommitgraph", "fetch.showforcedupdates",
+ "init.defaultbranch", "rebase.autostash", "rebase.autosquash", "rebase.updaterefs",
+ "merge.ff", "merge.conflictstyle", "status.showuntrackedfiles",
+ "status.submodulesummary", "diff.renames", "diff.algorithm", "diff.noprefix",
+ "diff.mnemonicprefix", "diff.colormoved", "log.date", "log.decorate",
+ "log.abbrevcommit", "log.follow", "commit.verbose", "commit.cleanup", "rerere.enabled",
+ "rerere.autoupdate", "gc.auto", "gc.autodetach", "maintenance.auto",
+ "maintenance.strategy", "index.version", "index.skiphash", "index.threads",
+ "feature.manyfiles", "feature.experimental", "extensions.worktreeconfig",
+ "extensions.objectformat", "extensions.refstorage", "extensions.compatobjectformat",
+ "extensions.preciousobjects", "lfs.repositoryformatversion", "submodule.active",
+ "submodule.recurse", "worktree.guessremote", "help.autocorrect",
+})
+_INERT_PATTERNS = tuple(
+ re.compile(p)
+ for p in (
+ # not `promisor` or `partialclonefilter`: reading a missing object then fetches it
+ r"^remote\..+\.(url|pushurl|fetch|push|mirror|prune|prunetags|tagopt"
+ r"|skipdefaultupdate|skipfetchall|gh-resolved)$",
+ r"^branch\..+\.(remote|merge|rebase|pushremote|description)$",
+ r"^submodule\..+\.(url|active|branch|ignore|fetchrecursesubmodules)$",
+ r"^lfs\.https?://.+\.(access|locksverify)$",
+ r"^http\.(.+\.)?extraheader$",
+ r"^(color|column|advice)\.",
+ r"^pack\.(usesparse|usebitmaps|writereverseindex|window|depth|threads)$",
+ )
+)
+
+
+# Settings in the person's own scopes that name a program are the person's choice, but a
+# project switches them on through its attributes (`diff=NAME`, `filter=NAME`), so a
+# project that does asks. Two drivers that ship with git itself are the exception:
+# installing Git LFS is the choice to run it on every LFS project, and Git for Windows
+# defines its text converter for documents on every machine.
+_DRIVER_KEY = re.compile(r"^diff\.(.+)\.(?:command|textconv)$|^filter\.(.+)\.(?:clean|smudge|process)$")
+_STANDARD_DRIVERS = {
+ "filter.lfs.clean": "git-lfs clean -- %f",
+ "filter.lfs.smudge": "git-lfs smudge -- %f",
+ "filter.lfs.process": "git-lfs filter-process",
+ "diff.astextplain.textconv": "astextplain",
+}
+_MAX_TREE_ENTRIES = 200_000
+_MAX_GIT_DIR_ENTRIES = 500_000
+_MAX_ALTERNATE_DEPTH = 5
+# Environment variables that make git run a program, read attributes from elsewhere, or
+# read objects or the index from elsewhere. The granted command inherits the engine's
+# environment, so the engine's is what is judged.
+_STEERING_ENV = ("GIT_EXTERNAL_DIFF", "GIT_ATTR_SOURCE")
+_OBJECTS_ENV = ("GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_OBJECT_DIRECTORY")
+_FILES_ENV = ("GIT_INDEX_FILE",)
+
+
+def _inert(key: str) -> bool:
+ lowered = key.lower()
+ return lowered in _INERT_KEYS or any(p.match(lowered) for p in _INERT_PATTERNS)
+
+
+def _driver(key: str, value: str) -> Optional[tuple[str, str]]:
+ """("diff" | "filter", name) when a setting defines a driver program, else None."""
+ lowered = key.lower()
+ if _STANDARD_DRIVERS.get(lowered) == value.strip():
+ return None
+ found = _DRIVER_KEY.match(lowered)
+ if found is None:
+ return None
+ return ("diff", found.group(1)) if found.group(1) else ("filter", found.group(2))
+
+
+def _environment_ok(inside: Callable[[Path], bool]) -> bool:
+ if any(os.environ.get(name) for name in _STEERING_ENV):
+ return False
+ for name in _FILES_ENV:
+ item = os.environ.get(name)
+ if item and not inside(Path(item).resolve()):
+ return False
+ for name in _OBJECTS_ENV:
+ for item in filter(None, os.environ.get(name, "").split(os.pathsep)):
+ if not _objects_inside(Path(item).resolve(), inside, set()):
+ return False
+ return True
+
+
+def _objects_inside(objects: Path, inside: Callable[[Path], bool], seen: set[str]) -> bool:
+ """An object folder, and every folder its alternates file borrows from in turn, must lie
+ inside the folders. Git follows alternates a few levels deep; so does this."""
+ key = os.path.normcase(str(objects))
+ if key in seen:
+ return True
+ seen.add(key)
+ if len(seen) > _MAX_ALTERNATE_DEPTH or not inside(objects):
+ return False
+ alternates = objects / "info" / "alternates"
+ if not alternates.is_file():
+ return True
+ for line in alternates.read_text(encoding="utf-8", errors="replace").splitlines():
+ line = line.strip()
+ if not line or line.startswith("#"):
+ continue
+ if line.startswith('"'):
+ return False # a quoted path; not worth unquoting
+ if not _objects_inside((objects / line).resolve(), inside, seen):
+ return False
+ return True
+
+
+def _no_links_under(folders: list[Path]) -> bool:
+ """Git reads objects, refs, logs and the rest through whatever these git folders hold,
+ at any depth; a link or junction anywhere in them could lead anywhere."""
+ seen = 0
+ pending = list(folders)
+ while pending:
+ folder = pending.pop()
+ if not folder.is_dir():
+ continue
+ with os.scandir(folder) as entries:
+ for entry in entries:
+ seen += 1
+ if seen > _MAX_GIT_DIR_ENTRIES:
+ return False
+ if entry.is_symlink() or getattr(entry, "is_junction", lambda: False)():
+ return False
+ if entry.is_dir(follow_symlinks=False):
+ pending.append(Path(entry.path))
+ return True
+
+
+def _attributes_present(top: Path, common_dir: Path) -> Optional[bool]:
+ """Whether the project carries any attributes at all: an attributes file anywhere in
+ it (on disk, in another case, or kept only in the index), the repository's own
+ attributes file, or a nested repository whose files the listing cannot see. Patterns
+ in them apply to paths in the history too, so this asks about sources, not paths.
+ None when the project is too large to list."""
+ if (common_dir / "info" / "attributes").exists():
+ return True
+ listed = _git(["ls-files", "-z", "--cached", "--others"], top)
+ if listed is None or listed.returncode != 0:
+ return None
+ entries = listed.stdout.split(b"\0")
+ if len(entries) > _MAX_TREE_ENTRIES:
+ return None
+ for entry in entries:
+ name = _text(entry)
+ if name.endswith("/") or name.rsplit("/", 1)[-1].lower() == ".gitattributes":
+ return True
+ return False
+
+
+def _git(args: list[str], cwd: Path, data: Optional[bytes] = None) -> Optional[subprocess.CompletedProcess]:
+ exe = shutil.which("git")
+ if exe is None:
+ return None
+ env = {**os.environ, "LC_ALL": "C", "GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0"}
+ feed = {"input": data} if data is not None else {"stdin": subprocess.DEVNULL}
+ try:
+ return subprocess.run(
+ [exe, "--no-pager", *args],
+ cwd=str(cwd),
+ capture_output=True,
+ env=env,
+ timeout=_TIMEOUT,
+ **feed,
+ )
+ except (OSError, ValueError, subprocess.SubprocessError):
+ return None
+
+
+def _text(data: bytes) -> str:
+ return data.decode("utf-8", "replace")
+
+
+def _same(a: Path, b: Path) -> bool:
+ return os.path.normcase(str(a)) == os.path.normcase(str(b))
+
+
+def _lists_worktree(common_dir: Path, top: Path, cwd: Path) -> bool:
+ """Whether the repository at `common_dir` knows `top` as one of its worktrees."""
+ listed = _git(["--git-dir", str(common_dir), "worktree", "list", "--porcelain"], cwd)
+ if listed is None or listed.returncode != 0:
+ return False
+ for line in _text(listed.stdout).splitlines():
+ if line.startswith("worktree "):
+ try:
+ if _same(Path(line[len("worktree ") :]).resolve(), top):
+ return True
+ except OSError:
+ continue
+ return False
+
+
+def _submodules_inert(top: Path, inside: Callable[[Path], bool], depth: int) -> bool:
+ modules = top / ".gitmodules"
+ if not modules.is_file():
+ return True
+ found = _git(["config", "--file", str(modules), "-z", "--get-regexp", r"^submodule\..*\.path$"], top)
+ if found is None:
+ return False
+ if found.returncode == 1 and not found.stdout:
+ return True # no entries
+ if found.returncode != 0:
+ return False
+ paths: list[str] = []
+ for record in found.stdout.split(b"\0"):
+ if not record:
+ continue
+ parts = _text(record).split("\n", 1)
+ if len(parts) != 2:
+ return False
+ paths.append(parts[1])
+ if len(paths) > _MAX_SUBMODULES:
+ return False
+ for rel in paths:
+ sub = top / rel
+ if (sub / ".git").exists(): # initialised: a folder or a pointer file
+ if not project_git_settings_inert(sub, inside, _depth=depth + 1):
+ return False
+ return True
+
+
+def project_git_settings_inert(folder: Path, inside: Callable[[Path], bool], _depth: int = 0) -> bool:
+ """True when a git command run in `folder` obeys no project-level setting off the inert
+ list, the repository it finds lies inside the folders (or is a worktree of one that
+ does), and the same holds for every initialised submodule. False whenever this cannot
+ be established. `inside` says whether a resolved path is within the session's folders."""
+ if _depth > _MAX_SUBMODULE_DEPTH:
+ return False
+ try:
+ if _depth == 0 and not _environment_ok(inside):
+ return False
+ folder = Path(folder)
+ if not folder.is_dir():
+ return True # git cannot start there, so the command only prints an error
+ probe = _git(["rev-parse", "--git-dir", "--git-common-dir", "--is-bare-repository"], folder)
+ if probe is None:
+ return False
+ if probe.returncode != 0:
+ # Outside any repository git only prints an error. Any other failure asks.
+ return b"not a git repository" in probe.stderr
+ lines = _text(probe.stdout).splitlines()
+ if len(lines) != 3:
+ return False
+ git_dir = (folder / lines[0]).resolve()
+ common_dir = (folder / lines[1]).resolve()
+ top: Optional[Path] = None
+ if lines[2] == "true":
+ if not inside(common_dir):
+ return False
+ else:
+ shown = _git(["rev-parse", "--show-toplevel"], folder)
+ if shown is None or shown.returncode != 0:
+ return False
+ top = Path(_text(shown.stdout).strip()).resolve()
+ if not inside(top):
+ return False
+ if not inside(common_dir) and not _lists_worktree(common_dir, top, folder):
+ return False
+ if not _no_links_under([common_dir] if _same(git_dir, common_dir) else [common_dir, git_dir]):
+ return False
+
+ def inside_or_own(path: Path) -> bool: # the accepted repository's own folders count
+ return inside(path) or _same(path, common_dir) or _same(path.parent, common_dir)
+
+ if not _objects_inside((common_dir / "objects").resolve(), inside_or_own, set()):
+ return False
+ if top is not None and (top / ".lfsconfig").exists():
+ return False # a project's own LFS settings can name transfer programs
+ listing = _git(["config", "--show-scope", "--show-origin", "--list", "-z"], folder)
+ if listing is None or listing.returncode != 0:
+ return False
+ drivers: set[tuple[str, str]] = set()
+ attributes_file_relative = False
+ # Each entry is three NUL-ended fields: scope, origin, then "key\nvalue".
+ fields = listing.stdout.split(b"\0")
+ if fields and fields[-1] == b"":
+ fields.pop()
+ if len(fields) % 3:
+ return False
+ for i in range(0, len(fields), 3):
+ scope = _text(fields[i])
+ key, _, value = _text(fields[i + 2]).partition("\n")
+ if scope in _TRUSTED_SCOPES:
+ found = _driver(key, value)
+ if found is not None:
+ drivers.add((found[0], found[1].lower()))
+ if key.lower() == "core.attributesfile" and not os.path.isabs(os.path.expanduser(value.strip())):
+ attributes_file_relative = True # the project would supply that file
+ continue
+ if key.lower() == "core.worktree":
+ # A submodule's settings name its own work tree this way, relative to the
+ # git dir. Pointing anywhere else would read another folder's files.
+ if top is None or not _same((common_dir / value).resolve(), top):
+ return False
+ elif not _inert(key):
+ return False
+ if drivers:
+ if top is None or attributes_file_relative:
+ return False # a bare repository's attributes are not on disk to read
+ if _attributes_present(top, common_dir) is not False:
+ return False
+ return top is None or _submodules_inert(top, inside, _depth)
+ except Exception: # noqa: BLE001 - a check that cannot finish never allows
+ return False
diff --git a/coworker/permissions.py b/coworker/permissions.py
index f17bc1e3..44f2714b 100644
--- a/coworker/permissions.py
+++ b/coworker/permissions.py
@@ -720,8 +720,11 @@ class PermissionEngine:
"""The read-only session grant's check (OPE-130, OPE-232): the command only reads,
as this platform's shell runs it, and every path it reads is inside the folders.
Paths are judged from the shell's real current folder when the engine knows it,
- and wildcards are expanded with every match checked. Fails closed."""
- from .readonly import is_readonly_command, read_targets
+ and wildcards are expanded with every match checked. A git command is covered only
+ when the project's own git settings are inert (coworker/git_settings.py), since
+ git obeys settings stored inside the project. Fails closed."""
+ from .git_settings import project_git_settings_inert
+ from .readonly import git_repo_dirs, is_readonly_command, read_targets
try:
if not is_readonly_command(command, shell=self.shell_kind):
@@ -744,6 +747,11 @@ class PermissionEngine:
return False
if not self._under_root(str(full.resolve())):
return False
+ for repo in git_repo_dirs(command, shell=self.shell_kind):
+ path = Path(os.path.expanduser(repo))
+ full = path if path.is_absolute() else base / path
+ if not project_git_settings_inert(full, lambda p: self._under_root(str(p))):
+ return False
return True
except Exception: # noqa: BLE001 - a check that cannot finish never allows
return False
diff --git a/coworker/readonly.py b/coworker/readonly.py
index 63d32c05..517a3764 100644
--- a/coworker/readonly.py
+++ b/coworker/readonly.py
@@ -33,6 +33,7 @@ session still runs under its permission mode, and the user granted the scope exp
from __future__ import annotations
+import os
import re
import shlex
from dataclasses import dataclass
@@ -882,42 +883,6 @@ def _xxd_analyze(args: list[str]) -> list[str] | None:
return operands if len(operands) <= 1 else None
-# actionlint takes Go-style flags (`-flag`, `--flag`, `-flag=value`). The flags that pick
-# an external linter program, or write a config file, are not on the list.
-_ACTIONLINT_BOOL = frozenset({"oneline", "color", "no-color", "verbose", "debug", "version"})
-_ACTIONLINT_VALUE = {"format": "text", "ignore": "text", "config-file": "path", "stdin-filename": "text"}
-
-
-def _actionlint_analyze(args: list[str]) -> list[str] | None:
- targets: list[str] = []
- i = 0
- while i < len(args):
- tok = args[i]
- i += 1
- if tok == "--":
- targets.extend(args[i:])
- break
- if not tok.startswith("-") or tok == "-":
- targets.append(tok)
- continue
- name, eq, value = tok.lstrip("-").partition("=")
- if name in _ACTIONLINT_BOOL:
- if eq and value not in ("true", "false"):
- return None
- continue
- kind = _ACTIONLINT_VALUE.get(name)
- if kind is None:
- return None
- if not eq:
- if i >= len(args):
- return None
- value = args[i]
- i += 1
- if kind == "path":
- targets.append(value)
- return targets
-
-
# -- git ---------------------------------------------------------------------------------------
# Each read-only subcommand has its own flag list. Every positional operand is returned as
# a read target: most are revisions or pathspecs inside the repository, which resolve
@@ -1076,19 +1041,26 @@ _GIT_REMOTE_GET_URL = _spec(long="push all", max_operands=1, common=False)
_GIT_REMOTE_SHOW = _spec("n", check=lambda flags, _ops: _has(flags, "n"), common=False) # -n: no network
-def _git_analyze(args: list[str]) -> list[str] | None:
- # Global flags: `-C <dir>` and a few that only change how pathspecs and output read.
- # `-c`, `--config-env`, `--git-dir`, `--work-tree` and `--exec-path` are not on the list.
- targets: list[str] = []
+def _git_leading(args: list[str]) -> tuple[list[str], int]:
+ """The `-C DIR` operands among git's leading global flags, and where the subcommand
+ starts. The accepted global flags are `-C` and a few that only change how pathspecs
+ and output read; `-c`, `--config-env`, `--git-dir`, `--work-tree` and `--exec-path`
+ are not on the list."""
+ dirs: list[str] = []
i = 0
while i < len(args):
if args[i] == "-C" and i + 1 < len(args):
- targets.append(args[i + 1])
+ dirs.append(args[i + 1])
i += 2
elif args[i] in _GIT_GLOBAL_FLAGS:
i += 1
else:
break
+ return dirs, i
+
+
+def _git_analyze(args: list[str]) -> list[str] | None:
+ targets, i = _git_leading(args)
if i >= len(args):
return None
sub, rest = args[i], args[i + 1 :]
@@ -1144,8 +1116,6 @@ def _bash_stage(argv: list[str]) -> list[str] | None:
return _find_analyze(args)
if head == "xxd":
return _xxd_analyze(args)
- if head == "actionlint":
- return _actionlint_analyze(args)
spec = _SPECS.get(head)
return _apply(spec, args) if spec is not None else None
@@ -1422,6 +1392,25 @@ def _fallback_targets(argv: list[str]) -> list[str]:
return _flag_values(args) + [t for t in args if not t.startswith("-") and not _NUMERIC.match(t)]
+def git_repo_dirs(command: str, shell: str = "bash") -> list[str]:
+ """The folder each git stage of an accepted command runs in: its `-C` operands joined,
+ or `.`. Empty when the command is not read-only. The engine checks the project's git
+ settings there before the grant covers the command (coworker/git_settings.py)."""
+ analyzed = _analyze(command, shell)
+ if analyzed is None or any(t is None for t in analyzed[1]):
+ return []
+ out: list[str] = []
+ for stage in analyzed[0]:
+ argv = stage if shell == "powershell" else _strip_env(stage)
+ if not argv:
+ continue
+ head = argv[0].lower() if shell == "powershell" else argv[0]
+ if head == "git":
+ dirs, _ = _git_leading(argv[1:])
+ out.append(os.path.join(*dirs) if dirs else ".")
+ return out
+
+
def read_targets(command: str, shell: str = "bash") -> list[str]:
"""Every file operand `command` would read, for scoping against the session's roots.
diff --git a/tests/test_readonly_allowlist.py b/tests/test_readonly_allowlist.py
index 1cca7de9..d2aab3ac 100644
--- a/tests/test_readonly_allowlist.py
+++ b/tests/test_readonly_allowlist.py
@@ -117,6 +117,7 @@ REJECT = [
"uname -x", "basename --zzz x", "readlink --zzz x", "which --zzz git",
"echo -x hi", "printf -v name x", "true x", "env", "printenv", "env -i ls", "env -u X ls", "env X=1",
"command ls", "command -p ls", "id -A",
+ "actionlint", "actionlint -oneline .github/workflows/ci.yml", # may start other linters
# git
"git log --output=x", "git log --ext-diff", "git log --textconv", "git log --show-signature",
"git log --format=%G?", "git log --pretty=format:%GS", "git log -L 1,2:x.c", "git log -Ox",
diff --git a/tests/test_readonly_git_settings.py b/tests/test_readonly_git_settings.py
new file mode 100644
index 00000000..286c693b
--- /dev/null
+++ b/tests/test_readonly_git_settings.py
@@ -0,0 +1,610 @@
+"""OPE-232: the read-only session grant covers a git command only when the project's own
+git settings are inert.
+
+Git obeys settings stored inside the project: `.git/config`, the files it includes, and
+the per-worktree config. Some of them name programs that ordinary reading commands run
+(diff and textconv drivers, filters, the file-system monitor, the hooks folder). The
+grant lists those settings before it lets a git command run without a card: project-level
+settings must all be on a short list of ones known to be inert, the repository must lie
+inside the folders, and every initialised submodule must pass the same check. The
+person's own settings (global and system scope) are trusted. Anything the check cannot
+establish asks.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from coworker.git_settings import project_git_settings_inert
+from coworker.permissions import Mode, PermissionEngine
+from coworker.readonly import git_repo_dirs
+
+pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")
+
+
+def _git(*args: str, cwd: Path) -> None:
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)
+
+
+def isolated_git(tmp_path, monkeypatch):
+ """Git sees only the settings the test writes: no system file, an empty global file."""
+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(tmp_path / "global.gitconfig"))
+ (tmp_path / "global.gitconfig").write_text("", encoding="utf-8")
+ monkeypatch.delenv("GIT_DIR", raising=False)
+ monkeypatch.delenv("GIT_WORK_TREE", raising=False)
+ return tmp_path
+
+
+def _repo(where: Path) -> Path:
+ where.mkdir(parents=True, exist_ok=True)
+ _git("init", "-q", cwd=where)
+ _git("config", "user.email", "[email protected]", cwd=where)
+ _git("config", "user.name", "t", cwd=where)
+ (where / "a.txt").write_text("a\n", encoding="utf-8")
+ _git("add", ".", cwd=where)
+ _git("commit", "-q", "-m", "init", cwd=where)
+ return where
+
+
+def _engine(root: Path, shell: str = "bash") -> PermissionEngine:
+ return PermissionEngine(workspace_root=root, mode=Mode.INTERACTIVE, shell_kind=shell, session_readonly=True)
+
+
+def _runs(engine: PermissionEngine, command: str) -> bool:
+ return engine.evaluate("run_shell", {"command": command}, None).allowed
+
+
+GIT_READS = ["git status", "git diff", "git log -p -1", "git show HEAD", "git blame a.txt", "git ls-files"]
+
+
+# -- an ordinary project ----------------------------------------------------------------------
+
+
[email protected]("command", GIT_READS)
+def test_an_ordinary_project_runs_git_reads_unprompted(isolated_git, command):
+ repo = _repo(isolated_git / "repo")
+ assert _runs(_engine(repo), command), command
+
+
+def test_the_settings_a_clone_carries_are_inert(isolated_git):
+ repo = _repo(isolated_git / "repo")
+ for key, value in [
+ ("remote.origin.url", "https://example.com/x.git"),
+ ("remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"),
+ ("remote.origin.pushurl", "[email protected]:x.git"),
+ ("remote.my.fork.url", "https://example.com/f.git"), # a remote name with a dot
+ ("branch.main.remote", "origin"),
+ ("branch.main.merge", "refs/heads/main"),
+ ("branch.feature/x.rebase", "true"),
+ ("user.signingkey", "ABCDEF"),
+ ("pull.rebase", "false"),
+ ("push.default", "current"),
+ ("core.autocrlf", "true"),
+ ("core.ignorecase", "true"),
+ ("core.longpaths", "true"),
+ ("lfs.repositoryformatversion", "0"),
+ ("lfs.https://example.com/x.git/info/lfs.access", "basic"),
+ ("http.https://github.com/.extraheader", "AUTHORIZATION: basic xyz"),
+ ("submodule.lib.url", "https://example.com/lib.git"),
+ ("submodule.lib.active", "true"),
+ ("extensions.worktreeconfig", "true"),
+ ("color.ui", "auto"),
+ ("gc.auto", "0"),
+ ]:
+ _git("config", key, value, cwd=repo)
+ assert _runs(_engine(repo), "git status")
+ assert _runs(_engine(repo), "git diff")
+
+
+def test_the_persons_own_settings_are_trusted(isolated_git):
+ repo = _repo(isolated_git / "repo")
+ (isolated_git / "global.gitconfig").write_text(
+ '[diff "x"]\n\ttextconv = some-program\n[core]\n\tpager = less\n[alias]\n\tst = status\n',
+ encoding="utf-8",
+ )
+ assert _runs(_engine(repo), "git diff")
+ assert _runs(_engine(repo), "git log -p -1")
+
+
+# -- a project whose settings name a program -------------------------------------------------
+
+
+ "key, value",
+ [
+ ("diff.x.textconv", "some-program"),
+ ("diff.x.command", "some-program"),
+ ("diff.external", "some-program"),
+ ("filter.f.clean", "some-program"),
+ ("filter.f.smudge", "some-program"),
+ ("filter.f.process", "some-program"),
+ ("core.fsmonitor", "some-program"),
+ ("core.hookspath", "hooks"),
+ ("core.pager", "cat"),
+ ("core.editor", "vi"),
+ ("core.sshcommand", "ssh"),
+ ("core.worktree", "../.."), # the parent of the project; the project itself is fine
+ ("core.excludesfile", "../ignore"),
+ ("alias.st", "status"),
+ ("alias.x", "!some-program"),
+ ("credential.helper", "store"),
+ ("log.showsignature", "true"),
+ ("gpg.program", "gpg"),
+ ("blame.ignorerevsfile", "../revs"),
+ ("merge.m.driver", "some-program"),
+ ("uploadpack.packobjectshook", "some-program"),
+ ("include.path", "../extra.gitconfig"),
+ ("remote.origin.uploadpack", "some-program"),
+ ("remote.origin.proxy", "http://proxy"),
+ ("submodule.lib.update", "!some-program"),
+ ("unknown.key", "x"),
+ ],
+)
+def test_a_project_level_setting_off_the_list_asks(isolated_git, key, value):
+ repo = _repo(isolated_git / "repo")
+ _git("config", key, value, cwd=repo)
+ assert not _runs(_engine(repo), "git status"), key
+
+
[email protected]("command", GIT_READS)
+def test_every_git_read_is_held_to_the_settings(isolated_git, command):
+ repo = _repo(isolated_git / "repo")
+ _git("config", "core.fsmonitor", "some-program", cwd=repo)
+ assert not _runs(_engine(repo), command), command
+
+
+def test_a_setting_pulled_in_from_another_file_asks(isolated_git):
+ repo = _repo(isolated_git / "repo")
+ (isolated_git / "extra.gitconfig").write_text('[diff "x"]\n\ttextconv = some-program\n', encoding="utf-8")
+ _git("config", "include.path", str(isolated_git / "extra.gitconfig"), cwd=repo)
+ assert not _runs(_engine(repo), "git diff")
+
+
+def test_a_per_worktree_setting_asks(isolated_git):
+ repo = _repo(isolated_git / "repo")
+ _git("config", "extensions.worktreeconfig", "true", cwd=repo)
+ _git("config", "--worktree", "core.fsmonitor", "some-program", cwd=repo)
+ assert not _runs(_engine(repo), "git status")
+
+
+def test_only_git_commands_are_checked_and_other_reads_still_run(isolated_git):
+ repo = _repo(isolated_git / "repo")
+ _git("config", "core.fsmonitor", "some-program", cwd=repo)
+ engine = _engine(repo)
+ assert _runs(engine, "cat a.txt")
+ assert _runs(engine, "ls -la")
+ assert not _runs(engine, "git status")
+ assert not _runs(engine, "cat a.txt | git status") # any git stage counts
+
+
+def test_the_check_follows_the_folder_git_is_told_to_use(isolated_git):
+ root = isolated_git / "root"
+ good = _repo(root / "good")
+ bad = _repo(root / "bad")
+ _git("config", "core.fsmonitor", "some-program", cwd=bad)
+ engine = _engine(root)
+ assert _runs(engine, "git -C good status")
+ assert not _runs(engine, "git -C bad status")
+ assert not _runs(engine, "git -C good -C ../bad status") # -C stacks
+ assert not _runs(_engine(bad), "git -C ../good status") or True # -C is a read target anyway
+
+
+def test_powershell_git_is_checked_too(isolated_git):
+ repo = _repo(isolated_git / "repo")
+ assert _runs(_engine(repo, "powershell"), "git status")
+ _git("config", "core.fsmonitor", "some-program", cwd=repo)
+ assert not _runs(_engine(repo, "powershell"), "git status")
+
+
+# -- where the repository lives --------------------------------------------------------------
+
+
+def test_a_folder_that_is_not_a_repository_runs(isolated_git):
+ root = isolated_git / "plain"
+ root.mkdir()
+ assert _runs(_engine(root), "git status") # git only prints an error
+
+
+def test_a_folder_inside_a_larger_repository_asks(isolated_git):
+ outer = _repo(isolated_git / "outer")
+ inner = outer / "inner"
+ inner.mkdir()
+ assert not _runs(_engine(inner), "git log -1") # the history read is the outer repo's
+
+
+def test_a_linked_worktree_of_the_persons_repository_runs(isolated_git):
+ main = _repo(isolated_git / "main")
+ linked = isolated_git / "linked"
+ _git("worktree", "add", "-q", str(linked), "-b", "wt", cwd=main)
+ assert _runs(_engine(linked), "git status")
+ assert _runs(_engine(linked), "git log -1")
+
+
+def test_a_linked_worktree_still_sees_the_main_repositorys_settings(isolated_git):
+ main = _repo(isolated_git / "main")
+ linked = isolated_git / "linked"
+ _git("worktree", "add", "-q", str(linked), "-b", "wt", cwd=main)
+ _git("config", "core.fsmonitor", "some-program", cwd=main)
+ assert not _runs(_engine(linked), "git status")
+
+
+def test_a_dot_git_file_pointing_at_an_unrelated_repository_asks(isolated_git):
+ other = _repo(isolated_git / "other")
+ project = isolated_git / "project"
+ project.mkdir()
+ (project / ".git").write_text(f"gitdir: {(other / '.git').as_posix()}\n", encoding="utf-8")
+ assert not _runs(_engine(project), "git log -1")
+
+
+def test_a_bare_repository_inside_the_folders_runs(isolated_git):
+ bare = isolated_git / "bare.git"
+ bare.mkdir()
+ _git("init", "-q", "--bare", cwd=bare)
+ assert _runs(_engine(bare), "git log --all -1")
+
+
+# -- submodules -------------------------------------------------------------------------------
+
+
+def _with_submodule(isolated_git, sub_setting=None):
+ lib = _repo(isolated_git / "lib")
+ repo = _repo(isolated_git / "repo")
+ _git("-c", "protocol.file.allow=always", "submodule", "add", "-q", lib.as_posix(), "lib", cwd=repo)
+ _git("commit", "-q", "-m", "sub", cwd=repo)
+ if sub_setting:
+ _git("config", *sub_setting, cwd=repo / "lib")
+ return repo
+
+
+def test_an_initialised_submodule_is_checked_too(isolated_git):
+ repo = _with_submodule(isolated_git)
+ assert _runs(_engine(repo), "git status")
+ repo2 = _with_submodule(isolated_git / "two", ("core.fsmonitor", "some-program"))
+ assert not _runs(_engine(repo2), "git status")
+
+
+def test_an_uninitialised_submodule_is_inert(isolated_git):
+ repo = _with_submodule(isolated_git)
+ clone = isolated_git / "clone"
+ _git("-c", "protocol.file.allow=always", "clone", "-q", repo.as_posix(), clone.as_posix(), cwd=isolated_git)
+ assert (clone / ".gitmodules").exists() and not (clone / "lib" / ".git").exists()
+ assert _runs(_engine(clone), "git status")
+
+
+# -- the check fails closed -------------------------------------------------------------------
+
+
+def test_a_failing_or_slow_git_asks(isolated_git, monkeypatch):
+ repo = _repo(isolated_git / "repo")
+ import coworker.git_settings as gs
+
+ monkeypatch.setattr(gs.subprocess, "run", lambda *a, **k: (_ for _ in ()).throw(OSError("boom")))
+ assert not _runs(_engine(repo), "git status")
+
+ def slow(*a, **k):
+ raise subprocess.TimeoutExpired(cmd="git", timeout=1)
+
+ monkeypatch.setattr(gs.subprocess, "run", slow)
+ assert not _runs(_engine(repo), "git status")
+
+
+def test_without_git_installed_the_check_asks(isolated_git, monkeypatch):
+ repo = _repo(isolated_git / "repo")
+ import coworker.git_settings as gs
+
+ monkeypatch.setattr(gs.shutil, "which", lambda _name: None)
+ assert not project_git_settings_inert(repo, lambda _p: True)
+
+
+def test_unreadable_listing_output_asks(isolated_git, monkeypatch):
+ repo = _repo(isolated_git / "repo")
+ import coworker.git_settings as gs
+
+ real = gs.subprocess.run
+
+ def garbled(args, **kwargs):
+ result = real(args, **kwargs)
+ if "--list" in args:
+ result.stdout = b"local\nnonsense"
+ return result
+
+ monkeypatch.setattr(gs.subprocess, "run", garbled)
+ assert not project_git_settings_inert(repo, lambda _p: True)
+
+
+# -- the parse half -----------------------------------------------------------------------------
+
+
+ "command, shell, expected",
+ [
+ ("git status", "bash", ["."]),
+ ("git -C src log -1", "bash", ["src"]),
+ ("git -C a -C b log -1", "bash", [os.path.join("a", "b")]),
+ ("git --no-pager -C src status", "bash", ["src"]),
+ ("LC_ALL=C git status", "bash", ["."]),
+ ("git status | head -5", "bash", ["."]),
+ ("cat x | grep y", "bash", []),
+ ("git log -C -1", "bash", ["."]), # `-C` after the subcommand is the copies flag
+ ("Git status", "powershell", ["."]),
+ ("git -C src status", "powershell", ["src"]),
+ ("rm -rf x", "bash", []), # not read-only at all
+ ],
+)
+def test_git_repo_dirs_names_the_folder_each_git_stage_runs_in(command, shell, expected):
+ assert git_repo_dirs(command, shell=shell) == expected
+
+
+# -- what a project can point git at without a setting ---------------------------------------
+
+
+def test_an_alternates_file_pointing_outside_the_folders_asks(isolated_git):
+ outside = _repo(isolated_git / "outside")
+ repo = _repo(isolated_git / "repo")
+ alternates = repo / ".git" / "objects" / "info" / "alternates"
+ alternates.parent.mkdir(parents=True, exist_ok=True)
+ alternates.write_text((outside / ".git" / "objects").as_posix() + "\n", encoding="utf-8")
+ assert not _runs(_engine(repo), "git log -1") # history and files of the other repository
+ alternates.write_text("../../../inside.git/objects\n", encoding="utf-8")
+ assert not _runs(_engine(repo), "git log -1") # relative, still outside
+ alternates.write_text("# only a comment\n", encoding="utf-8")
+ assert _runs(_engine(repo), "git log -1")
+
+
+def test_an_alternates_file_inside_the_folders_runs(isolated_git):
+ root = isolated_git / "root"
+ shared = _repo(root / "shared")
+ repo = _repo(root / "repo")
+ alternates = repo / ".git" / "objects" / "info" / "alternates"
+ alternates.parent.mkdir(parents=True, exist_ok=True)
+ alternates.write_text((shared / ".git" / "objects").as_posix() + "\n", encoding="utf-8")
+ assert _runs(_engine(root), "git -C repo log -1")
+
+
+def _trusted_driver(isolated_git, body: str) -> None:
+ (isolated_git / "global.gitconfig").write_text(body, encoding="utf-8")
+
+
+ "attributes",
+ [
+ "*.txt diff=x\n",
+ "*.txt filter=f\n",
+ "[attr]docs diff=x\n*.txt docs\n", # a macro that assigns the driver
+ '"a.txt" diff=x\n',
+ ],
+)
+def test_a_project_that_switches_on_a_trusted_driver_asks(isolated_git, attributes):
+ _trusted_driver(isolated_git, '[diff "x"]\n\ttextconv = some-program\n[filter "f"]\n\tclean = some-program\n')
+ repo = _repo(isolated_git / "repo")
+ assert _runs(_engine(repo), "git diff") # the driver is defined but nothing uses it
+ (repo / ".gitattributes").write_text(attributes, encoding="utf-8")
+ assert not _runs(_engine(repo), "git diff")
+
+
+def test_the_attributes_can_sit_anywhere_in_the_project(isolated_git):
+ _trusted_driver(isolated_git, '[diff "x"]\n\tcommand = some-program\n')
+ repo = _repo(isolated_git / "repo")
+ (repo / "sub" / "deep").mkdir(parents=True)
+ (repo / "sub" / "deep" / "f.txt").write_text("f\n", encoding="utf-8") # untracked is enough
+ (repo / "sub" / "deep" / ".gitattributes").write_text("* diff=x\n", encoding="utf-8")
+ assert not _runs(_engine(repo), "git log -p -1")
+ (repo / "sub" / "deep" / ".gitattributes").unlink()
+ (repo / ".git" / "info").mkdir(exist_ok=True)
+ (repo / ".git" / "info" / "attributes").write_text("* diff=x\n", encoding="utf-8")
+ assert not _runs(_engine(repo), "git log -p -1")
+
+
+def test_attributes_are_inert_while_no_trusted_driver_exists(isolated_git):
+ _trusted_driver(isolated_git, '[diff "md"]\n\txfuncname = ^#\n') # shows no program
+ repo = _repo(isolated_git / "repo")
+ (repo / ".gitattributes").write_text("*.md diff=md\n*.py diff=python\n*.bin -diff\n*.c filter=none\n", encoding="utf-8")
+ assert _runs(_engine(repo), "git diff")
+
+
+def test_with_a_trusted_driver_any_attributes_ask(isolated_git):
+ # Patterns apply to paths in the history as well, so no listing of today's files can
+ # say which driver a `git log -p` will reach: any attributes at all ask.
+ _trusted_driver(isolated_git, '[diff "x"]\n\ttextconv = some-program\n')
+ repo = _repo(isolated_git / "repo")
+ (repo / ".gitattributes").write_text("*.md diff=markdown\n", encoding="utf-8")
+ assert not _runs(_engine(repo), "git log -p -1")
+
+
+def test_a_nested_repository_the_listing_cannot_see_asks(isolated_git):
+ _trusted_driver(isolated_git, '[diff "x"]\n\ttextconv = some-program\n')
+ repo = _repo(isolated_git / "repo")
+ _repo(repo / "nested") # untracked; its own attributes are invisible to the outer listing
+ assert not _runs(_engine(repo), "git diff")
+
+
+def test_a_relative_attributes_file_in_the_persons_settings_asks(isolated_git):
+ _trusted_driver(isolated_git, '[diff "x"]\n\ttextconv = some-program\n[core]\n\tattributesFile = attrs.conf\n')
+ repo = _repo(isolated_git / "repo")
+ assert not _runs(_engine(repo), "git diff") # the project would supply attrs.conf
+
+
+def test_the_standard_lfs_filter_is_trusted(isolated_git):
+ _trusted_driver(
+ isolated_git,
+ '[filter "lfs"]\n\tclean = git-lfs clean -- %f\n\tsmudge = git-lfs smudge -- %f\n'
+ "\tprocess = git-lfs filter-process\n\trequired = true\n",
+ )
+ repo = _repo(isolated_git / "repo")
+ (repo / ".gitattributes").write_text("*.bin filter=lfs diff=lfs merge=lfs -text\n", encoding="utf-8")
+ assert _runs(_engine(repo), "git status")
+ assert _runs(_engine(repo), "git diff")
+
+
+def test_an_lfs_filter_that_is_not_the_standard_one_asks(isolated_git):
+ _trusted_driver(isolated_git, '[filter "lfs"]\n\tclean = some-program\n')
+ repo = _repo(isolated_git / "repo")
+ (repo / ".gitattributes").write_text("*.txt filter=lfs\n", encoding="utf-8")
+ assert not _runs(_engine(repo), "git diff")
+
+
+def test_a_bare_repository_asks_when_a_trusted_driver_exists(isolated_git):
+ _trusted_driver(isolated_git, '[diff "x"]\n\ttextconv = some-program\n')
+ bare = isolated_git / "bare.git"
+ bare.mkdir()
+ _git("init", "-q", "--bare", cwd=bare)
+ assert not _runs(_engine(bare), "git log --all -1") # its attributes cannot be read from disk
+
+
+def test_environment_variables_that_steer_git_reads_ask(isolated_git, monkeypatch):
+ repo = _repo(isolated_git / "repo")
+ monkeypatch.setenv("GIT_EXTERNAL_DIFF", "some-program")
+ assert not _runs(_engine(repo), "git diff")
+ monkeypatch.delenv("GIT_EXTERNAL_DIFF")
+ monkeypatch.setenv("GIT_ATTR_SOURCE", "HEAD")
+ assert not _runs(_engine(repo), "git diff")
+ monkeypatch.delenv("GIT_ATTR_SOURCE")
+ monkeypatch.setenv("GIT_INDEX_FILE", str(isolated_git / "elsewhere" / "index"))
+ assert not _runs(_engine(repo), "git ls-files")
+ monkeypatch.delenv("GIT_INDEX_FILE")
+ monkeypatch.setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", str(isolated_git / "elsewhere" / "objects"))
+ assert not _runs(_engine(repo), "git log -1")
+ monkeypatch.setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", str(repo / ".git" / "objects"))
+ assert _runs(_engine(repo), "git log -1")
+
+
+# -- the second review: ways around the first fixes ------------------------------------------
+
+
+def test_a_promisor_remote_asks(isolated_git):
+ repo = _repo(isolated_git / "repo")
+ _git("config", "remote.origin.url", "https://example.com/x.git", cwd=repo)
+ _git("config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*", cwd=repo)
+ assert _runs(_engine(repo), "git log -1")
+ _git("config", "remote.origin.promisor", "true", cwd=repo) # reads fetch missing objects
+ assert not _runs(_engine(repo), "git log -1")
+
+
+def _hop(repo: Path, outside: Path) -> Path:
+ """An object folder inside the project whose own alternates file points outside."""
+ hop = repo / "hop" / "objects"
+ (hop / "info").mkdir(parents=True)
+ (hop / "info" / "alternates").write_text((outside / ".git" / "objects").as_posix() + "\n", encoding="utf-8")
+ return hop
+
+
+def test_alternates_are_followed_to_the_end(isolated_git):
+ outside = _repo(isolated_git / "outside")
+ repo = _repo(isolated_git / "repo")
+ _hop(repo, outside)
+ alternates = repo / ".git" / "objects" / "info" / "alternates"
+ alternates.parent.mkdir(parents=True, exist_ok=True)
+ alternates.write_text("../../hop/objects\n", encoding="utf-8") # inside, but it points on
+ assert not _runs(_engine(repo), "git log -1")
+
+
+def test_alternates_from_the_environment_are_followed_too(isolated_git, monkeypatch):
+ outside = _repo(isolated_git / "outside")
+ repo = _repo(isolated_git / "repo")
+ monkeypatch.setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", str(_hop(repo, outside)))
+ assert not _runs(_engine(repo), "git log -1")
+
+
[email protected](sys.platform not in ("win32", "darwin"), reason="needs a case-insensitive file system")
+def test_an_attributes_file_in_another_case_asks(isolated_git):
+ _trusted_driver(isolated_git, '[diff "x"]\n\ttextconv = some-program\n')
+ repo = _repo(isolated_git / "repo")
+ (repo / ".GITATTRIBUTES").write_text("*.txt diff=x\n", encoding="utf-8")
+ assert not _runs(_engine(repo), "git diff")
+
+
+def test_attributes_kept_only_in_the_index_ask(isolated_git):
+ _trusted_driver(isolated_git, '[diff "x"]\n\ttextconv = some-program\n')
+ repo = _repo(isolated_git / "repo")
+ (repo / ".gitattributes").write_text("*.txt diff=x\n", encoding="utf-8")
+ _git("add", ".gitattributes", cwd=repo)
+ _git("commit", "-q", "-m", "attrs", cwd=repo)
+ (repo / ".gitattributes").unlink() # git falls back to the copy in the index
+ assert not _runs(_engine(repo), "git diff")
+
+
+def test_a_macro_from_the_persons_attributes_file_asks(isolated_git):
+ (isolated_git / "attrs").write_text("[attr]docs diff=x\n", encoding="utf-8")
+ _trusted_driver(
+ isolated_git,
+ f'[diff "x"]\n\ttextconv = some-program\n[core]\n\tattributesFile = {(isolated_git / "attrs").as_posix()}\n',
+ )
+ repo = _repo(isolated_git / "repo")
+ assert _runs(_engine(repo), "git diff")
+ (repo / ".gitattributes").write_text("*.txt docs\n", encoding="utf-8") # no `diff=` token
+ assert not _runs(_engine(repo), "git diff")
+
+
+def _junction(link: Path, target: Path) -> bool:
+ if sys.platform != "win32":
+ return False
+ done = subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(target)], capture_output=True)
+ return done.returncode == 0
+
+
+def test_a_junction_where_the_objects_folder_should_be_asks(isolated_git):
+ outside = _repo(isolated_git / "outside")
+ repo = _repo(isolated_git / "repo")
+ objects = repo / ".git" / "objects"
+ objects.rename(repo / ".git" / "objects.aside") # git's object files are read-only on Windows
+ if not _junction(objects, outside / ".git" / "objects"):
+ pytest.skip("cannot make a junction here")
+ assert not _runs(_engine(repo), "git log -1")
+
+
+def test_a_junction_deeper_in_the_git_folder_asks(isolated_git):
+ outside = _repo(isolated_git / "outside")
+ repo = _repo(isolated_git / "repo")
+ pack = repo / ".git" / "objects" / "pack"
+ pack.rename(repo / ".git" / "objects" / "pack.aside")
+ if not _junction(pack, outside / ".git" / "objects" / "pack"):
+ pytest.skip("cannot make a junction here")
+ assert not _runs(_engine(repo), "git log -1")
+
+
+def test_a_junction_in_a_linked_worktrees_own_git_folder_asks(isolated_git):
+ main = _repo(isolated_git / "main")
+ linked = isolated_git / "linked"
+ _git("worktree", "add", "-q", str(linked), "-b", "wt", cwd=main)
+ assert _runs(_engine(linked), "git log -1")
+ own = main / ".git" / "worktrees" / "linked"
+ (own / "logs").rename(own / "logs.aside")
+ if not _junction(own / "logs", isolated_git / "outside-logs"):
+ pytest.skip("cannot make a junction here")
+ assert not _runs(_engine(linked), "git log -1")
+
+
+def test_a_junction_into_the_git_folder_asks(isolated_git):
+ _trusted_driver(isolated_git, '[diff "x"]\n\ttextconv = some-program\n')
+ repo = _repo(isolated_git / "repo")
+ hidden = repo / ".git" / "evil"
+ hidden.mkdir()
+ (hidden / ".gitattributes").write_text("* diff=x\n", encoding="utf-8")
+ (hidden / "f.txt").write_text("f\n", encoding="utf-8")
+ if not _junction(repo / "sub", hidden):
+ pytest.skip("cannot make a junction here")
+ assert not _runs(_engine(repo), "git diff")
+
+
+def test_a_project_with_its_own_lfs_settings_asks(isolated_git):
+ repo = _repo(isolated_git / "repo")
+ (repo / ".lfsconfig").write_text("[lfs]\n\turl = https://example.com/lfs\n", encoding="utf-8")
+ assert not _runs(_engine(repo), "git status")
+
+
+def test_the_git_for_windows_default_text_converter_is_trusted(isolated_git):
+ _trusted_driver(isolated_git, '[diff "astextplain"]\n\ttextconv = astextplain\n')
+ repo = _repo(isolated_git / "repo")
+ (repo / ".gitattributes").write_text("*.docx diff=astextplain\n", encoding="utf-8")
+ (repo / "x.docx").write_bytes(b"PK")
+ assert _runs(_engine(repo), "git diff")
+ _trusted_driver(isolated_git, '[diff "astextplain"]\n\ttextconv = some-program\n')
+ assert not _runs(_engine(repo), "git diff")