From a1956dcc6a5522ef75cacf2c243686923e5e43b9 Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Mon, 30 Nov 2026 22:32:53 +0900 Subject: [PATCH] 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 --- README.md | 2 + docs/client-contract.md | 4 +- pages | 279 +++++++++++++++++++++++++++++++++++++++- test_pages.py | 193 +++++++++++++++++++++++++++ 4 files changed, 476 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 63f424c..fc4badd 100644 --- a/README.md +++ b/README.md @@ -152,8 +152,10 @@ OSの言語からは推測しません。最初に名前付きプロファイル | `ls` / `cd` / `pwd` | Semantic Pathをたどる。仮想フォルダにも移動可能 | | `cat` / `view` | 正本の出力(`--stream` で逐次出力+終端SHA-256検証)/`$PAGER`で閲覧 | | `get ADDRESS LOCAL` | 正本をファイルへ安全保存(`--resume` / `--max-bytes` / `--timeout`、既存ファイルは上書きしない) | +| `mget REMOTE LOCAL_DIR` | リモートPath/glob(`-r` / `--dry-run` / `--resume`)で一括ダウンロード。既存ファイルは上書きしない | | `edit ADDRESS` | `$EDITOR`で編集。未存在Pathは確認後に新規作成。Wikiはauthoring Markdown、他のテキストは原文 | | `put LOCAL ADDRESS --base REVISION_UUID` | 明示した基点RevisionとのCASで更新 | +| `mput LOCAL... REMOTE_PREFIX` | ローカルファイル/globから新規Pageを一括作成(`-r` / `--strip-ext` / `--dry-run`、既存Pathは412で停止) | | `recover [PATH]` | 退避された原稿の一覧表示・再開・破棄(`--list` / `--edit` / `--discard`) | | `search QUERY` | 権限付きの検索候補 | | `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 | diff --git a/docs/client-contract.md b/docs/client-contract.md index 93eb747..3631d99 100644 --- a/docs/client-contract.md +++ b/docs/client-contract.md @@ -72,4 +72,6 @@ Viewer面(`/...`)や非正規Projection面(`/v/raw/...`)と分離され メール取り込みは1通2 MiB、本文は明示指定時のみ、保持するメモは16 KiBまで。再送用要求は最大20件。連絡先importは1枚のUTF-8 vCard、64 KiBまで。NeoMutt検索は本人・Domain内の個人アドレス帳を対象とし、最大100件を返す。 -CLIの単体・実バイナリ試験は合成データのみを使用する。サーバー側の権限・CAS・OIDC署名検証とGoのHTTP結合テストはPagesWikiリポジトリで管理する。新規Page作成には `PUT /_/api/v1/pages/path:...` に対応したサーバーが必要。Windowsの資格情報保護とロック移植、バイナリ大容量アップロードAPI、一括転送(`mget`/`mput`)は後続タスク。 +一括転送(`mget` / `mput`)はローカルとリモートのglob対象を明示分離し、1回あたり最大500ファイル・200フォルダを上限とする。`mget` は末尾セグメントのglob(または `--recursive`)でリモートを走査し、`..` や制御文字、シンボリックリンク、宛先ディレクトリ外への出力を拒否し、0700ディレクトリ・0600ファイル・no-clobberで保存する。`mput` はシンボリックリンク・バイナリ・1 MiB超過・重複宛先を送信前に拒否し、各ファイルを `PUT /_/api/v1/pages/path:...`(`If-None-Match: *`)で新規作成のみ行い、既存Pageを無断上書きしない(`--dry-run` で事前確認可)。 + +CLIの単体・実バイナリ試験は合成データのみを使用する。サーバー側の権限・CAS・OIDC署名検証とGoのHTTP結合テストはPagesWikiリポジトリで管理する。新規Page作成および `mput` には `PUT /_/api/v1/pages/path:...` に対応したサーバーが必要。Windowsの資格情報保護とロック移植、バイナリ大容量アップロードAPIは後続タスク。 diff --git a/pages b/pages index ad573e0..199a9e9 100755 --- a/pages +++ b/pages @@ -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') diff --git a/test_pages.py b/test_pages.py index 89c15a1..2dcc60d 100644 --- a/test_pages.py +++ b/test_pages.py @@ -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)