repos: import moves the clone where it was inspected; inspect never reads its config

* Inspect takes the URL the import will use, so a destination using
  %(repo_host)s/%(repo_owner)s is computed the same way by both (it used
  the origin's, while import used the submitted URL's).  Import requires
  the inspected destination, and refuses to move the clone anywhere else.
* Inspect runs git against a throwaway git directory holding the clone's
  HEAD, refs and (through alternates) objects, so the clone's unsanitized
  config (and anything it includes) is never read.
* A submodule's `.git` file is read as git reads it: only the line
  ending is trimmed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-10-06 19:11:17 -06:00
parent 4b034ae3ee
commit 89dad0570a
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
7 changed files with 159 additions and 23 deletions

View file

@ -2597,9 +2597,10 @@ export function repoArchiveURL(repoId) {
return `${REPOS_API}/${repoId}/archive.zip`;
}
// What importing the git clone in `directory` (relative to the media directory) would do. Changes nothing.
export async function inspectRepoImport(directory, name, tagName) {
const body = {directory, name: name || null, tag_name: tagName || null};
// What importing the git clone in `directory` (relative to the media directory) would do, with the URL the
// import will use. Changes nothing.
export async function inspectRepoImport(directory, name, tagName, url) {
const body = {directory, name: name || null, tag_name: tagName || null, url: url || null};
const response = await apiPost(`${REPOS_API}/import/inspect`, body);
if (response.ok) {
return {inspection: (await response.json())['inspection']};
@ -2607,7 +2608,8 @@ export async function inspectRepoImport(directory, name, tagName) {
return {error: await getErrorMessage(response, 'Cannot import this directory.')};
}
// Import an existing git clone as a Repo. `repo`: {directory, confirm, url?, name?, tag_name?, frequency?, ...}
// Import an existing git clone as a Repo. `repo`: {directory, destination, confirm, url?, name?, tag_name?, ...}
// `destination` is the inspected one; the server refuses to move the clone anywhere else.
export async function importRepo(repo) {
const response = await apiPost(`${REPOS_API}/import`, repo);
if (response.ok) {

View file

@ -750,7 +750,8 @@ export function RepoImportPage() {
const [confirm, setConfirm] = useState(false);
const [submitting, setSubmitting] = useState(false);
// Inspect the directory again whenever it, the name, or the Tag change (they decide where it will be moved).
// Inspect the directory again whenever it, the URL, the name, or the Tag change (they decide where it will be
// moved).
useEffect(() => {
if (!directory) {
setInspection(null);
@ -759,7 +760,8 @@ export function RepoImportPage() {
}
let current = true;
const timer = setTimeout(async () => {
const {inspection: newInspection, error} = await inspectRepoImport(directory, name.trim(), tagName);
const {inspection: newInspection, error} = await inspectRepoImport(directory, name.trim(), tagName,
url.trim());
if (!current) return;
setInspection(newInspection || null);
setInspectError(error || null);
@ -772,7 +774,7 @@ export function RepoImportPage() {
clearTimeout(timer);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [directory, name, tagName]);
}, [directory, name, tagName, url]);
const handleDirectory = (value) => {
setDirectory(value || '');
@ -791,6 +793,8 @@ export function RepoImportPage() {
try {
const repo = await importRepo({
directory,
// Where the inspection said it would go; the server refuses anywhere else.
destination: inspection.destination,
confirm,
url: url.trim(),
name: name.trim() || null,

View file

@ -1,6 +1,6 @@
import React from 'react';
import {Route, Routes} from 'react-router';
import {act, fireEvent, render, screen, within} from '../test-utils';
import {act, fireEvent, render, screen, waitFor, within} from '../test-utils';
import {
RepoEditPage,
RepoImportPage,
@ -317,7 +317,10 @@ describe('RepoImportPage', () => {
fireEvent.click(screen.getByText('Pick directory'));
expect(await screen.findByText('2 commits are not on the remote')).toBeInTheDocument();
expect(inspectRepoImport).toHaveBeenCalledWith('code/kiwix-tools', '', null);
expect(inspectRepoImport).toHaveBeenCalledWith('code/kiwix-tools', '', null, '');
// Inspected again with the URL the import will use.
await waitFor(() => expect(inspectRepoImport).toHaveBeenCalledWith('code/kiwix-tools', '', null,
'https://github.com/kiwix/kiwix-tools'));
expect(screen.getByText('git@github.com:kiwix/kiwix-tools.git')).toBeInTheDocument();
expect(screen.getByText('repos/kiwix-tools')).toBeInTheDocument();
// The URL comes from the origin.
@ -331,7 +334,7 @@ describe('RepoImportPage', () => {
await flush();
expect(importRepo).toHaveBeenCalledWith({
directory: 'code/kiwix-tools', confirm: true, url: 'https://github.com/kiwix/kiwix-tools', name: null,
directory: 'code/kiwix-tools', destination: 'repos/kiwix-tools', confirm: true, url: 'https://github.com/kiwix/kiwix-tools', name: null,
tag_name: null, frequency: 604800, mode: 'full', branch: null, submodules: false,
});
expect(screen.getByText('repo page')).toBeInTheDocument();

View file

@ -53,7 +53,8 @@ async def post_repo(request: Request, body: schema.RepoCreateRequest):
validate=True,
)
async def post_inspect_import(request: Request, body: schema.RepoImportInspectRequest):
info = lib.inspect_import(request.ctx.session, body.directory, body.name or None, body.tag_name or None)
info = lib.inspect_import(request.ctx.session, body.directory, body.name or None, body.tag_name or None,
body.url or None)
return json_response(dict(inspection=info))
@ -79,6 +80,7 @@ async def post_import(request: Request, body: schema.RepoImportRequest):
submodules=body.submodules,
name=body.name or None,
description=body.description or None,
expected_destination=body.destination,
)
repo = Repository.find_by_id(session, repo.id, options=Repository.json_options())
return json_response(dict(repo=repo.__json__()), status=HTTPStatus.CREATED)

View file

@ -1,4 +1,5 @@
import asyncio
import contextlib
import html
import ipaddress
import os
@ -492,8 +493,9 @@ def working_tree_git_error(directory: pathlib.Path) -> Optional[str]:
git_file = here / '.git'
if git_file.is_symlink():
return f'{git_file} is a link'
content = git_file.read_text(errors='replace')[:4096].strip()
if not content.startswith('gitdir: ') or '\n' in content:
# Read as git does: only the line ending is trimmed.
content = git_file.read_text(errors='replace')[:4096].rstrip('\r\n')
if not content.startswith('gitdir: ') or '\n' in content or '\r' in content:
return f'{git_file} is not a submodule\'s link'
target = (here / content[len('gitdir: '):]).resolve()
if modules not in target.parents:
@ -812,6 +814,34 @@ def resolve_import_directory(session: Session, directory: str) -> pathlib.Path:
return path
@contextlib.contextmanager
def _read_only_git_dir(directory: pathlib.Path):
"""A throwaway git directory with the clone's HEAD, refs and objects, but none of its config (which has not been
sanitized, and could include anything). The clone's objects are only read, through alternates."""
git_dir = directory / '.git'
with tempfile.TemporaryDirectory(prefix='wrolpi-inspect-') as temporary:
view = pathlib.Path(temporary)
(view / 'objects/info').mkdir(parents=True)
(view / 'objects/info/alternates').write_text(f'{(git_dir / "objects").resolve()}\n')
config = '[core]\n\trepositoryformatversion = 0\n\tbare = true\n'
entries = _git_config_entries(git_dir / 'config')
object_format = [v for k, v in entries if k.lower() == 'extensions.objectformat']
if object_format and object_format[0] in ('sha1', 'sha256'):
config = f'[core]\n\trepositoryformatversion = 1\n\tbare = true\n[extensions]\n' \
f'\tobjectformat = {object_format[0]}\n'
(view / 'config').write_text(config)
for name in ('HEAD', 'packed-refs', 'shallow'):
source = git_dir / name
if source.is_file() and not source.is_symlink():
shutil.copyfile(source, view / name)
if (git_dir / 'refs').is_dir() and not (git_dir / 'refs').is_symlink():
shutil.copytree(git_dir / 'refs', view / 'refs', symlinks=True,
ignore=lambda d, names: [i for i in names if (pathlib.Path(d) / i).is_symlink()])
else:
(view / 'refs').mkdir()
yield view
def _git_output_sync(directory: pathlib.Path, *args) -> Optional[str]:
result = subprocess.run(git_command(*args), cwd=directory, env=git_env(), capture_output=True)
return result.stdout.decode(errors='replace').strip() if result.returncode == 0 else None
@ -833,8 +863,12 @@ def _read_head_commit(directory: pathlib.Path) -> dict:
return dict(head_sha=sha, head_date=head_date, head_message=message.strip().split('\n')[0] or None)
def inspect_import(session: Session, directory: str, name: str = None, tag_name: str = None) -> dict:
"""What importing the git clone in `directory` as a Repo would do. Changes nothing."""
def inspect_import(session: Session, directory: str, name: str = None, tag_name: str = None,
url_override: str = None) -> dict:
"""What importing the git clone in `directory` as a Repo would do. Changes nothing.
`url` is the URL the import will use (its host and owner can be in the Repo's directory); without it, the URL
comes from the clone's origin."""
path = resolve_import_directory(session, directory)
entries = _git_config_entries(path / '.git/config')
keys = {key.lower() for key, _ in entries}
@ -848,26 +882,35 @@ def inspect_import(session: Session, directory: str, name: str = None, tag_name:
url = remote_https_url(origin) if origin else None
parsed = None
origin_url = None
if url:
try:
parsed = parse_repo_url(url)
url = parsed.url
url = origin_url = parsed.url
except InvalidRepo:
url = None
if given := (url_override or '').strip():
try:
parsed = parse_repo_url(given)
except InvalidRepo:
parsed = None
name = (name or (parsed.name if parsed else path.name)).strip()
destination = format_repo_destination(name, tag_name, parsed.owner if parsed else None,
parsed.host if parsed else None)
head = (path / '.git/HEAD').read_text(errors='replace').strip() if (path / '.git/HEAD').is_file() else ''
branch = head[len('ref: refs/heads/'):] if head.startswith('ref: refs/heads/') else None
local_commits = _git_output_sync(path, 'rev-list', '--count', 'HEAD', '--not', '--remotes')
# git never runs with the clone's own config here: it has not been sanitized yet.
with _read_only_git_dir(path) as view:
local_commits = _git_output_sync(view, 'rev-list', '--count', 'HEAD', '--not', '--remotes')
head_commit = _read_head_commit(view)
return dict(
directory=str(get_relative_to_media_directory(path)),
origin=origin,
url=url,
url=origin_url,
name=name,
branch=branch if branch and is_valid_branch(branch) else None,
**_read_head_commit(path),
**head_commit,
local_commits=int(local_commits) if local_commits and local_commits.isdigit() else None,
shallow=(path / '.git/shallow').is_file(),
destination=str(get_relative_to_media_directory(destination)),
@ -879,11 +922,14 @@ def inspect_import(session: Session, directory: str, name: str = None, tag_name:
async def import_repository(session: Session, directory: str, url: str = None, confirm: bool = False,
tag_name: str = None, frequency: int = DEFAULT_REPO_FREQUENCY, mode: str = 'full',
branch: str = None, submodules: bool = False, name: str = None,
description: str = None) -> Repository:
description: str = None, expected_destination: str = None) -> Repository:
"""Import the git clone in `directory` as a Repo: it is moved into the Repos directory, and from then on is a
mirror of `url` (which must be the clone's origin). Local changes and commits are discarded by its updates."""
mirror of `url` (which must be the clone's origin). Local changes and commits are discarded by its updates.
`destination` is the directory the inspection said the clone would be moved to; the import is refused if it
would be moved anywhere else."""
_validate_frequency(frequency)
info = inspect_import(session, directory, name, tag_name)
info = inspect_import(session, directory, name, tag_name, url)
source = resolve_import_directory(session, directory)
url = (url or info['url'] or '').strip()
if not url:
@ -898,6 +944,11 @@ async def import_repository(session: Session, directory: str, url: str = None, c
repo = _create_repository_records(session, parsed.url, tag_name, mode, branch, info['name'], description, None,
submodules)
destination = repo.directory
relative_destination = str(get_relative_to_media_directory(destination))
if relative_destination != info['destination'] or (
expected_destination is not None and relative_destination != expected_destination):
raise InvalidRepo(f'The repo would be moved to {relative_destination}, not '
f'{expected_destination or info["destination"]}. Inspect it again')
moving = destination.resolve() != source
if moving:
if source in destination.resolve().parents:

View file

@ -36,11 +36,14 @@ class RepoImportInspectRequest:
directory: str
name: Optional[str] = None
tag_name: Optional[str] = None
url: Optional[str] = None
@dataclass
class RepoImportRequest:
directory: str
# The destination the inspection reported; the import is refused if the clone would be moved anywhere else.
destination: str
confirm: bool = False
url: Optional[str] = None
tag_name: Optional[str] = None

View file

@ -128,7 +128,8 @@ async def test_import(test_session, test_directory, async_client, test_wrolpi_co
await refresh_files()
assert test_session.query(FileGroup).filter(FileGroup.primary_path.contains('code/kiwix-tools')).count()
body = dict(directory='code/kiwix-tools', tag_name='Software', confirm=True, frequency=86400)
body = dict(directory='code/kiwix-tools', tag_name='Software', confirm=True, frequency=86400,
destination='repos/Software/kiwix-tools')
request, response = await async_client.post('/api/repos/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.CREATED, response.json
imported = response.json['repo']
@ -237,3 +238,73 @@ async def test_import_moves_back_on_failure(test_session, test_directory, async_
assert (directory / '.git').is_dir()
assert not (test_directory / 'repos/kiwix-tools').exists()
assert test_session.query(Repository).count() == 0
@pytest.mark.asyncio
async def test_import_destination_matches_the_inspection(test_session, test_directory, async_client,
test_wrolpi_config, user_clone, git_remote_factory):
"""With a template using the URL's host and owner, the inspection is made with the URL the import will use, and
the import refuses a destination other than the one inspected."""
from wrolpi.common import get_wrolpi_config
get_wrolpi_config().repos_destination = 'repos/%(repo_host)s/%(repo_owner)s/%(repo_name)s'
directory, _ = user_clone('code/library', remote=git_remote_factory('library'))
git(directory, 'remote', 'remove', 'origin') # The URL must be given.
body = dict(directory='code/library')
request, response = await async_client.post('/api/repos/import/inspect', content=json.dumps(body))
assert response.json['inspection']['destination'] == 'repos/library'
url = 'https://git.example.com/owner/library'
body = dict(directory='code/library', url=url)
request, response = await async_client.post('/api/repos/import/inspect', content=json.dumps(body))
inspected = response.json['inspection']['destination']
assert inspected == 'repos/git.example.com/owner/library'
# An import of what was inspected without the URL is refused.
body = dict(directory='code/library', url=url, confirm=True, destination='repos/library')
request, response = await async_client.post('/api/repos/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.BAD_REQUEST
assert 'Inspect it again' in response.json['error']
assert directory.is_dir()
body = dict(directory='code/library', url=url, confirm=True, destination=inspected)
request, response = await async_client.post('/api/repos/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.CREATED, response.json
assert response.json['repo']['directory'] == inspected
assert (test_directory / inspected / '.git').is_dir()
# The API always checks the destination.
body = dict(directory='code/other', url=url, confirm=True)
request, response = await async_client.post('/api/repos/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.BAD_REQUEST
@pytest.mark.asyncio
async def test_inspect_never_reads_the_clones_config(test_session, test_directory, async_client, test_wrolpi_config,
user_clone):
"""Inspecting runs no git command with the clone's (unsanitized) config: one git refuses to read still inspects."""
directory, remote = user_clone()
with (directory / '.git/config').open('a') as fh:
fh.write('[core]\n\trepositoryformatversion = 1\n[extensions]\n\tnotAnExtension = true\n'
f'[include]\n\tpath = {test_directory}/included.gitconfig\n')
# git itself refuses this repository.
assert subprocess.run(['git', '-c', 'safe.directory=*', 'rev-parse', 'HEAD'], cwd=directory,
capture_output=True).returncode != 0
info = lib.inspect_import(test_session, 'code/kiwix-tools')
assert info['head_sha'] == remote.head
assert info['head_message'] == 'Initial commit'
assert info['local_commits'] == 0
def test_working_tree_git_file_is_read_like_git(tmp_path):
"""git trims only the line ending from a `.git` file, not spaces; so does WROLPi."""
repo = tmp_path / 'repo'
(repo / '.git/modules/library').mkdir(parents=True)
(repo / 'vendor/library').mkdir(parents=True)
# git reads this as "<...>/library " (with the space): not the checked git directory.
(repo / 'vendor/library/.git').write_text('gitdir: ../../.git/modules/library/../../../.. \n')
assert lib.working_tree_git_error(repo)
(repo / 'vendor/library/.git').write_text('gitdir: ../../.git/modules/library\r\n')
assert lib.working_tree_git_error(repo) is None