diff --git a/modules/repos/downloader.py b/modules/repos/downloader.py index 330203ae..8f8fa014 100644 --- a/modules/repos/downloader.py +++ b/modules/repos/downloader.py @@ -12,7 +12,8 @@ from wrolpi.dates import now from wrolpi.downloader import Downloader, Download, DownloadContext, DownloadResult, make_progress_callback from wrolpi.errors import DownloadError from .lib import git_command, git_env, find_readme, get_repo_size, is_valid_branch, read_readme_text, \ - submodule_fetch_config, resolve_repo_addresses, pin_config, HostAddresses + submodule_fetch_config, resolve_repo_addresses, pin_config, HostAddresses, clone_ownership_error, mark_clone, \ + sanitize_git_config from .models import Repository __all__ = ['GitDownloader', 'git_downloader', 'PreparedRepo', 'ExecutedRepo', 'parse_git_progress'] @@ -126,12 +127,20 @@ class GitDownloader(Downloader): args.extend(['--depth', '1', '--single-branch', '--no-tags']) args.extend(['--', prepared.url, str(directory)]) await self._git(download, ctx, directory.parent, *args, progress=True, prepared=prepared) + mark_clone(directory, prepared.url) async def _update(self, download: Download, ctx: DownloadContext, prepared: PreparedRepo, branch: str): directory = prepared.directory git = lambda *args, **kwargs: self._git(download, ctx, directory, *args, prepared=prepared, # noqa: E731 **kwargs) + # Only a clone WROLPi made (or imported) for this Repo is reset and cleaned; its config cannot change what + # 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) + await git('config', 'remote.origin.url', prepared.url) + old_head = await git('rev-parse', '--verify', '--quiet', 'HEAD', check=False) if prepared.mode == 'snapshot': await git('fetch', '--progress', '--depth', '1', '--no-tags', 'origin', branch, progress=True) @@ -258,7 +267,7 @@ class GitDownloader(Downloader): # The remote chooses its default branch's name, and branches are passed to git as arguments. if not is_valid_branch(branch): raise DownloadError(f'Invalid branch name: {branch!r}') - if (directory / '.git').is_dir(): + if (directory / '.git').exists() or (directory / '.git').is_symlink(): await self._update(download, ctx, prepared, branch) else: await self._clone(download, ctx, prepared, branch) diff --git a/modules/repos/lib.py b/modules/repos/lib.py index 76b323f6..bf419156 100644 --- a/modules/repos/lib.py +++ b/modules/repos/lib.py @@ -7,6 +7,7 @@ import re import shutil import socket import stat +import subprocess from dataclasses import dataclass, field from typing import List, NamedTuple, Optional, Tuple from urllib.parse import urlparse @@ -31,13 +32,14 @@ from .models import Repository, REPO_MODES logger = logger.getChild(__name__) -__all__ = ['ParsedRepoURL', 'parse_repo_url', 'repo_url_key', 'git_command', 'git_env', 'create_repository', - 'update_repository', 'delete_repository', 'get_repositories', 'list_repo_tree', 'find_readme', - 'repo_destination_variables', 'repos_destination_root', 'validate_repos_destination', 'is_valid_branch', - 'submodule_url_error', 'HostAddresses', 'resolve_repo_addresses', 'pin_config', 'is_public_address', - 'submodule_fetch_config', 'read_readme_text', 'search_repos', 'count_repos', 'search_repos_by_name', - 'get_repo_log', 'get_repo_root', 'repo_archive_name', 'stream_repo_archive', 'ReposConfig', - 'repos_config', 'get_repos_config', 'save_repos_config', 'import_repos_config', 'DEFAULT_REPO_FREQUENCY'] +__all__ = ['ParsedRepoURL', 'parse_repo_url', 'repo_url_key', 'git_command', 'git_env', 'REPO_MARKER', + 'clone_ownership_error', 'mark_clone', 'sanitize_git_config', 'create_repository', 'update_repository', + 'delete_repository', 'get_repositories', 'list_repo_tree', 'find_readme', 'repo_destination_variables', + 'repos_destination_root', 'validate_repos_destination', 'is_valid_branch', 'submodule_url_error', + 'HostAddresses', 'resolve_repo_addresses', 'pin_config', 'is_public_address', 'submodule_fetch_config', + 'read_readme_text', 'search_repos', 'count_repos', 'search_repos_by_name', 'get_repo_log', + 'get_repo_root', 'repo_archive_name', 'stream_repo_archive', 'ReposConfig', 'repos_config', + 'get_repos_config', 'save_repos_config', 'import_repos_config', 'DEFAULT_REPO_FREQUENCY'] DEFAULT_REPO_FREQUENCY = DownloadFrequency.weekly.value @@ -307,6 +309,81 @@ def git_env() -> dict: return env +# WROLPi marks the clones it makes (and imports) with this file in `.git`; it holds the Repo's `repo_url_key`. +REPO_MARKER = 'wrolpi-repo' + +# The only settings kept in a clone's config: anything else (include.path, url.*.insteadOf, http.proxy, +# core.sshCommand, ...) could change what git runs or where it connects. +ALLOWED_GIT_CONFIG_RE = re.compile( + r'^(core\.(repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode|symlinks)' + r'|extensions\.objectformat|remote\.origin\.(url|fetch)|branch\..+\.(remote|merge)' + r'|submodule\..+\.(url|active))$', re.IGNORECASE) + + +def clone_ownership_error(directory: pathlib.Path, url: str) -> Optional[str]: + """Why the clone in `directory` must not be updated as the Repo with `url`, or None. + + WROLPi resets and cleans its clones, so it only updates the ones it made (or imported) for this Repo.""" + git_dir = directory / '.git' + if git_dir.is_symlink() or not git_dir.is_dir(): + return f'{directory} is not a git directory' + marker = git_dir / REPO_MARKER + if marker.is_symlink() or not marker.is_file() or marker.read_text().strip() != repo_url_key(url): + return f'{directory} was not created by WROLPi. Import it from the Repos page' + return None + + +def mark_clone(directory: pathlib.Path, url: str): + (directory / '.git' / REPO_MARKER).write_text(f'{repo_url_key(url)}\n') + + +def _git_config_entries(config_file: pathlib.Path) -> List[Tuple[str, str]]: + """The entries of a git config file (its includes are not followed).""" + result = subprocess.run(git_command('config', '--file', str(config_file), '--null', '--list'), env=git_env(), + capture_output=True, check=True) + entries = [] + for record in result.stdout.decode(errors='replace').split('\0'): + if record: + key, _, value = record.partition('\n') + entries.append((key, value)) + return entries + + +def _sanitize_config_file(config_file: pathlib.Path, worktree_root: Optional[pathlib.Path] = None): + entries = _git_config_entries(config_file) + keep = [] + for key, value in entries: + if ALLOWED_GIT_CONFIG_RE.match(key): + keep.append((key, value)) + elif worktree_root and key.lower() == 'core.worktree': + # A submodule's work tree, which must be inside the repo. + worktree = (config_file.parent / value).resolve() + if worktree == worktree_root or worktree_root in worktree.parents: + keep.append((key, value)) + if len(keep) == len(entries): + return + new = config_file.with_name(f'{config_file.name}.wrolpi') + new.unlink(missing_ok=True) + new.touch() + for key, value in keep: + subprocess.run(git_command('config', '--file', str(new), '--add', key, value), env=git_env(), + capture_output=True, check=True) + os.replace(new, config_file) + logger.warning(f'Removed {len(entries) - len(keep)} unexpected settings from {config_file}') + + +def sanitize_git_config(directory: pathlib.Path): + """Keep only the settings WROLPi needs in the configs of the repo in `directory` (and its submodules).""" + git_dir = directory / '.git' + root = directory.resolve() + _sanitize_config_file(git_dir / 'config') + modules = git_dir / 'modules' + if modules.is_dir() and not modules.is_symlink(): + for config_file in modules.rglob('config'): + if config_file.is_file() and not config_file.is_symlink() and (config_file.parent / 'HEAD').exists(): + _sanitize_config_file(config_file, worktree_root=root) + + def find_readme(directory: pathlib.Path) -> Optional[str]: """Return the name of the preferred README file in `directory`, if any.""" try: diff --git a/modules/repos/test/test_ownership.py b/modules/repos/test/test_ownership.py new file mode 100644 index 00000000..82ea3e5b --- /dev/null +++ b/modules/repos/test/test_ownership.py @@ -0,0 +1,130 @@ +import subprocess + +import pytest + +from modules.repos import lib +from wrolpi.downloader import Download, DownloadStatus + + +def git(directory, *args) -> str: + return subprocess.run(['git', '-c', 'safe.directory=*', *args], cwd=directory, check=True, + capture_output=True).stdout.decode().strip() + + +async def update(test_session, repos_download_manager): + download = test_session.query(Download).one() + download.renew() + test_session.commit() + await repos_download_manager.wait_for_all_downloads() + test_session.expire_all() + return test_session.query(Download).one() + + +@pytest.mark.asyncio +async def test_clone_is_marked(test_session, git_remote_factory, repos_download_manager): + """WROLPi marks the clones it makes, so it never mistakes another clone for one of its own.""" + remote = git_remote_factory() + repo = lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + assert (repo.directory / '.git' / lib.REPO_MARKER).read_text().strip() == lib.repo_url_key(remote.url) + + +@pytest.mark.asyncio +async def test_update_refuses_unmarked_clone(test_session, test_directory, git_remote_factory, + repos_download_manager): + """A clone WROLPi did not make (or made for another repo) is not updated, so it is never reset or cleaned.""" + remote = git_remote_factory() + directory = test_directory / 'repos/example' + directory.parent.mkdir(parents=True) + git(directory.parent, 'clone', '--quiet', str(remote.path), str(directory)) + (directory / 'my-work.txt').write_text('uncommitted') + + lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + + download = test_session.query(Download).one() + assert download.status == DownloadStatus.deferred + assert 'was not created by WROLPi' in download.error + assert (directory / 'my-work.txt').read_text() == 'uncommitted' + + # A marker for another repo is not this repo's. + (directory / '.git' / lib.REPO_MARKER).write_text('git.example.com/owner/other') + download = await update(test_session, repos_download_manager) + assert 'was not created by WROLPi' in download.error + assert (directory / 'my-work.txt').exists() + + +@pytest.mark.asyncio +async def test_update_refuses_git_file(test_session, test_directory, git_remote_factory, repos_download_manager): + """`.git` must be the repo's own directory, not a file or link which points elsewhere.""" + remote = git_remote_factory() + directory = test_directory / 'repos/example' + directory.mkdir(parents=True) + (directory / '.git').write_text('gitdir: /somewhere/else\n') + + lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + download = test_session.query(Download).one() + assert download.status == DownloadStatus.deferred + assert 'not a git directory' in download.error + + +@pytest.mark.asyncio +async def test_update_fetches_the_repo_url(test_session, git_remote_factory, repos_download_manager): + """The Repo's URL is fetched, whatever the clone's origin says.""" + remote = git_remote_factory() + other = git_remote_factory('other') + repo = lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + + git(repo.directory, 'config', 'remote.origin.url', other.url) + head = remote.commit({'new.txt': 'new'}, 'New') + await update(test_session, repos_download_manager) + assert repo.head_sha == head + assert git(repo.directory, 'config', 'remote.origin.url') == remote.url + + +@pytest.mark.asyncio +async def test_update_sanitizes_git_config(test_session, git_remote_factory, repos_download_manager): + """Only the settings WROLPi needs survive in a clone's config; a planted setting cannot change what git does.""" + remote = git_remote_factory() + repo = lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + + config = repo.directory / '.git/config' + config.write_text(config.read_text() + ( + '[url "https://127.0.0.1/"]\n\tinsteadOf = https://git.example.com/\n' + '[http]\n\tproxy = http://127.0.0.1:9\n' + '[include]\n\tpath = /etc/evil.gitconfig\n' + '[core]\n\tsshCommand = evil\n\tworktree = /etc\n\tfsmonitor = evil\n' + )) + head = remote.commit({'new.txt': 'new'}, 'New') + download = await update(test_session, repos_download_manager) + assert download.status == DownloadStatus.complete, download.error + assert repo.head_sha == head + + keys = set(git(repo.directory, 'config', '--local', '--name-only', '--list').splitlines()) + assert {'remote.origin.url', 'remote.origin.fetch', 'core.repositoryformatversion'} <= keys + assert not {'url.https://127.0.0.1/.insteadof', 'http.proxy', 'include.path', 'core.sshcommand', + 'core.worktree', 'core.fsmonitor'} & keys + + +def test_sanitize_git_config_submodules(tmp_path): + """A submodule's config may point its work tree inside the repo, and nowhere else.""" + repo = tmp_path / 'repo' + git_dir = repo / '.git' + module = git_dir / 'modules/library' + module.mkdir(parents=True) + (repo / 'vendor/library').mkdir(parents=True) + (git_dir / 'config').write_text('[core]\n\trepositoryformatversion = 0\n\tbare = false\n') + (module / 'config').write_text('[core]\n\trepositoryformatversion = 0\n\tworktree = ../../../vendor/library\n' + '[remote "origin"]\n\turl = https://git.example.com/owner/library\n') + evil = git_dir / 'modules/evil' + evil.mkdir() + (evil / 'config').write_text('[core]\n\tworktree = /etc\n') + for gitdir in (module, evil): + (gitdir / 'HEAD').write_text('ref: refs/heads/main\n') + + lib.sanitize_git_config(repo) + assert 'worktree = ../../../vendor/library' in (module / 'config').read_text() + assert 'worktree' not in (evil / 'config').read_text()