feat(transfer): add mget and mput batch transfers with safety guards

- Add pages mget with remote glob/--recursive/--dry-run/--resume, traversal rejection, 0700/0600 permissions, and no-clobber
- Add pages mput with local glob/--recursive/--strip-ext/--dry-run and create-only CAS via PUT /_/api/v1/pages/path:...
- Enforce symlink, binary, 1 MiB, duplicate-path, and batch size caps before upload
- Add unit tests and update README.md and docs/client-contract.md
This commit is contained in:
Anya Tokugawa committed 2026-11-30 22:32:53 +09:00
1 parent 13a4416af9
commit a1956dcc6a
4 files changed
+476 -2

No files matched your search

+193
View File
@@ -1131,6 +1131,199 @@ class RemoteTests(unittest.TestCase):
with self.assertRaisesRegex(Failure, 'Incomplete transfer'):
m['execute'](client, profile, ['cat', '/doc.txt', '--stream'])
def test_mget_remote_glob_recursive_dry_run_no_clobber_and_traversal_guard(self):
tree = {
'/docs': {
'entries': [
{'name': 'a.md', 'path': '/docs/a.md', 'kind': 'file'},
{'name': 'b.txt', 'path': '/docs/b.txt', 'kind': 'file'},
{'name': 'sub', 'path': '/docs/sub', 'kind': 'folder'},
],
'truncated': False,
},
'/docs/sub': {
'entries': [
{'name': 'deep.md', 'path': '/docs/sub/deep.md', 'kind': 'file'},
],
'truncated': False,
},
'/evil': {
'entries': [
{'name': '../escape', 'path': '/evil/../escape', 'kind': 'file'},
],
'truncated': False,
},
'/trunc': {
'entries': [
{'name': 'only.md', 'path': '/trunc/only.md', 'kind': 'file'},
],
'truncated': True,
},
}
contents = {
'/docs/a.md': b'alpha',
'/docs/b.txt': b'bravo',
'/docs/sub/deep.md': b'delta',
'/trunc/only.md': b'only',
}
raw_calls = []
def handle(h):
parsed = m['url'].urlsplit(h.path)
if parsed.path == '/_/api/v1/path-picker':
qs = m['url'].parse_qs(parsed.query)
p = qs.get('path', ['/'])[0]
reply(h, 200, tree.get(p, {'entries': [], 'truncated': False}))
return
if parsed.path.startswith('/v/raw/path:'):
rpath = m['url'].unquote(parsed.path[len('/v/raw/path:'):])
raw_calls.append(rpath)
body = contents.get(rpath)
if body is None:
reply(h, 404, {'error': 'not_found'})
return
digest = hashlib.sha256(body).hexdigest()
h.send_response(200)
h.send_header('Content-Type', 'text/plain; charset=utf-8')
h.send_header('Content-Length', str(len(body)))
h.send_header('X-PagesWiki-Revision-UUID', 'rev-' + rpath.rsplit('/', 1)[-1])
h.send_header('X-PagesWiki-Document-SHA256', digest)
h.end_headers()
h.wfile.write(body)
return
reply(h, 404, {'error': 'unknown'})
with server(handle) as base, tempfile.TemporaryDirectory() as root:
client = Client(base)
profile = Profile('mget', root)
profile.data = {'cwd': '/'}
# --dry-run makes zero /v/raw calls and creates no directory.
dry_dir = Path(root) / 'dry-out'
with contextlib.redirect_stdout(io.StringIO()) as out:
m['execute'](client, profile, ['mget', '/docs/*.md', str(dry_dir), '--dry-run'])
self.assertIn('DRY-RUN\t/docs/a.md', out.getvalue())
self.assertNotIn('/docs/b.txt', out.getvalue())
self.assertEqual(raw_calls, [])
self.assertFalse(dry_dir.exists())
# Non-recursive glob downloads matching files only with 0600 permissions.
out_dir = Path(root) / 'out'
with contextlib.redirect_stdout(io.StringIO()) as out:
m['execute'](client, profile, ['mget', '/docs/*.md', str(out_dir)])
self.assertEqual((out_dir / 'a.md').read_bytes(), b'alpha')
self.assertEqual(stat.S_IMODE((out_dir / 'a.md').stat().st_mode), 0o600)
self.assertFalse((out_dir / 'b.txt').exists())
self.assertFalse((out_dir / 'sub').exists())
self.assertIn('1 downloaded, 0 failed', out.getvalue())
# Recursive mget preserves subdirectories and enforces no-clobber on existing files.
(out_dir / 'a.md').write_bytes(b'existing-protected')
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err:
with self.assertRaisesRegex(Failure, '1 failure'):
m['execute'](client, profile, ['mget', '/docs', str(out_dir), '--recursive'])
self.assertEqual((out_dir / 'a.md').read_bytes(), b'existing-protected')
self.assertEqual((out_dir / 'b.txt').read_bytes(), b'bravo')
self.assertEqual((out_dir / 'sub/deep.md').read_bytes(), b'delta')
self.assertEqual(stat.S_IMODE((out_dir / 'sub').stat().st_mode), 0o700)
self.assertIn('no-clobber', err.getvalue())
# Truncated listing emits warning on stderr.
trunc_dir = Path(root) / 'trunc-out'
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err:
m['execute'](client, profile, ['mget', '/trunc', str(trunc_dir)])
self.assertIn('WARNING:', err.getvalue())
self.assertEqual((trunc_dir / 'only.md').read_bytes(), b'only')
# Traversal entry name is rejected before any download.
raw_calls.clear()
evil_dir = Path(root) / 'evil-out'
with self.assertRaisesRegex(Failure, 'Unsafe remote entry'):
m['execute'](client, profile, ['mget', '/evil/*', str(evil_dir)])
self.assertEqual(raw_calls, [])
self.assertFalse((Path(root) / 'escape').exists())
def test_mput_local_glob_create_only_conflict_dry_run_and_guards(self):
with tempfile.TemporaryDirectory() as root:
notes = Path(root) / 'notes'
sub = notes / 'sub'
sub.mkdir(parents=True)
(notes / 'a.md').write_text('# Alpha\n', encoding='utf-8')
(notes / 'readme.txt').write_text('plain text\n', encoding='utf-8')
(sub / 'b.md').write_text('# Sub Beta\n', encoding='utf-8')
client = Client('https://example.test', 'token', 'auto')
profile = Profile('mput', root)
profile.data = {'cwd': '/'}
# --dry-run lists planned creates without network calls.
with patch.object(client, 'create_page') as create_mock, \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
m['execute'](client, profile, ['mput', str(notes / '*.md'), str(notes / '*.txt'), '/docs', '--strip-ext', '--dry-run'])
create_mock.assert_not_called()
self.assertIn('WARNING:', err.getvalue())
self.assertIn('->\t/docs/a\t(markdown, lang=und', out.getvalue())
self.assertIn('->\t/docs/readme\t(raw, lang=und', out.getvalue())
# Local glob upload creates matching pages via create_page (create-only CAS) with und warning.
with patch.object(client, 'create_page', return_value={'revision_uuid': 'rev-1'}) as create_mock, \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
m['execute'](client, profile, ['mput', str(notes / '*.md'), '/docs'])
self.assertIn('WARNING:', err.getvalue())
create_mock.assert_called_once_with('path:/docs/a.md', '# Alpha\n', True, lang='und', filename='a.md')
self.assertIn('1 created, 0 failed', out.getvalue())
# Recursive directory + --strip-ext + explicit --lang ja suppresses warning and maps subdirs.
with patch.object(client, 'create_page', return_value={'revision_uuid': 'rev-2'}) as create_mock, \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
m['execute'](client, profile, ['mput', str(notes), '/wiki', '--recursive', '--strip-ext', '--lang', 'ja'])
self.assertEqual(err.getvalue(), '')
called_addrs = [c.args[0] for c in create_mock.call_args_list]
self.assertEqual(called_addrs, ['path:/wiki/a', 'path:/wiki/readme', 'path:/wiki/sub/b'])
# 412 conflict on one target reports FAIL, continues others, and raises summary Failure.
with patch.object(client, 'create_page', side_effect=[Failure('Exists', 412), {'revision_uuid': 'rev-3'}, {'revision_uuid': 'rev-4'}]) as create_mock, \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
with self.assertRaisesRegex(Failure, '1 failure'):
m['execute'](client, profile, ['mput', str(notes), '/wiki', '--recursive', '--lang', 'ja'])
self.assertEqual(create_mock.call_count, 3)
self.assertIn('FAIL\t', err.getvalue())
self.assertIn('2 created, 1 failed', out.getvalue())
# 405 unsupported server stops immediately on first request.
with patch.object(client, 'create_page', side_effect=Failure('Unavailable', 405)) as create_mock, \
contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure) as caught:
m['execute'](client, profile, ['mput', str(notes), '/wiki', '--recursive', '--lang', 'ja'])
self.assertEqual(caught.exception.status, 405)
self.assertEqual(create_mock.call_count, 1)
# Guards reject duplicate target paths, symlinks, binary files, and >1 MiB files before any HTTP call.
dup_dir = Path(root) / 'dup'
dup_dir.mkdir()
(dup_dir / 'same.md').write_text('a', encoding='utf-8')
(dup_dir / 'same.txt').write_text('b', encoding='utf-8')
with patch.object(client, 'create_page') as create_mock:
with self.assertRaisesRegex(Failure, 'Duplicate target remote Path'):
m['execute'](client, profile, ['mput', str(dup_dir), '/wiki', '--recursive', '--strip-ext', '--lang', 'ja'])
link_file = Path(root) / 'link.md'
link_file.symlink_to(notes / 'a.md')
with self.assertRaisesRegex(Failure, 'symlink'):
m['execute'](client, profile, ['mput', str(link_file), '/wiki', '--lang', 'ja'])
bin_file = Path(root) / 'bin.dat'
bin_file.write_bytes(b'\xff\xfe\x00\x01')
with self.assertRaisesRegex(Failure, 'Binary or non-UTF-8'):
m['execute'](client, profile, ['mput', str(bin_file), '/wiki', '--lang', 'ja'])
big_file = Path(root) / 'big.md'
big_file.write_bytes(b'x' * ((1 << 20) + 1))
with self.assertRaisesRegex(Failure, '1 MiB client limit'):
m['execute'](client, profile, ['mput', str(big_file), '/wiki', '--lang', 'ja'])
create_mock.assert_not_called()
def oidc_integration():
fixture=json.load(sys.stdin)