From 0676535b24218b32b687bcd6f088adffa9e69493 Mon Sep 17 00:00:00 2001 From: Roland Date: Tue, 6 Oct 2026 17:45:05 -0600 Subject: [PATCH] repos: ignore the repos destination's own directory, and validate it The constant `repos` was always ignored, but the Repos Directory setting accepted any relative template (`library/%(repo_name)s`, `%(repo_name)s`), whose checkouts (and .git) would be indexed. The fixed directory at the start of the destination is now the ignored one (on config import and when the setting is saved). A destination must start with a fixed directory, contain %(repo_name)s, use only the repo variables, and not overlap another special directory; a hand-edited config that breaks these rules falls back to the default. Co-Authored-By: Claude Opus 5.5 --- app/src/components/admin/Settings.js | 3 +- modules/repos/lib.py | 68 ++++++++++++++++++++++++--- modules/repos/test/test_lib.py | 70 ++++++++++++++++++++++++++++ wrolpi/common.py | 12 +++-- wrolpi/root_api.py | 13 ++++-- 5 files changed, 152 insertions(+), 14 deletions(-) diff --git a/app/src/components/admin/Settings.js b/app/src/components/admin/Settings.js index c5b71cb6..b5dc15fe 100644 --- a/app/src/components/admin/Settings.js +++ b/app/src/components/admin/Settings.js @@ -864,7 +864,8 @@ export function SettingsPage() {
  • %(repo_owner)s - Owner from the repo URL
  • %(repo_host)s - Host from the repo URL
  • -

    Files in the repos directory are never indexed.

    +

    Must start with a fixed directory (like repos/), which + is never indexed, and contain %(repo_name)s.

    } position='top' /> diff --git a/modules/repos/lib.py b/modules/repos/lib.py index ac6a5a88..76b323f6 100644 --- a/modules/repos/lib.py +++ b/modules/repos/lib.py @@ -18,7 +18,7 @@ from wrolpi import fts from wrolpi.cmd import GIT_BIN, run_command from wrolpi.collections.models import Collection from wrolpi.common import ConfigFile, get_media_directory, get_relative_to_media_directory, logger, \ - escape_file_name, background_task + escape_file_name, background_task, get_wrolpi_config from wrolpi.db import get_db_session from wrolpi.downloader import DownloadFrequency, save_downloads_config from wrolpi.errors import UnknownDirectory, ValidationError @@ -33,11 +33,11 @@ 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', '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'] + '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 @@ -383,6 +383,62 @@ def read_readme_text(path: pathlib.Path) -> Optional[str]: return text.strip() or None +# The variables a `repos_destination` may use (see Collection.format_destination). +REPOS_DESTINATION_VARIABLES = ('repo_name', 'repo_tag', 'repo_owner', 'repo_host', 'tag_name', 'name', 'tag') + + +def repos_destination_root(destination: str) -> str: + """The fixed directory at the start of a `repos_destination` (before any variable). It is never indexed.""" + parts = [] + for part in (destination or '').split('/'): + if '%(' in part: + break + parts.append(part) + return '/'.join(i for i in parts if i) + + +def validate_repos_destination(destination: str, config=None) -> str: + """An error message for an invalid `repos_destination`, or an empty string. + + Every repo must live under the destination's fixed directory, which is ignored (repo files are never indexed), + and that directory must not hold any other kind of WROLPi content.""" + config = config or get_wrolpi_config() + if not destination: + return 'Repos directory cannot be empty' + if destination.startswith('/'): + return 'Repos directory must be relative to the media directory' + if any(i in ('..', '.') for i in destination.split('/')): + return 'Repos directory cannot contain ".." or "."' + try: + destination % {i: 'x' for i in REPOS_DESTINATION_VARIABLES} + except (KeyError, ValueError, TypeError): + return f'Unknown variable in Repos directory, use: {", ".join(REPOS_DESTINATION_VARIABLES)}' + if '%(repo_name)s' not in destination and '%(name)s' not in destination: + return 'Repos directory must contain the repo name: %(repo_name)s' + root = repos_destination_root(destination) + if not root: + return 'Repos directory must start with a fixed directory, like repos/' + + others = { + 'videos_destination': config.videos_destination, + 'archive_destination': config.archive_destination, + 'map_destination': config.map_destination, + 'zims_destination': config.zims_destination, + 'playlists_destination': config.playlists_destination, + 'tags directory': 'tags', + 'config directory': 'config', + } + root_parts = tuple(root.split('/')) + for name, other in others.items(): + other_parts = tuple(repos_destination_root(other).split('/')) if other else () + if not other_parts or other_parts == ('',): + continue + overlap = min(len(root_parts), len(other_parts)) + if root_parts[:overlap] == other_parts[:overlap]: + return f'Repos directory cannot overlap the {name} ({other!r})' + return '' + + def repo_destination_variables(collection: Collection) -> dict: """Variables for `repos_destination` which are stored on the Repository (not the Collection).""" session = Session.object_session(collection) diff --git a/modules/repos/test/test_lib.py b/modules/repos/test/test_lib.py index b74053d0..eaf00ac3 100644 --- a/modules/repos/test/test_lib.py +++ b/modules/repos/test/test_lib.py @@ -1,4 +1,6 @@ +import json import os +from http import HTTPStatus import pytest from mock import mock @@ -10,6 +12,7 @@ from wrolpi.collections.models import Collection from wrolpi.common import get_wrolpi_config from wrolpi.downloader import Download, DownloadFrequency from wrolpi.errors import UnknownDirectory, ValidationError +from wrolpi.files.lib import get_normalized_ignored_directories from wrolpi.files.models import FileGroup @@ -307,3 +310,70 @@ def test_git_command_ignores_hostile_environment(tmp_path): capture_output=True) assert result.returncode != 0 assert b"transport 'file' not allowed" in result.stderr + + +@pytest.mark.parametrize('destination,error', [ + ('repos/%(repo_tag)s/%(repo_name)s', None), + ('library/code/%(repo_owner)s/%(repo_name)s', None), + ('repos/%(tag)s/%(name)s', None), + ('%(repo_name)s', 'fixed directory'), # Would put repos in the media directory itself. + ('%(repo_tag)s/%(repo_name)s', 'fixed directory'), + ('repos', 'repo name'), # Every repo in one directory. + ('repos/%(repo_tag)s', 'repo name'), + ('repos/%(bogus)s/%(repo_name)s', 'Unknown variable'), + ('repos/%(repo_name)d', 'Unknown variable'), + ('/repos/%(repo_name)s', 'relative'), + ('../repos/%(repo_name)s', '".."'), + ('repos/./%(repo_name)s', '".."'), + ('videos/%(repo_name)s', 'videos_destination'), + ('archive/x/%(repo_name)s', 'archive_destination'), + ('playlists/%(repo_name)s', 'playlists_destination'), + ('tags/%(repo_name)s', 'tags directory'), + ('config/%(repo_name)s', 'config directory'), + ('', 'empty'), +]) +@pytest.mark.asyncio +async def test_validate_repos_destination(async_client, test_wrolpi_config, destination, error): + result = lib.validate_repos_destination(destination) + if error is None: + assert result == '' + else: + assert error in result, result + + +def test_repos_destination_root(): + assert lib.repos_destination_root('repos/%(repo_tag)s/%(repo_name)s') == 'repos' + assert lib.repos_destination_root('library/code/%(repo_name)s') == 'library/code' + assert lib.repos_destination_root('%(repo_name)s') == '' + + +@pytest.mark.asyncio +async def test_repos_destination_is_ignored(test_session, test_directory, async_client, test_wrolpi_config, + refresh_files): + """Wherever repos are saved, their files are not indexed.""" + body = dict(repos_destination='%(repo_name)s') + request, response = await async_client.patch('/api/settings', content=json.dumps(body)) + assert response.status_code == HTTPStatus.BAD_REQUEST + + body = dict(repos_destination='library/code/%(repo_tag)s/%(repo_name)s') + request, response = await async_client.patch('/api/settings', content=json.dumps(body)) + assert response.status_code == HTTPStatus.NO_CONTENT + assert str(test_directory / 'library/code') in get_normalized_ignored_directories() + + repo = lib.create_repository(test_session, 'https://github.com/a/b') + assert repo.directory == test_directory / 'library/code/b' + repo.directory.mkdir(parents=True) + (repo.directory / 'README.md').write_text('# B') + (test_directory / 'other.txt').write_text('other') + await refresh_files() + assert [i.primary_path.name for i in test_session.query(FileGroup)] == ['other.txt'] + + # A hand-edited config which breaks the rules falls back to the default. + config = get_wrolpi_config() + config.save(overwrite=True) + data = config.read_config_file() + data['repos_destination'] = '%(repo_name)s' + data['version'] = (data.get('version') or 0) + 1 + config.write_config_data(data, config.get_file()) + config.import_config() + assert config.repos_destination == 'repos/%(repo_tag)s/%(repo_name)s' diff --git a/wrolpi/common.py b/wrolpi/common.py index c9307dab..ee2f3b8f 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -1396,10 +1396,16 @@ class WROLPiConfig(ConfigFile): if self._config['playlists_destination'] not in ignored: ignored.append(self._config['playlists_destination']) self._config['ignored_directories'] = ignored - # Git repositories are browsed through the Repos module; their files are never indexed. + # Git repositories are browsed through the Repos module; their files are never indexed. Every repo is + # under the fixed directory at the start of the repos destination. + from modules.repos.lib import validate_repos_destination, repos_destination_root + if error := validate_repos_destination(self._config['repos_destination'], self): + logger.warning(f'Using the default repos destination: {error}') + self._config['repos_destination'] = self.default_config['repos_destination'] + repos_root = repos_destination_root(self._config['repos_destination']) ignored = list(self._config.get('ignored_directories') or []) - if REPOS_DIRECTORY not in ignored: - ignored.append(REPOS_DIRECTORY) + if repos_root not in ignored: + ignored.append(repos_root) self._config['ignored_directories'] = ignored self.successful_import = True diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index e90ed24f..791cc9a2 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -282,12 +282,11 @@ async def update_settings(_: Request, body: schema.SettingsRequest): # The Settings page may not send `repos_destination`; only validate it when it is provided. if body.repos_destination is not None: + from modules.repos.lib import validate_repos_destination if not body.repos_destination: new_config['repos_destination'] = wrolpi_config.default_config['repos_destination'] - elif pathlib.Path(body.repos_destination).is_absolute(): - raise InvalidConfig('Repos directory must be relative to media directory') - elif '..' in pathlib.Path(body.repos_destination).parts: - raise InvalidConfig('Repos directory must not contain ".."') + elif error := validate_repos_destination(body.repos_destination): + raise InvalidConfig(error) # Validate timezone if provided; empty string clears it. if body.timezone is not None: @@ -325,6 +324,12 @@ async def update_settings(_: Request, body: schema.SettingsRequest): # Save config settings (hotspot control is now through Controller endpoints) wrolpi_config.update(new_config) + if body.repos_destination is not None: + # Repo files are never indexed, wherever repos are saved. + from modules.repos.lib import repos_destination_root + from wrolpi.files.lib import add_ignore_directory + add_ignore_directory(repos_destination_root(wrolpi_config.repos_destination)) + # If the Zim directory changed, restart Kiwix so it serves the new directory # without waiting for a reboot. Local import avoids a circular import # (modules depend on wrolpi, not the reverse).