4 Commits
Author SHA1 Message Date
Anya Tokugawa 6d2bbe57ff release: bump version to 0.7.0
Test and release pages-cli / linux (push) Successful in 5s
Test and release pages-cli / macos (push) Skipped
2026-11-30 22:43:14 +09:00
Anya Tokugawa 44be7c6382 feat(shell): add quote/cursor-aware completion, Ctrl+P fuzzy picker, and opt-in history
Test and release pages-cli / linux (push) Successful in 48s
Test and release pages-cli / macos (push) Skipped
- Add quote-aware, mid-cursor, and command/subcommand-aware Tab completion in shell
- Add Ctrl+P keybinding and pick command for interactive fuzzy search via search/suggest and path-picker
- Add explicit opt-in persistent shell history (pages shell --history) stored in 0700/0600 files with secret-line filtering
- Add unit tests and update README.md and docs/client-contract.md
2026-11-30 22:36:45 +09:00
Anya Tokugawa a1956dcc6a 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
2026-11-30 22:32:53 +09:00
Anya Tokugawa 13a4416af9 feat(transfer): add streaming cat, resumable Range downloads, and transfer deadlines
- Add O(1)-memory chunked Client.stream_request with total transfer deadline and premature-EOF detection
- Add pages cat --stream with incremental stdout output and end-of-stream SHA-256 verification
- Add pages get --resume with private 0600 staging, Range/If-Range/Content-Range checks, full re-hash before atomic no-clobber commit, and --max-bytes/--timeout
- Pre-check 1 MiB limit in pages put and update docs and unit tests
2026-11-30 22:27:52 +09:00
6 changed files with 1657 additions and 69 deletions

No files matched your search

+2 -2
View File
@@ -18,8 +18,8 @@ rpm/debは初期配布の必須条件にせず、LinuxはELFを提供する。Py
```sh ```sh
# ダウンロード先で実行。手元にあるファイルをチェックする。 # ダウンロード先で実行。手元にあるファイルをチェックする。
sha256sum --ignore-missing -c pages-cli-v0.6.0-linux-amd64-SHA256SUMS sha256sum --ignore-missing -c pages-cli-v0.7.0-linux-amd64-SHA256SUMS
tar -xzf pages-cli-v0.6.0-linux-amd64.tar.gz tar -xzf pages-cli-v0.7.0-linux-amd64.tar.gz
mkdir -p ~/.local/bin mkdir -p ~/.local/bin
install -m 755 pages ~/.local/bin/pages install -m 755 pages ~/.local/bin/pages
pages --version pages --version
+7 -4
View File
@@ -150,17 +150,20 @@ OSの言語からは推測しません。最初に名前付きプロファイル
| コマンド | 用途 | | コマンド | 用途 |
| --- | --- | | --- | --- |
| `ls` / `cd` / `pwd` | Semantic Pathをたどる。仮想フォルダにも移動可能 | | `ls` / `cd` / `pwd` | Semantic Pathをたどる。仮想フォルダにも移動可能 |
| `cat` / `view` | 正本の出力/`$PAGER`で閲覧 | | `cat` / `view` | 正本の出力(`--stream` で逐次出力+終端SHA-256検証)/`$PAGER`で閲覧 |
| `get ADDRESS LOCAL` | 正本をダウンロード。既存のローカルファイルは上書きしない | | `get ADDRESS LOCAL` | 正本をファイルへ安全保存(`--resume` / `--max-bytes` / `--timeout`、既存ファイルは上書きしない) |
| `mget REMOTE LOCAL_DIR` | リモートPath/glob(`-r` / `--dry-run` / `--resume`)で一括ダウンロード。既存ファイルは上書きしない |
| `edit ADDRESS` | `$EDITOR`で編集。未存在Pathは確認後に新規作成。Wikiはauthoring Markdown、他のテキストは原文 | | `edit ADDRESS` | `$EDITOR`で編集。未存在Pathは確認後に新規作成。Wikiはauthoring Markdown、他のテキストは原文 |
| `put LOCAL ADDRESS --base REVISION_UUID` | 明示した基点RevisionとのCASで更新 | | `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`) | | `recover [PATH]` | 退避された原稿の一覧表示・再開・破棄(`--list` / `--edit` / `--discard`) |
| `search QUERY` | 権限付きの検索候補 | | `search QUERY` | 権限付きの検索候補 |
| `pick [QUERY]`(シェル内 `Ctrl+P`) | 対話シェルでのファジー検索選択・入力補完・操作 |
| `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 | | `open ADDRESS` | ブラウザで閲覧。ブラウザ側ログインを使用 |
| `status` / `logout` | 接続状態表示/セッション失効 | | `status` / `logout` | 接続状態表示/セッション失効 |
`pages --help`、`pages configure --help`、`pages edit --help` で引数を確認できます。 `pages --help`、`pages configure --help`、`pages edit --help`、`pages shell --help` で引数を確認できます。
Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位置の補完、Ctrl+Pのfuzzy UIは後続です。 コマンド名・サブコマンド・引用文字・途中カーソル位置に対応したTab補完、`Ctrl+P`(または `pick`)によるファジー検索選択、上下キーの履歴に対応しています。履歴は既定でプロセス内のみ保持し、`pages shell --history` を明示指定した場合だけ秘密情報を除外して `0600` ファイルへ保存します。
### 言語を指定して編集する ### 言語を指定して編集する
+1 -1
View File
@@ -1 +1 @@
0.6.0 0.7.0
+8 -2
View File
@@ -18,6 +18,8 @@ OIDC入口はサーバーv0.3.0以降。OIDCで認証した利用者への追加
設定のorigin・usernameと保存セッションの対応を検査する。ログイン中の接続先変更はlogoutを先に行う。logoutはサーバーの失効に失敗した場合、成功と報告せず資格情報を残す。パスワード・TOTP・Bearerを引数、URL、履歴、設定表示へ含めない。セッションファイルは平文なので、同じOSユーザーやrootからは保護できない。OS keyringは未対応。 設定のorigin・usernameと保存セッションの対応を検査する。ログイン中の接続先変更はlogoutを先に行う。logoutはサーバーの失効に失敗した場合、成功と報告せず資格情報を残す。パスワード・TOTP・Bearerを引数、URL、履歴、設定表示へ含めない。セッションファイルは平文なので、同じOSユーザーやrootからは保護できない。OS keyringは未対応。
対話シェルの履歴は既定でプロセス内のみに保持する。`pages shell --history` を明示指定した場合のみ、`history/PROFILE.history`(ディレクトリ `0700`、ファイル `0600`、シンボリックリンク拒否)へ保存し、`login` や `Bearer`/`password`/`pw_api_` 等を含む行は保存・読込時に除外する。`Ctrl+P`/`pick` のファジー検索もサーバー側の `GET /_/api/v1/search/suggest` と `GET /_/api/v1/path-picker` を使い、サーバー側認可の範囲のみ候補表示する。
## アドレスと編集 ## アドレスと編集
Pathは到達経路、UUIDはPageの識別子、Revisionは履歴。正本は `/v/raw/path:/...`、`uuid:`、`rev:` で取得する。Wiki正本はHTMLで、編集用Markdownはauthoring射影。children等の展開結果を保存せず、HTMLの保護フェンスを既存変換APIで往復する。 Pathは到達経路、UUIDはPageの識別子、Revisionは履歴。正本は `/v/raw/path:/...`、`uuid:`、`rev:` で取得する。Wiki正本はHTMLで、編集用Markdownはauthoring射影。children等の展開結果を保存せず、HTMLの保護フェンスを既存変換APIで往復する。
@@ -66,8 +68,12 @@ Viewer面(`/...`)や非正規Projection面(`/v/raw/...`)と分離され
## 上限と検証 ## 上限と検証
ネットワークには20秒のsocket timeoutと応答サイズ上限がある。総転送時間の厳密なdeadlineや巨大転送のstreamingは未対応。`get` は最大64 MiB、SHA-256を照合し、新規0600ファイルへ出力する。既存ファイルは上書きしない。編集テキストは1 MiB、JSON送信は2 MiBまで。 ネットワークには20秒のsocket timeoutに加え、総転送時間の上限(既定300秒、`--timeout` で指定可)とサイズ上限がある。`cat` は既定で全体のSHA-256を検証してから出力し、パイプ等へ逐次出力したい場合は `cat --stream` で64 KiB単位のO(1)ストリーミング出力を行い、ストリーム終端で全体SHA-256および `Content-Length` との途中切断を検証する(不一致時は信頼不可の警告を出して非ゼロ終了する)。
ファイルダウンロード(`get`)では到着チャンクを未確定ピースとして扱い、保存先ディレクトリ内の非公開一時ファイル(`0600`)へ書き込む。通常時は失敗・通信断・`Ctrl+C` で一時ファイルを即削除し、全SHA-256検証・`fsync` 後に既存ファイルを上書きせず原子的に配置する。`get --resume` 指定時は中断時に `.FILE.pages-part` と `.FILE.pages-part.json`(Bearer非含有、`0600`)を保持し、再開時に `Range` + `If-Range`(`ETag`)+ `Content-Range` + `X-PagesWiki-Document-SHA256` を照合(更新されていれば先頭から再取得)し、全ピース揃った段階で先頭から全体を再ハッシュした上で原子配置する(破損・改ざん検知時はステージングを削除して停止)。クライアント層はチャンク単位のストリーミング送信(`Client.stream_request`)にも対応し、`put` は送信前にローカルファイルの1 MiB上限を検査する。編集テキストは1 MiB、JSON送信は2 MiBまで。
メール取り込みは1通2 MiB、本文は明示指定時のみ、保持するメモは16 KiBまで。再送用要求は最大20件。連絡先importは1枚のUTF-8 vCard、64 KiBまで。NeoMutt検索は本人・Domain内の個人アドレス帳を対象とし、最大100件を返す。 メール取り込みは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の資格情報保護とロック移植、巨大ファイル転送は後続タスク。 一括転送(`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は後続タスク。
+1017 -51
View File
File diff suppressed because it is too large. Load diff
+622 -9
View File
@@ -301,15 +301,29 @@ class RemoteTests(unittest.TestCase):
with self.assertRaises(Failure): client.save(state,'new') with self.assertRaises(Failure): client.save(state,'new')
def test_download_private_and_no_clobber(self): def test_download_private_and_no_clobber(self):
headers=Message(); headers['X-PagesWiki-Revision-UUID']='rev' payload = b'data'
with tempfile.TemporaryDirectory() as root: digest = hashlib.sha256(payload).hexdigest()
profile=Profile('test',root) def handle(h):
client=Client('https://example.test') h.send_response(200)
file=str(Path(root)/'download') h.send_header('Content-Type', 'application/octet-stream')
with patch.object(client,'raw',return_value=(b'data',headers)), contextlib.redirect_stdout(io.StringIO()): h.send_header('Content-Length', str(len(payload)))
m['execute'](client,profile,['get','/path',file]) h.send_header('X-PagesWiki-Revision-UUID', 'rev')
self.assertEqual(stat.S_IMODE(Path(file).stat().st_mode),0o600) h.send_header('X-PagesWiki-Document-SHA256', digest)
with self.assertRaises(FileExistsError): m['execute'](client,profile,['get','/path',file]) h.end_headers()
h.wfile.write(payload)
with server(handle) as base, tempfile.TemporaryDirectory() as root:
profile = Profile('test', root)
client = Client(base)
file = str(Path(root) / 'download')
with contextlib.redirect_stdout(io.StringIO()):
m['execute'](client, profile, ['get', '/path', file])
self.assertEqual(Path(file).read_bytes(), payload)
self.assertEqual(stat.S_IMODE(Path(file).stat().st_mode), 0o600)
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
with self.assertRaises(FileExistsError):
m['execute'](client, profile, ['get', '/path', file])
self.assertEqual(Path(file).read_bytes(), payload)
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
def test_auto_snapshot_pins_visible_language_and_head(self): def test_auto_snapshot_pins_visible_language_and_head(self):
client=Client('https://example.test','token') client=Client('https://example.test','token')
@@ -823,6 +837,605 @@ class RemoteTests(unittest.TestCase):
self.assertIn('Discarded recovery draft', out.getvalue()) self.assertIn('Discarded recovery draft', out.getvalue())
self.assertFalse(discard_dir.exists()) self.assertFalse(discard_dir.exists())
def test_streaming_download_chunks_integrity_limits_cancel_and_deadline(self):
large = (b'0123456789abcdef' * 12800) # 204,800 bytes (> 3 * CHUNK_SIZE)
large_digest = hashlib.sha256(large).hexdigest()
mode = {'data': large, 'digest': large_digest, 'send_cl': True}
def handle(h):
h.send_response(200)
h.send_header('Content-Type', 'application/octet-stream')
if mode['send_cl']:
h.send_header('Content-Length', str(len(mode['data'])))
h.send_header('X-PagesWiki-Revision-UUID', 'rev-large')
h.send_header('X-PagesWiki-Document-SHA256', mode['digest'])
h.end_headers()
try:
for idx in range(0, len(mode['data']), 16384):
h.wfile.write(mode['data'][idx:idx + 16384])
except (BrokenPipeError, ConnectionResetError):
pass
with server(handle) as base, tempfile.TemporaryDirectory() as root:
client = Client(base)
profile = Profile('stream', root)
dest = Path(root) / 'large.bin'
with contextlib.redirect_stdout(io.StringIO()):
m['execute'](client, profile, ['get', '/large.bin', str(dest)])
self.assertEqual(dest.read_bytes(), large)
self.assertEqual(stat.S_IMODE(dest.stat().st_mode), 0o600)
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
# SHA-256 mismatch leaves neither destination nor temp file.
mode['digest'] = '0' * 64
bad_dest = Path(root) / 'bad.bin'
with self.assertRaisesRegex(Failure, 'SHA-256 mismatch'):
client.download('path:/bad.bin', str(bad_dest))
self.assertFalse(bad_dest.exists())
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
mode['digest'] = large_digest
# Limit rejected early via Content-Length and mid-stream without Content-Length.
mode['data'] = b'x' * 200
mode['digest'] = hashlib.sha256(mode['data']).hexdigest()
for send_cl in (True, False):
mode['send_cl'] = send_cl
over_dest = Path(root) / f'over-{send_cl}.bin'
with self.assertRaisesRegex(Failure, 'exceeds client limit'):
client.download('path:/over', str(over_dest), limit=100)
self.assertFalse(over_dest.exists())
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
with self.assertRaisesRegex(Failure, 'exceeds client limit'):
m['execute'](client, profile, ['get', '/over', str(Path(root) / 'cli-over.bin'), '--max-bytes', '100'])
self.assertFalse((Path(root) / 'cli-over.bin').exists())
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
# Cancellation (Ctrl+C / KeyboardInterrupt) cleans up temp file cleanly.
mode['data'] = large; mode['digest'] = large_digest; mode['send_cl'] = True
cancel_dest = Path(root) / 'cancel.bin'
with patch.object(m['os'], 'fsync', side_effect=KeyboardInterrupt()):
with self.assertRaises(KeyboardInterrupt):
client.download('path:/cancel', str(cancel_dest))
self.assertFalse(cancel_dest.exists())
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
# Total transfer deadline cleans up temp file cleanly.
ticks = iter([0.0, 0.0, 10.0])
deadline_dest = Path(root) / 'slow.bin'
with self.assertRaisesRegex(Failure, 'total time deadline'):
client.download('path:/slow', str(deadline_dest), deadline_seconds=5, clock=lambda: next(ticks, 10.0))
self.assertFalse(deadline_dest.exists())
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
def test_streaming_upload_chunks_deadline_and_put_precheck(self):
received = []
def handle(h):
try:
length = int(h.headers.get('Content-Length', 0))
data = h.rfile.read(length)
received.append((h.command, length, data))
reply(h, 200, {'status': 'ok'})
except (BrokenPipeError, ConnectionResetError):
pass
payload = b'stream-chunk-' * 12000 # 156,000 bytes
with server(handle) as base:
client = Client(base, 'token')
raw, _ = client.stream_request(
'/upload', method='PUT', data=io.BytesIO(payload),
content_length=len(payload), content_type='application/octet-stream',
max_request_bytes=1 << 20)
self.assertEqual(json.loads(raw), {'status': 'ok'})
self.assertEqual(received[0][0], 'PUT')
self.assertEqual(received[0][1], len(payload))
self.assertEqual(received[0][2], payload)
ticks = iter([0.0, 0.0, 10.0])
with self.assertRaisesRegex(Failure, 'total time deadline'):
client.stream_request(
'/upload', method='PUT', data=io.BytesIO(payload),
content_length=len(payload), content_type='application/octet-stream',
max_request_bytes=1 << 20, deadline_seconds=5, clock=lambda: next(ticks, 10.0))
with tempfile.TemporaryDirectory() as root:
profile = Profile('test', root)
profile.data = {'cwd': '/'}
too_big = Path(root) / 'big.txt'
too_big.write_bytes(b'a' * ((1 << 20) + 1))
client = Client('https://example.test', 'token')
with patch.object(client, 'snapshot') as snap_mock, patch.object(client, 'save') as save_mock:
with self.assertRaisesRegex(Failure, '1 MiB client limit'):
m['execute'](client, profile, ['put', str(too_big), '/page', '--base', 'rev-1'])
snap_mock.assert_not_called()
save_mock.assert_not_called()
def test_resumable_file_download_pieces_range_and_full_rehash(self):
data_v1 = (b'piece-v1-' * 20000) # 180,000 bytes
sha_v1 = hashlib.sha256(data_v1).hexdigest()
etag_v1 = '"' + sha_v1 + '"'
data_v2 = (b'piece-v2-' * 22000) # 198,000 bytes
sha_v2 = hashlib.sha256(data_v2).hexdigest()
etag_v2 = '"' + sha_v2 + '"'
state = {'body': data_v1, 'sha': sha_v1, 'etag': etag_v1, 'rev': 'rev-1', 'interrupt_after': None}
requests = []
def handle(h):
requests.append((h.command, h.path, h.headers.get('Range'), h.headers.get('If-Range')))
body = state['body']
rng = h.headers.get('Range')
if_rng = h.headers.get('If-Range')
if rng and rng.startswith('bytes=') and (if_rng is None or if_rng == state['etag']):
start = int(rng.split('=', 1)[1].split('-', 1)[0])
part = body[start:]
h.send_response(206)
h.send_header('Content-Type', 'application/octet-stream')
h.send_header('Content-Length', str(len(part)))
h.send_header('Content-Range', f'bytes {start}-{len(body) - 1}/{len(body)}')
h.send_header('ETag', state['etag'])
h.send_header('X-PagesWiki-Revision-UUID', state['rev'])
h.send_header('X-PagesWiki-Document-SHA256', state['sha'])
h.end_headers()
h.wfile.write(part)
return
h.send_response(200)
h.send_header('Content-Type', 'application/octet-stream')
h.send_header('Content-Length', str(len(body)))
h.send_header('ETag', state['etag'])
h.send_header('X-PagesWiki-Revision-UUID', state['rev'])
h.send_header('X-PagesWiki-Document-SHA256', state['sha'])
h.end_headers()
try:
limit_bytes = state['interrupt_after']
to_send = body[:limit_bytes] if limit_bytes is not None else body
for idx in range(0, len(to_send), 16384):
h.wfile.write(to_send[idx:idx + 16384])
except (BrokenPipeError, ConnectionResetError):
pass
with server(handle) as base, tempfile.TemporaryDirectory() as root:
client = Client(base)
profile = Profile('resume', root)
dest = Path(root) / 'file.bin'
part_file = Path(root) / '.file.bin.pages-part'
meta_file = Path(root) / '.file.bin.pages-part.json'
# Test A: interrupt mid-download, keep private 0600 pieces, then resume via Range/If-Range.
state['interrupt_after'] = 65536
with contextlib.redirect_stderr(io.StringIO()) as err:
with self.assertRaisesRegex(Failure, 'Incomplete transfer'):
m['execute'](client, profile, ['get', '/file.bin', str(dest), '--resume'])
self.assertFalse(dest.exists())
self.assertTrue(part_file.exists() and meta_file.exists())
self.assertEqual(stat.S_IMODE(part_file.stat().st_mode), 0o600)
self.assertEqual(stat.S_IMODE(meta_file.stat().st_mode), 0o600)
self.assertEqual(part_file.stat().st_size, 65536)
self.assertIn('Partial download retained', err.getvalue())
meta = json.loads(meta_file.read_text(encoding='utf-8'))
self.assertEqual(meta['expected_sha256'], sha_v1)
self.assertEqual(meta['total_bytes'], len(data_v1))
state['interrupt_after'] = None
requests.clear()
with contextlib.redirect_stdout(io.StringIO()):
m['execute'](client, profile, ['get', '/file.bin', str(dest), '--resume'])
self.assertEqual(requests[0][2], 'bytes=65536-')
self.assertEqual(requests[0][3], etag_v1)
self.assertEqual(dest.read_bytes(), data_v1)
self.assertEqual(stat.S_IMODE(dest.stat().st_mode), 0o600)
self.assertFalse(part_file.exists())
self.assertFalse(meta_file.exists())
# Test B: mid-file corruption in .pages-part is caught by full re-hash before commit.
dest_b = Path(root) / 'corrupt.bin'
part_b = Path(root) / '.corrupt.bin.pages-part'
meta_b = Path(root) / '.corrupt.bin.pages-part.json'
state['interrupt_after'] = 65536
with contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(Failure):
client.download('path:/corrupt.bin', str(dest_b), resume=True)
raw_part = bytearray(part_b.read_bytes())
raw_part[0] ^= 0xFF
part_b.write_bytes(bytes(raw_part))
state['interrupt_after'] = None
with self.assertRaisesRegex(Failure, 'SHA-256 mismatch'):
client.download('path:/corrupt.bin', str(dest_b), resume=True)
self.assertFalse(dest_b.exists())
self.assertFalse(part_b.exists())
self.assertFalse(meta_b.exists())
# Test C: If-Range mismatch when remote page changed restarts cleanly from offset 0.
dest_c = Path(root) / 'updated.bin'
part_c = Path(root) / '.updated.bin.pages-part'
meta_c = Path(root) / '.updated.bin.pages-part.json'
state['interrupt_after'] = 65536
with contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(Failure):
client.download('path:/updated.bin', str(dest_c), resume=True)
state.update({'body': data_v2, 'sha': sha_v2, 'etag': etag_v2, 'rev': 'rev-2', 'interrupt_after': None})
requests.clear()
client.download('path:/updated.bin', str(dest_c), resume=True)
self.assertEqual(requests[0][2], 'bytes=65536-')
self.assertEqual(requests[0][3], etag_v1)
self.assertEqual(dest_c.read_bytes(), data_v2)
self.assertFalse(part_c.exists())
self.assertFalse(meta_c.exists())
# Test D: insecure staging permission or mismatched origin is rejected before any HTTP call.
dest_d = Path(root) / 'badperm.bin'
part_d = Path(root) / '.badperm.bin.pages-part'
meta_d = Path(root) / '.badperm.bin.pages-part.json'
part_d.write_bytes(b'abc'); part_d.chmod(0o644)
meta_d.write_text(json.dumps({'origin': base, 'address': 'path:/badperm.bin', 'lang': 'auto',
'expected_sha256': sha_v2, 'total_bytes': len(data_v2), 'etag': etag_v2}))
meta_d.chmod(0o600)
requests.clear()
with self.assertRaisesRegex(Failure, '0600'):
client.download('path:/badperm.bin', str(dest_d), resume=True)
self.assertEqual(requests, [])
part_d.chmod(0o600)
meta_d.write_text(json.dumps({'origin': 'https://other.invalid', 'address': 'path:/badperm.bin', 'lang': 'auto',
'expected_sha256': sha_v2, 'total_bytes': len(data_v2), 'etag': etag_v2}))
with self.assertRaisesRegex(Failure, 'mismatched partial'):
client.download('path:/badperm.bin', str(dest_d), resume=True)
self.assertEqual(requests, [])
def test_streaming_cat_incremental_output_and_post_checksum_and_truncation(self):
payload = (b'stream-line-data\n' * 10000) # 170,000 bytes
digest = hashlib.sha256(payload).hexdigest()
mode = {'body': payload, 'digest': digest, 'cl': len(payload), 'truncate_at': None}
def handle(h):
h.send_response(200)
h.send_header('Content-Type', 'text/plain; charset=utf-8')
if mode['cl'] is not None:
h.send_header('Content-Length', str(mode['cl']))
h.send_header('X-PagesWiki-Revision-UUID', 'rev-cat')
h.send_header('X-PagesWiki-Document-SHA256', mode['digest'])
h.end_headers()
to_send = mode['body'][:mode['truncate_at']] if mode['truncate_at'] is not None else mode['body']
for idx in range(0, len(to_send), 32768):
h.wfile.write(to_send[idx:idx + 32768])
with server(handle) as base, tempfile.TemporaryDirectory() as root:
client = Client(base)
profile = Profile('cat', root)
writes = []
class FakeStdout:
def __init__(self):
self.buffer = self
def isatty(self):
return False
def write(self, data):
writes.append(data)
return len(data)
def flush(self):
pass
fake_out = FakeStdout()
with patch.object(m['sys'], 'stdout', fake_out):
m['execute'](client, profile, ['cat', '/doc.txt', '--stream'])
self.assertGreater(len(writes), 1)
self.assertEqual(b''.join(writes), payload)
# Corrupt checksum triggers non-zero failure warning after streaming.
writes.clear()
mode['digest'] = '0' * 64
with patch.object(m['sys'], 'stdout', fake_out):
with self.assertRaisesRegex(Failure, 'must not be trusted'):
m['execute'](client, profile, ['cat', '/doc.txt', '--stream'])
mode['digest'] = digest
# Premature EOF (shorter than Content-Length) fails explicitly.
writes.clear()
mode['cl'] = len(payload)
mode['truncate_at'] = 5000
with patch.object(m['sys'], 'stdout', fake_out):
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 test_shell_completions_quotes_mid_cursor_and_commands(self):
client = Client('https://example.test', 'token')
def fake_listing(path, prefix=''):
data = {
'/': [
{'name': 'my folder', 'path': '/my folder', 'kind': 'folder'},
{'name': 'my doc', 'path': '/my doc', 'kind': 'file'},
{'name': 'docs', 'path': '/docs', 'kind': 'folder'},
{'name': 'bad\x1bctrl', 'path': '/bad\x1bctrl', 'kind': 'file'},
],
'/docs': [
{'name': 'guide', 'path': '/docs/guide', 'kind': 'file'},
{'name': 'sub dir', 'path': '/docs/sub dir', 'kind': 'folder'},
],
}
entries = [e for e in data.get(path, []) if e['name'].startswith(prefix)]
return {'entries': entries}
with patch.object(client, 'listing', side_effect=fake_listing):
self.assertEqual(m['shell_completions'](client, '/', 'ed'), ['edit'])
self.assertEqual(m['shell_completions'](client, '/', 'm'), ['mget', 'mput'])
self.assertEqual(m['shell_completions'](client, '/', 'task pr'), ['task preferences', 'task project-add', 'task projects'])
self.assertEqual(m['shell_completions'](client, '/', 'cd "my fol'), ['cd "my folder/'])
self.assertEqual(m['shell_completions'](client, '/', "edit 'my d"), ["edit 'my doc'"])
unquoted = m['shell_completions'](client, '/', 'cat my')
self.assertEqual(unquoted, ["cat 'my folder/'", "cat 'my doc'"])
self.assertEqual(m['shell_completions'](client, '/', 'edit docs/gu'), ['edit docs/guide'])
self.assertEqual(m['shell_completions'](client, '/docs', 'ls sub'), ["ls 'sub dir/'"])
self.assertEqual(m['shell_completions'](client, '/', 'edit --l'), [])
self.assertEqual(m['shell_completions'](client, '/', 'cat uuid:123'), [])
def test_fuzzy_pick_ctrl_p_and_opt_in_history(self):
client = Client('https://example.test', 'token')
suggest_items = [
{'path': '/docs/guide', 'label': 'User Guide', 'kind': 'page'},
{'path': '/notes/design', 'label': 'Architecture', 'kind': 'page'},
{'path': '/evil\x07path', 'label': 'Evil', 'kind': 'page'},
]
listing_items = [
{'name': 'local-note', 'path': '/local-note', 'kind': 'file'},
]
def fake_json(route, **kwargs):
self.assertTrue(route.startswith('/_/api/v1/search/suggest?'))
return {'items': suggest_items}
with patch.object(client, 'json', side_effect=fake_json), \
patch.object(client, 'listing', return_value={'entries': listing_items}):
cands = m['_gather_pick_candidates'](client, '/', 'dg')
paths = [c['path'] for c in cands]
self.assertEqual(paths[0], '/docs/guide')
self.assertNotIn('/evil\x07path', paths)
profile = type('P', (), {'name': 'test', 'data': {'cwd': '/', 'expires': time.time() + 600}})()
fake_tty = type('TTY', (), {'isatty': lambda self: True})()
with patch.object(m['sys'], 'stdin', fake_tty), \
patch.object(client, 'json', return_value={'items': suggest_items}), \
patch.object(client, 'listing', return_value={'entries': listing_items}):
with patch('builtins.input', side_effect=['1']), contextlib.redirect_stdout(io.StringIO()):
res = m['fuzzy_pick'](client, profile, initial_query='dg', initial_line='edit ')
self.assertEqual(res, 'edit /docs/guide')
with patch('builtins.input', side_effect=['dg', '1', 'c']), \
patch.dict(m['fuzzy_pick'].__globals__, {'execute': lambda c, p, w: p.data.__setitem__('cwd', w[1])}), \
contextlib.redirect_stdout(io.StringIO()):
res2 = m['fuzzy_pick'](client, profile)
self.assertIsNone(res2)
self.assertEqual(profile.data['cwd'], '/docs/guide')
with patch.object(m['sys'], 'stdin', io.StringIO('')):
with self.assertRaisesRegex(Failure, 'requires a TTY'):
m['fuzzy_pick'](client, profile)
class FakeReadline:
def __init__(self, items=None):
self.items = list(items or [])
self.delims = ''
def set_history_length(self, n): pass
def set_completer_delims(self, d): self.delims = d
def set_completer(self, fn): pass
def parse_and_bind(self, s): pass
def set_completion_display_matches_hook(self, fn): pass
def set_pre_input_hook(self, fn): pass
def get_current_history_length(self): return len(self.items)
def get_history_item(self, i): return self.items[i - 1]
def add_history(self, s): self.items.append(s)
with tempfile.TemporaryDirectory() as root:
fake_rl = FakeReadline()
with patch.dict('sys.modules', {'readline': fake_rl}), \
patch('builtins.input', side_effect=['pwd', 'exit']), \
contextlib.redirect_stdout(io.StringIO()):
m['shell'](client, profile, persist_history=False, history_root=root)
self.assertFalse((Path(root) / 'pages-cli/history').exists())
fake_rl2 = FakeReadline(['ls /docs', 'login', 'cat /a Bearer secret', 'pwd', 'edit pw_api_123'])
with patch.dict('sys.modules', {'readline': fake_rl2}), \
patch('builtins.input', side_effect=['\x1fedit dg', 'exit']), \
patch.dict(m['shell'].__globals__, {'fuzzy_pick': lambda c, p, initial_query='', initial_line='': initial_line + '/docs/guide'}), \
contextlib.redirect_stdout(io.StringIO()):
m['shell'](client, profile, persist_history=True, history_root=root)
hist_file = Path(root) / 'pages-cli/history/test.history'
self.assertTrue(hist_file.exists())
self.assertEqual(stat.S_IMODE(hist_file.parent.stat().st_mode), 0o700)
self.assertEqual(stat.S_IMODE(hist_file.stat().st_mode), 0o600)
saved_lines = hist_file.read_text(encoding='utf-8').splitlines()
self.assertEqual(saved_lines, ['ls /docs', 'pwd'])
loader_rl = FakeReadline()
m['_load_shell_history'](loader_rl, hist_file)
self.assertEqual(loader_rl.items, ['ls /docs', 'pwd'])
hist_file.chmod(0o644)
with self.assertRaisesRegex(Failure, '0600'):
m['_load_shell_history'](FakeReadline(), hist_file)
def oidc_integration(): def oidc_integration():
fixture=json.load(sys.stdin) fixture=json.load(sys.stdin)