mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-03 21:29:59 -05:00
repos: never write through links in a clone's .git
A clone being imported is controlled by whoever put it in the media directory. A link at .git/wrolpi-repo or .git/config.wrolpi made the marker and the sanitized config write wherever it pointed. The marker is written with O_NOFOLLOW (after removing a link), the sanitized config through mkstemp, and a .git/config which is not a regular file is refused (by Import, and before an update). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c0b9c41ee5
commit
a79278e048
3 changed files with 65 additions and 5 deletions
|
|
@ -138,7 +138,10 @@ class GitDownloader(Downloader):
|
|||
# git runs or where it connects, and it is fetched from the Repo's URL, whatever its origin says.
|
||||
if error := clone_ownership_error(directory, prepared.url):
|
||||
raise DownloadError(error)
|
||||
await asyncio.to_thread(sanitize_git_config, directory)
|
||||
try:
|
||||
await asyncio.to_thread(sanitize_git_config, directory)
|
||||
except ValueError as e:
|
||||
raise DownloadError(str(e))
|
||||
await git('config', '--replace-all', 'remote.origin.url', prepared.url)
|
||||
refspec = FULL_REFSPEC if prepared.mode == 'full' else f'+refs/heads/{branch}:refs/remotes/origin/{branch}'
|
||||
await git('config', '--replace-all', 'remote.origin.fetch', refspec)
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import shutil
|
|||
import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, NamedTuple, Optional, Tuple
|
||||
|
|
@ -336,7 +337,13 @@ def clone_ownership_error(directory: pathlib.Path, url: str) -> Optional[str]:
|
|||
|
||||
|
||||
def mark_clone(directory: pathlib.Path, url: str):
|
||||
(directory / '.git' / REPO_MARKER).write_text(f'{repo_url_key(url)}\n')
|
||||
marker = directory / '.git' / REPO_MARKER
|
||||
# The clone may hold a link here (e.g. one being imported); never write through it.
|
||||
if marker.is_symlink():
|
||||
marker.unlink()
|
||||
fd = os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644)
|
||||
with os.fdopen(fd, 'w') as fh:
|
||||
fh.write(f'{repo_url_key(url)}\n')
|
||||
|
||||
|
||||
def _git_config_entries(config_file: pathlib.Path) -> List[Tuple[str, str]]:
|
||||
|
|
@ -374,6 +381,8 @@ def _format_git_config(entries: List[Tuple[str, str]]) -> str:
|
|||
|
||||
|
||||
def _sanitize_config_file(config_file: pathlib.Path, worktree_root: Optional[pathlib.Path] = None):
|
||||
if config_file.is_symlink() or not config_file.is_file():
|
||||
raise ValueError(f'{config_file} is not a file')
|
||||
entries = _git_config_entries(config_file)
|
||||
keep = []
|
||||
for key, value in entries:
|
||||
|
|
@ -386,9 +395,15 @@ def _sanitize_config_file(config_file: pathlib.Path, worktree_root: Optional[pat
|
|||
keep.append((key, value))
|
||||
if len(keep) == len(entries):
|
||||
return
|
||||
new = config_file.with_name(f'{config_file.name}.wrolpi')
|
||||
new.write_text(_format_git_config(keep))
|
||||
os.replace(new, config_file)
|
||||
# An unpredictable, newly created file: the directory may hold links (e.g. a clone being imported).
|
||||
fd, new = tempfile.mkstemp(dir=config_file.parent, prefix=f'{config_file.name}.wrolpi-')
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as fh:
|
||||
fh.write(_format_git_config(keep))
|
||||
os.replace(new, config_file)
|
||||
except BaseException:
|
||||
pathlib.Path(new).unlink(missing_ok=True)
|
||||
raise
|
||||
logger.warning(f'Removed {len(entries) - len(keep)} unexpected settings from {config_file}')
|
||||
|
||||
|
||||
|
|
@ -703,6 +718,9 @@ def resolve_import_directory(session: Session, directory: str) -> pathlib.Path:
|
|||
git_dir = path / '.git'
|
||||
if git_dir.is_symlink() or not git_dir.is_dir():
|
||||
raise InvalidRepo(f'{directory} is not a git clone (it has no .git directory)')
|
||||
config = git_dir / 'config'
|
||||
if config.is_symlink() or not config.is_file():
|
||||
raise InvalidRepo(f'{directory} cannot be imported: its .git/config is not a file')
|
||||
return path
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -165,3 +165,42 @@ def test_sanitized_config_round_trips(tmp_path):
|
|||
result = git(repo, 'config', '--file', '.git/config', '--get-all', 'branch.main.merge')
|
||||
assert result.split('\n') == values
|
||||
assert 'proxy' not in (repo / '.git/config').read_text()
|
||||
|
||||
|
||||
def test_marker_and_config_do_not_follow_links(tmp_path):
|
||||
"""A clone (e.g. one being imported) can hold links; WROLPi never writes through them."""
|
||||
repo = tmp_path / 'repo'
|
||||
git_dir = repo / '.git'
|
||||
git_dir.mkdir(parents=True)
|
||||
victim = tmp_path / 'victim.txt'
|
||||
victim.write_text('precious')
|
||||
|
||||
(git_dir / lib.REPO_MARKER).symlink_to(victim)
|
||||
lib.mark_clone(repo, 'https://github.com/a/b')
|
||||
assert victim.read_text() == 'precious'
|
||||
assert not (git_dir / lib.REPO_MARKER).is_symlink()
|
||||
assert (git_dir / lib.REPO_MARKER).read_text().strip() == 'github.com/a/b'
|
||||
|
||||
(git_dir / 'config').write_text('[http]\n\tproxy = evil\n[core]\n\tbare = false\n')
|
||||
(git_dir / 'config.wrolpi').symlink_to(victim)
|
||||
lib.sanitize_git_config(repo)
|
||||
assert victim.read_text() == 'precious'
|
||||
assert 'proxy' not in (git_dir / 'config').read_text()
|
||||
|
||||
# A config which is a link is refused.
|
||||
(git_dir / 'config').unlink()
|
||||
(git_dir / 'config').symlink_to(victim)
|
||||
with pytest.raises(ValueError):
|
||||
lib.sanitize_git_config(repo)
|
||||
assert victim.read_text() == 'precious'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_import_refuses_linked_config(test_session, test_directory, async_client, test_wrolpi_config):
|
||||
from modules.repos.errors import InvalidRepo
|
||||
directory = test_directory / 'code/linked'
|
||||
git(test_directory, 'init', '--quiet', 'code/linked')
|
||||
(directory / '.git/config').unlink()
|
||||
(directory / '.git/config').symlink_to(test_directory / 'elsewhere')
|
||||
with pytest.raises(InvalidRepo, match='config'):
|
||||
lib.inspect_import(test_session, 'code/linked')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue