mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-02 04:46:18 -05:00
repos: validate branch names and repo directories
Branch names are passed to git as arguments and come from the API, the config, a `/tree/<branch>` URL, or the remote itself (its default branch). A name starting with `-` would be read as an option, so every branch must pass git's ref-name rules, including in the downloader just before use. A repo URL with a `.` or `..` path segment (or a `..` name) could format a directory outside its template (e.g. `repos/<tag>/..` is the whole repos directory). Such URLs and names are rejected, and every repo directory, including one from repos.yaml, must be strictly inside the media directory with no `..`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b3255e715c
commit
f49288b8ec
4 changed files with 145 additions and 7 deletions
|
|
@ -27,7 +27,7 @@ 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', 'ReposConfig', 'repos_config', 'get_repos_config', 'save_repos_config',
|
||||
'repo_destination_variables', 'is_valid_branch', 'ReposConfig', 'repos_config', 'get_repos_config', 'save_repos_config',
|
||||
'import_repos_config', 'DEFAULT_REPO_FREQUENCY']
|
||||
|
||||
DEFAULT_REPO_FREQUENCY = DownloadFrequency.weekly.value
|
||||
|
|
@ -75,6 +75,9 @@ def parse_repo_url(url: str) -> ParsedRepoURL:
|
|||
parts = [i for i in path.split('/') if i]
|
||||
if not parts:
|
||||
raise InvalidRepo('Repo URL must have a path')
|
||||
if any(i in ('.', '..') for i in parts):
|
||||
# The name and owner are used in the Repo's directory.
|
||||
raise InvalidRepo('Repo URL must not contain "." or ".." in its path')
|
||||
name = parts[-1].removesuffix('.git')
|
||||
if not name:
|
||||
raise InvalidRepo('Repo URL must have a name')
|
||||
|
|
@ -85,6 +88,33 @@ def parse_repo_url(url: str) -> ParsedRepoURL:
|
|||
return ParsedRepoURL(url=f'{parsed.scheme}://{netloc}{path}', host=host, owner=owner, name=name, branch=branch)
|
||||
|
||||
|
||||
# Characters git forbids in a ref name (`git check-ref-format`), plus whitespace.
|
||||
INVALID_BRANCH_CHARACTERS_RE = re.compile(r'[\x00-\x20\x7f~^:?*\[\\]')
|
||||
|
||||
|
||||
def is_valid_branch(branch: str) -> bool:
|
||||
"""Is `branch` a valid git branch name (the rules of `git check-ref-format --branch`)?
|
||||
|
||||
Branch names are passed to git as arguments, so a name starting with `-` (an option) is never valid."""
|
||||
if not branch or not isinstance(branch, str):
|
||||
return False
|
||||
if branch.startswith('-') or branch == '@' or '@{' in branch or '..' in branch:
|
||||
return False
|
||||
if INVALID_BRANCH_CHARACTERS_RE.search(branch):
|
||||
return False
|
||||
if branch.startswith('/') or branch.endswith('/') or '//' in branch or branch.endswith('.'):
|
||||
return False
|
||||
for component in branch.split('/'):
|
||||
if component.startswith('.') or component.endswith('.lock'):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _validate_branch(branch: Optional[str]):
|
||||
if branch is not None and not is_valid_branch(branch):
|
||||
raise ValidationError(f'Invalid branch name: {branch!r}')
|
||||
|
||||
|
||||
def repo_url_key(url: str) -> str:
|
||||
"""Two URLs of the same repo have the same key (`.git` suffix and case of the host are ignored)."""
|
||||
parsed = urlparse(url.strip())
|
||||
|
|
@ -164,6 +194,20 @@ def _validate_mode(mode: str):
|
|||
raise ValidationError(f'Repo mode must be one of {", ".join(REPO_MODES)}')
|
||||
|
||||
|
||||
def _validate_directory(directory: pathlib.Path):
|
||||
"""A Repo's directory is strictly inside the media directory; it is cloned into, and may be deleted."""
|
||||
media_directory = get_media_directory()
|
||||
directory = pathlib.Path(directory)
|
||||
if '..' in directory.parts or not directory.is_absolute():
|
||||
raise InvalidRepo(f'Invalid repo directory: {directory}')
|
||||
try:
|
||||
relative = directory.relative_to(media_directory)
|
||||
except ValueError:
|
||||
raise InvalidRepo('Repo directory must be in the media directory')
|
||||
if not relative.parts:
|
||||
raise InvalidRepo('Repo directory can not be the media directory')
|
||||
|
||||
|
||||
def _validate_frequency(frequency: int):
|
||||
if not isinstance(frequency, int) or frequency <= 0:
|
||||
raise ValidationError('Repo frequency must be a positive number of seconds')
|
||||
|
|
@ -177,7 +221,10 @@ def create_repository(session: Session, url: str, tag_name: str = None, frequenc
|
|||
_validate_mode(mode)
|
||||
_validate_frequency(frequency)
|
||||
branch = branch or parsed.branch or None
|
||||
_validate_branch(branch)
|
||||
name = (name or parsed.name).strip()
|
||||
if name in ('', '.', '..'):
|
||||
raise InvalidRepo(f'Invalid repo name: {name!r}')
|
||||
|
||||
if get_repository_by_url(session, parsed.url):
|
||||
raise RepoConflict(f'A repo with this URL already exists: {parsed.url}')
|
||||
|
|
@ -195,8 +242,7 @@ def create_repository(session: Session, url: str, tag_name: str = None, frequenc
|
|||
session.flush([repo])
|
||||
|
||||
directory = directory or collection.format_destination(tag_name)
|
||||
if not str(directory.resolve()).startswith(str(get_media_directory().resolve()) + '/'):
|
||||
raise InvalidRepo('Repo directory must be in the media directory')
|
||||
_validate_directory(directory)
|
||||
if session.query(Collection).filter(Collection.directory == directory, Collection.id != collection.id).first():
|
||||
raise RepoConflict(f'Another collection already uses the directory {get_relative_to_media_directory(directory)}')
|
||||
collection.directory = directory
|
||||
|
|
@ -221,7 +267,9 @@ def update_repository(session: Session, repo_id: int, description: str = None, f
|
|||
_validate_mode(mode)
|
||||
repo.mode = mode
|
||||
if branch is not None:
|
||||
repo.branch = branch.strip() or None
|
||||
branch = branch.strip() or None
|
||||
_validate_branch(branch)
|
||||
repo.branch = branch
|
||||
if frequency is not None:
|
||||
_validate_frequency(frequency)
|
||||
if download := repo.download:
|
||||
|
|
@ -415,6 +463,8 @@ class ReposConfig(ConfigFile):
|
|||
_validate_frequency(frequency)
|
||||
directory = data.get('directory')
|
||||
directory = get_media_directory() / directory if directory else None
|
||||
if directory:
|
||||
_validate_directory(directory)
|
||||
tag_name = data.get('tag_name')
|
||||
|
||||
repo = get_repository_by_url(session, parsed.url)
|
||||
|
|
@ -430,7 +480,9 @@ class ReposConfig(ConfigFile):
|
|||
if directory:
|
||||
collection.directory = directory
|
||||
repo.mode = mode
|
||||
repo.branch = data.get('branch') or None
|
||||
branch = data.get('branch') or None
|
||||
_validate_branch(branch)
|
||||
repo.branch = branch
|
||||
if download := repo.download:
|
||||
download.frequency = frequency
|
||||
else:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue