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

+278 -1
View File
@@ -11,7 +11,9 @@ import contextlib
import difflib
import errno
import fcntl
import fnmatch
import getpass
import glob
import hashlib
from html.parser import HTMLParser
import json
@@ -78,6 +80,8 @@ CHUNK_SIZE = 65536
DEFAULT_TIMEOUT = 20
DEFAULT_DEADLINE = 300
DEFAULT_DOWNLOAD_LIMIT = 64 << 20
MAX_BATCH_FILES = 500
MAX_BATCH_FOLDERS = 200
def _iter_stream(stream, expected_length, deadline, clock):
@@ -1374,6 +1378,256 @@ def contacts(client, words):
print(json.dumps(data,ensure_ascii=False,indent=2))
def _safe_rel_dest(local_root, rel_parts):
if local_root.is_symlink():
raise Failure('Destination directory must not be a symlink.')
if not rel_parts:
raise Failure('Invalid empty destination path.')
for part in rel_parts:
if (not part or part in ('.', '..') or '/' in part or '\\' in part
or any(unicodedata.category(c).startswith('C') for c in part)):
raise Failure('Unsafe remote entry name rejected: ' + safe_text(part))
cur = local_root
for part in rel_parts:
cur = cur / part
if cur.is_symlink():
raise Failure('Refusing to follow symlink in destination path: ' + safe_text(cur))
root_resolved = local_root.resolve(strict=False)
dest_resolved = cur.resolve(strict=False)
try:
dest_resolved.relative_to(root_resolved)
except ValueError:
raise Failure('Destination path escapes target directory.') from None
return cur
def _collect_remote_files(client, remote_spec, cwd, *, recursive=False):
if remote_spec.startswith(('uuid:', 'rev:')):
raise Failure('mget requires a remote Path or remote glob pattern, not uuid:/rev:.')
raw_path = remote_spec.removeprefix('path:')
full = semantic(raw_path, cwd)
cached_probe = None
if any(ch in full for ch in '*?['):
parent = posixpath.dirname(full)
pattern = posixpath.basename(full)
if any(ch in parent for ch in '*?['):
raise Failure('Wildcards are supported only in the final Path segment; use --recursive for subtrees.')
elif recursive:
parent = full
pattern = '*'
else:
cached_probe = client.listing(full)
if cached_probe.get('entries'):
parent = full
pattern = '*'
else:
if full == '/':
return []
parent = posixpath.dirname(full)
pattern = posixpath.basename(full)
cached_probe = None
queue = [(parent, ())]
visited = {parent}
files = []
truncated_any = False
while queue:
cur_dir, rel_prefix = queue.pop(0)
listing = cached_probe if (cached_probe is not None and cur_dir == parent) else client.listing(cur_dir)
cached_probe = None
if listing.get('truncated'):
truncated_any = True
for entry in listing.get('entries', []):
name = entry.get('name', '')
epath = entry.get('path', '')
if (not isinstance(name, str) or not name or name in ('.', '..')
or '/' in name or '\\' in name
or any(unicodedata.category(c).startswith('C') for c in name)
or not isinstance(epath, str) or not epath.startswith('/')
or any(unicodedata.category(c).startswith('C') for c in epath)):
raise Failure('Unsafe remote entry metadata rejected.')
if entry.get('kind') == 'folder':
if recursive and epath not in visited:
if len(visited) >= MAX_BATCH_FOLDERS:
raise Failure('Batch folder limit (%d) exceeded; narrow the Path.' % MAX_BATCH_FOLDERS)
visited.add(epath)
queue.append((epath, rel_prefix + (name,)))
elif fnmatch.fnmatchcase(name, pattern):
if len(files) >= MAX_BATCH_FILES:
raise Failure('Batch file limit (%d) exceeded; narrow the Path pattern.' % MAX_BATCH_FILES)
files.append(('path:' + epath, rel_prefix + (name,)))
if truncated_any:
print('WARNING: One or more remote folder listings were truncated by the server; narrow the Path pattern for complete results.', file=sys.stderr)
return files
def mget(client, cwd, remote_spec, local_dir, *, recursive=False, resume=False, limit=DEFAULT_DOWNLOAD_LIMIT, deadline_seconds=DEFAULT_DEADLINE, dry_run=False):
if limit <= 0 or deadline_seconds <= 0:
raise Failure('Download limit and timeout must be positive.')
root = Path(local_dir)
if root.is_symlink():
raise Failure('Destination directory must not be a symlink.')
if root.exists() and not root.is_dir():
raise Failure('Destination exists and is not a directory.')
files = _collect_remote_files(client, remote_spec, cwd, recursive=recursive)
if not files:
raise Failure('No remote pages matched pattern.')
planned = []
seen_dests = set()
for raddr, rel_parts in files:
dest = _safe_rel_dest(root, rel_parts)
if dest in seen_dests:
raise Failure('Duplicate local destination path: ' + safe_text(dest))
seen_dests.add(dest)
planned.append((raddr, dest))
if dry_run:
for raddr, dest in planned:
print('DRY-RUN\t' + safe_text(raddr[5:]) + '\t->\t' + safe_text(dest))
print(f'Matched: {len(planned)} file(s).')
return
root.mkdir(mode=0o700, parents=True, exist_ok=True)
ok = 0
failed = 0
for raddr, dest in planned:
dest.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
try:
headers, size = client.download(raddr, str(dest), limit=limit, deadline_seconds=deadline_seconds, resume=resume)
rev = headers.get('X-PagesWiki-Revision-UUID', 'unknown')
print('OK\t' + safe_text(raddr[5:]) + '\t->\t' + safe_text(dest) + f'\t({size} bytes, rev: {safe_text(rev)})')
ok += 1
except FileExistsError:
print('FAIL\t' + safe_text(raddr[5:]) + '\t->\t' + safe_text(dest) + '\tFile exists (no-clobber)', file=sys.stderr)
failed += 1
except (Failure, OSError) as e:
print('FAIL\t' + safe_text(raddr[5:]) + '\t->\t' + safe_text(dest) + '\t' + safe_text(str(e)), file=sys.stderr)
failed += 1
print(f'Summary: {ok} downloaded, {failed} failed.')
if failed:
raise Failure(f'mget completed with {failed} failure(s).')
def _walk_local_dir(base_dir, root_dir):
for entry in sorted(base_dir.iterdir()):
if entry.is_symlink():
raise Failure('Refusing to upload symlink: ' + safe_text(entry))
if entry.is_dir():
yield from _walk_local_dir(entry, root_dir)
elif entry.is_file():
yield entry, entry.relative_to(root_dir).parts
def _collect_local_files(specs, remote_prefix, cwd, *, recursive=False, strip_ext=False):
prefix_addr = address(remote_prefix, cwd)
if not prefix_addr.startswith('path:'):
raise Failure('mput destination must be a remote Path prefix.')
base_remote = prefix_addr[5:]
collected = []
for spec in specs:
if any(ch in spec for ch in '*?['):
raw_matches = sorted(Path(p) for p in glob.glob(spec, recursive=recursive))
parts = Path(spec).parts
prefix_parts = []
for part in parts:
if any(ch in part for ch in '*?['):
break
prefix_parts.append(part)
glob_base = Path(*prefix_parts) if prefix_parts else Path('.')
for match in raw_matches:
if match.is_symlink():
raise Failure('Refusing to upload symlink: ' + safe_text(match))
if match.is_dir():
if recursive:
for fpath, rel in _walk_local_dir(match, glob_base):
collected.append((fpath, rel))
elif match.is_file():
try:
rel = match.relative_to(glob_base).parts
except ValueError:
rel = (match.name,)
collected.append((match, rel if rel else (match.name,)))
else:
p = Path(spec)
if p.is_symlink():
raise Failure('Refusing to upload symlink: ' + safe_text(spec))
if not p.exists():
raise Failure('Local file not found: ' + safe_text(spec))
if p.is_dir():
if not recursive:
raise Failure('Directory requires --recursive: ' + safe_text(spec))
for fpath, rel in _walk_local_dir(p, p):
collected.append((fpath, rel))
elif p.is_file():
collected.append((p, (p.name,)))
else:
raise Failure('Unsupported local file type: ' + safe_text(spec))
if len(collected) > MAX_BATCH_FILES:
raise Failure('Batch file limit (%d) exceeded; narrow the local selection.' % MAX_BATCH_FILES)
result = []
seen_remote = set()
for src_path, rel_parts in collected:
parts = list(rel_parts)
if strip_ext and parts:
last = parts[-1]
if not last.startswith('.') and Path(last).suffix and Path(last).stem:
parts[-1] = Path(last).stem
if not parts or any((not seg or seg in ('.', '..') or '\\' in seg or any(unicodedata.category(c).startswith('C') for c in seg)) for seg in parts):
raise Failure('Unsafe local relative path: ' + safe_text(src_path))
rpath = semantic('/'.join(parts), base_remote)
if rpath == '/':
raise Failure('Cannot upload to root Path /.')
if rpath in seen_remote:
raise Failure('Duplicate target remote Path: ' + safe_text(rpath))
seen_remote.add(rpath)
size = src_path.stat().st_size
if size > 1 << 20:
raise Failure('Text edit exceeds the 1 MiB client limit: ' + safe_text(src_path))
try:
src_path.read_text(encoding='utf-8')
except UnicodeDecodeError:
raise Failure('Binary or non-UTF-8 file is not supported by mput: ' + safe_text(src_path)) from None
result.append((src_path, 'path:' + rpath, size))
return result
def mput(client, cwd, local_specs, remote_prefix, *, fmt='auto', lang=None, recursive=False, strip_ext=False, dry_run=False):
items = _collect_local_files(local_specs, remote_prefix, cwd, recursive=recursive, strip_ext=strip_ext)
if not items:
raise Failure('No local files matched.')
chosen = language(lang) if lang else client.lang
if chosen == 'auto':
target_lang = 'und'
print("WARNING: Creating pages with language 'und' (profile language is 'auto'). Use --lang TAG to specify an explicit language.", file=sys.stderr)
else:
target_lang = chosen
if dry_run:
for src, raddr, size in items:
markdown = (fmt == 'markdown') or (fmt == 'auto' and src.suffix.lower() in ('.md', '.markdown'))
kind = 'markdown' if markdown else 'raw'
print('DRY-RUN\t' + safe_text(src) + '\t->\t' + safe_text(raddr[5:]) + f'\t({kind}, lang={safe_text(target_lang)}, {size} bytes)')
print(f'Matched: {len(items)} file(s).')
return
ok = 0
failed = 0
for src, raddr, _ in items:
markdown = (fmt == 'markdown') or (fmt == 'auto' and src.suffix.lower() in ('.md', '.markdown'))
text = src.read_text(encoding='utf-8')
if not text:
print('FAIL\t' + safe_text(src) + '\t->\t' + safe_text(raddr[5:]) + '\tEmpty file skipped', file=sys.stderr)
failed += 1
continue
try:
result = client.create_page(raddr, text, markdown, lang=target_lang, filename=src.name)
print('OK\t' + safe_text(src) + '\t->\t' + safe_text(raddr[5:]) + '\t(rev: ' + safe_text(result['revision_uuid']) + ')')
ok += 1
except Failure as e:
if e.status in (404, 405, 501):
raise
print('FAIL\t' + safe_text(src) + '\t->\t' + safe_text(raddr[5:]) + '\t' + safe_text(str(e)), file=sys.stderr)
failed += 1
print(f'Summary: {ok} created, {failed} failed.')
if failed:
raise Failure(f'mput completed with {failed} failure(s).')
def execute(client, profile, words):
if words and words[0] in ('contact','contacts'):
return contacts(client,words[1:])
@@ -1397,6 +1651,21 @@ def execute(client, profile, words):
p.add_argument('--timeout', type=int, default=DEFAULT_DEADLINE, help='Total transfer deadline in seconds (default: 300)')
p = sub.add_parser('put'); p.add_argument('local'); p.add_argument('path'); p.add_argument('--base', required=True)
p.add_argument('--format', choices=['raw', 'markdown'], default='raw')
p = sub.add_parser('mget', help='Batch download pages matching a remote Path/glob into a local directory')
p.add_argument('remote', help='Remote Path or glob pattern (quote wildcards in your shell)')
p.add_argument('local_dir', help='Local destination directory')
p.add_argument('-r', '--recursive', action='store_true', help='Recurse into remote folders')
p.add_argument('--resume', action='store_true', help='Retain/resume partial downloads via HTTP Range/If-Range')
p.add_argument('--max-bytes', type=int, default=DEFAULT_DOWNLOAD_LIMIT, help='Maximum download size per file in bytes')
p.add_argument('--timeout', type=int, default=DEFAULT_DEADLINE, help='Total transfer deadline per file in seconds')
p.add_argument('--dry-run', action='store_true', help='List matched files without downloading')
p = sub.add_parser('mput', help='Batch create new Pages from local files/globs under a remote Path prefix (create-only CAS)')
p.add_argument('paths', nargs='+', help='One or more local files/globs followed by the remote destination Path prefix')
p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto', help='auto treats .md/.markdown as Markdown authoring and other UTF-8 files as raw')
p.add_argument('--lang', help='Target language tag (auto creates as und with warning)')
p.add_argument('-r', '--recursive', action='store_true', help='Recurse into local directories / ** globs')
p.add_argument('--strip-ext', action='store_true', help='Strip file extensions from destination Page names')
p.add_argument('--dry-run', action='store_true', help='List matched files without uploading')
p = sub.add_parser('recover', help='List, resume, or discard retained local edit drafts')
p.add_argument('target', nargs='?', help='Recovery directory, recovery.json, or retained document file')
p.add_argument('--list', action='store_true', dest='list_only', help='List retained local drafts')
@@ -1407,6 +1676,14 @@ def execute(client, profile, words):
args = parser.parse_args(words)
cwd = profile.data.get('cwd', '/')
cmd = args.command
if cmd == 'mget':
mget(client, cwd, args.remote, args.local_dir, recursive=args.recursive, resume=args.resume,
limit=args.max_bytes, deadline_seconds=args.timeout, dry_run=args.dry_run); return
if cmd == 'mput':
if len(args.paths) < 2:
parser.error('mput requires at least one local source and a remote Path prefix.')
mput(client, cwd, args.paths[:-1], args.paths[-1], fmt=args.format, lang=args.lang,
recursive=args.recursive, strip_ext=args.strip_ext, dry_run=args.dry_run); return
if cmd == 'recover':
recover(client, profile, args.target, edit_first=args.edit_first, discard=args.discard, list_only=args.list_only); return
if cmd == 'logout':
@@ -1529,7 +1806,7 @@ def shell(client, profile):
def main(argv=None):
parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, edit, recover, search, open, task, contacts. Use pages COMMAND --help.')
parser = argparse.ArgumentParser(prog='pages', description=__doc__, epilog='Commands: configure, login, logout, status, shell, ls, cd, pwd, cat, view, get, put, mget, mput, edit, recover, search, open, task, contacts. Use pages COMMAND --help.')
parser.add_argument('--version', action='version', version='pages-cli ' + VERSION)
parser.add_argument('--profile', help='Use another configured connection for this invocation')
parser.add_argument('--lang', help='auto or an exact language tag for this invocation')