Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c92531a257 | ||
|
|
7176b2c47b | ||
|
|
9a0ebd874f | ||
|
|
6d2bbe57ff | ||
|
|
44be7c6382 | ||
|
|
a1956dcc6a | ||
|
|
13a4416af9 |
No files matched your search
+2
-2
@@ -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
|
||||||
|
|||||||
@@ -150,17 +150,23 @@ 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、他のテキストは原文 |
|
||||||
|
| `vi ADDRESS` | ローカルの `vi` を明示起動して編集・CAS保存(未存在時は `$EDITOR` へフォールバック) |
|
||||||
| `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`) | 対話シェルでのインラインfzf風TUIファジー検索選択・フォルダ展開(`TERM=dumb` 等では行選択へフォールバック) |
|
||||||
|
| `!COMMAND` / `!cd DIR`(シェル内) | シェルを使わず(`shell=False` で)ローカルコマンドを実行、`!cd` でローカル作業ディレクトリを移動 |
|
||||||
|
| `$[--stream\|--file] CMD WIKI_PATH`(シェル内) | Wiki上のファイルをローカルアプリへ射影して開く(`vlc`/`mpv` 等はループバックRangeプロキシでストリーミング、その他は読取専用一時ファイル。ローカルファイルは `local:PATH`) |
|
||||||
| `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は後続です。
|
コマンド名・サブコマンド・引用文字・途中カーソル位置・`$CMD` の引数に対応したTab補完、`Ctrl+P`(または `pick`)によるfzf風TUIファジー検索選択(文字入力でリアルタイム絞込、`↑/↓`/`Ctrl+J/K`/`Ctrl+N/P` で移動、`Tab` でフォルダ展開、`Enter` で確定、`Esc`/`Ctrl+C` で取消)、上下キーの履歴に対応しています。履歴は既定でプロセス内のみ保持し、`pages shell --history` を明示指定した場合だけ秘密情報を除外して `0600` ファイルへ保存します。
|
||||||
|
|
||||||
### 言語を指定して編集する
|
### 言語を指定して編集する
|
||||||
|
|
||||||
|
|||||||
+15
-2
@@ -18,6 +18,10 @@ 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` のファジー検索はTTY環境でPOSIX `termios`/`tty` によるインラインTUI(非TTY・`TERM=dumb`時は行選択フォールバック)を提供し、サーバー側の `GET /_/api/v1/search/suggest` と `GET /_/api/v1/path-picker` を使ってサーバー側認可の範囲のみ候補表示する。
|
||||||
|
|
||||||
|
対話シェル内の `!CMD`(`!cd` 含む)は `shell=False` でローカル実行し、Bearerトークンや設定秘密情報を追加しない。`$CMD`(`--stream` / `--file`)はWiki上の正本をローカルアプリへ読み取り専用射影する。メディアプレイヤー等(`vlc`/`mpv`/`ffplay` 等、または `--stream` 明示)に対しては、`127.0.0.1` のみに束縛した一時ループバックHTTPプロキシを起動し、推測不能なワンタイムランダムパスへ中継する(子プロセス引数・環境変数へBearerを出さず、`GET`/`HEAD`/`Range` のみを `NoRedirect`・CLI TLSポリシー付きで中継し、子プロセス終了時に即座に待受を閉じる)。ローカルファイル必須のアプリ(または `--file` 明示)に対しては、`0700` 一時ディレクトリ内へ全体SHA-256検証済みの `0400` 読み取り専用一時ファイルを展開し、終了時(例外・異常終了を含む)に必ず削除する。`vi ADDRESS` はローカルの `vi` バイナリ(未存在時は `$EDITOR`)を `shell=False` で起動し、`edit` と同じCAS保存・復旧契約を共有する。
|
||||||
|
|
||||||
## アドレスと編集
|
## アドレスと編集
|
||||||
|
|
||||||
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 +70,17 @@ 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は後続タスク。
|
||||||
|
|
||||||
|
### サーバー連携待ちの提案API(設計相談中)
|
||||||
|
|
||||||
|
- **アカウント・セッション照会(`whois` / `w` / `last`)**: 既存 `auth_sessions` / `principals` を読み取り専用で返すJSON API(`GET /_/api/v1/auth/whoami`、`GET /_/api/v1/auth/sessions`、`GET /_/api/v1/auth/sessions/history`)をサーバー側と調整中。`token_hash` 等の秘密値は返さず、旧サーバー(`404`/`405`/`501`)への自動フォールバックは行わない。
|
||||||
|
- **明示的空フォルダ/予約エンティティ(`mkdir` 案3)**: 仮想フォルダ(Page存在に付随する接頭辞)とは別に、全クライアントで共有・永続化できる空フォルダ作成・削除・`path-picker` 統合API(例: `PUT /_/api/v1/folders/path:...` + `If-None-Match: *`、`DELETE /_/api/v1/folders/path:...`)をサーバー側と調整中。
|
||||||
+890
-5
@@ -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()
|
||||||
|
def handle(h):
|
||||||
|
h.send_response(200)
|
||||||
|
h.send_header('Content-Type', 'application/octet-stream')
|
||||||
|
h.send_header('Content-Length', str(len(payload)))
|
||||||
|
h.send_header('X-PagesWiki-Revision-UUID', 'rev')
|
||||||
|
h.send_header('X-PagesWiki-Document-SHA256', digest)
|
||||||
|
h.end_headers()
|
||||||
|
h.wfile.write(payload)
|
||||||
|
with server(handle) as base, tempfile.TemporaryDirectory() as root:
|
||||||
profile = Profile('test', root)
|
profile = Profile('test', root)
|
||||||
client=Client('https://example.test')
|
client = Client(base)
|
||||||
file = str(Path(root) / 'download')
|
file = str(Path(root) / 'download')
|
||||||
with patch.object(client,'raw',return_value=(b'data',headers)), contextlib.redirect_stdout(io.StringIO()):
|
with contextlib.redirect_stdout(io.StringIO()):
|
||||||
m['execute'](client, profile, ['get', '/path', file])
|
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(stat.S_IMODE(Path(file).stat().st_mode), 0o600)
|
||||||
with self.assertRaises(FileExistsError): m['execute'](client,profile,['get','/path',file])
|
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,877 @@ 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 test_fuzzy_pick_tui_navigation_caching_and_fallback(self):
|
||||||
|
# Full-width display truncation avoids terminal line wrapping on CJK text.
|
||||||
|
self.assertEqual(m['_truncate_display']('日本語タイトル', 7), '日本語…')
|
||||||
|
self.assertEqual(m['_truncate_display']('日本語タイトル', 6), '日本…')
|
||||||
|
self.assertEqual(m['_truncate_display']('abc\x1bdef', 10), 'abcdef')
|
||||||
|
|
||||||
|
client = Client('https://example.test', 'token')
|
||||||
|
suggest_calls = []
|
||||||
|
listing_calls = []
|
||||||
|
|
||||||
|
def fake_json(route, **kwargs):
|
||||||
|
suggest_calls.append(route)
|
||||||
|
if 'q=guide' in route:
|
||||||
|
return {'items': [
|
||||||
|
{'path': '/docs/guide', 'label': 'User Guide', 'kind': 'page'},
|
||||||
|
{'path': '/docs/guideline', 'label': 'Guideline', 'kind': 'page'},
|
||||||
|
]}
|
||||||
|
return {'items': []}
|
||||||
|
|
||||||
|
def fake_listing(path, prefix=''):
|
||||||
|
listing_calls.append(path)
|
||||||
|
if path == '/':
|
||||||
|
return {'entries': [
|
||||||
|
{'name': 'docs', 'path': '/docs', 'kind': 'folder'},
|
||||||
|
{'name': 'readme', 'path': '/readme', 'kind': 'file'},
|
||||||
|
]}
|
||||||
|
if path == '/docs':
|
||||||
|
return {'entries': [
|
||||||
|
{'name': 'intro', 'path': '/docs/intro', 'kind': 'file'},
|
||||||
|
]}
|
||||||
|
return {'entries': []}
|
||||||
|
|
||||||
|
with patch.object(client, 'json', side_effect=fake_json), \
|
||||||
|
patch.object(client, 'listing', side_effect=fake_listing):
|
||||||
|
# Type 'g', 'u', backspace -> 'g', clear, Tab into /docs, then Enter on /docs/intro.
|
||||||
|
keys = iter([
|
||||||
|
('CHAR', 'g'), ('CHAR', 'u'), 'BACKSPACE', 'CLEAR',
|
||||||
|
'ENTER',
|
||||||
|
])
|
||||||
|
out = io.StringIO()
|
||||||
|
res = m['_run_tui_picker'](
|
||||||
|
client, '/', '', key_reader=lambda: next(keys),
|
||||||
|
out=out, term_size=lambda: os.terminal_size((80, 12)),
|
||||||
|
)
|
||||||
|
self.assertEqual(res, '/docs')
|
||||||
|
rendered = out.getvalue()
|
||||||
|
self.assertIn('\x1b[H\x1b[J', rendered)
|
||||||
|
self.assertIn('\x1b[7m>', rendered)
|
||||||
|
|
||||||
|
# Drill down into /docs folder with Tab, then navigate Down/Up without duplicate HTTP calls.
|
||||||
|
suggest_calls.clear()
|
||||||
|
listing_calls.clear()
|
||||||
|
keys2 = iter([
|
||||||
|
'TAB', 'DOWN', 'UP', 'ENTER',
|
||||||
|
])
|
||||||
|
res2 = m['_run_tui_picker'](
|
||||||
|
client, '/', '', key_reader=lambda: next(keys2),
|
||||||
|
out=io.StringIO(), term_size=lambda: os.terminal_size((80, 12)),
|
||||||
|
)
|
||||||
|
self.assertEqual(res2, '/docs/intro')
|
||||||
|
self.assertEqual(listing_calls, ['/', '/docs'])
|
||||||
|
self.assertEqual(suggest_calls, [])
|
||||||
|
|
||||||
|
# Multi-step typing and ESC cancel returns None and uses query cache.
|
||||||
|
suggest_calls.clear()
|
||||||
|
keys3 = iter([
|
||||||
|
('CHAR', 'g'), ('CHAR', 'u'), ('CHAR', 'i'), ('CHAR', 'd'), ('CHAR', 'e'),
|
||||||
|
'DOWN', 'UP', 'ESC',
|
||||||
|
])
|
||||||
|
res3 = m['_run_tui_picker'](
|
||||||
|
client, '/', '', key_reader=lambda: next(keys3),
|
||||||
|
out=io.StringIO(), term_size=lambda: os.terminal_size((80, 12)),
|
||||||
|
)
|
||||||
|
self.assertIsNone(res3)
|
||||||
|
self.assertEqual(len([c for c in suggest_calls if c.endswith('q=guide')]), 1)
|
||||||
|
|
||||||
|
# TERM=dumb falls back to _line_fuzzy_pick even when both stdin and stdout are TTYs.
|
||||||
|
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(m['sys'], 'stdout', fake_tty), \
|
||||||
|
patch.dict(os.environ, {'TERM': 'dumb'}), \
|
||||||
|
patch.dict(m['fuzzy_pick'].__globals__, {'_line_fuzzy_pick': lambda *a, **kw: '/docs/intro', '_tui_fuzzy_pick': lambda *a, **kw: self.fail('should not invoke TUI on TERM=dumb')}):
|
||||||
|
self.assertEqual(m['fuzzy_pick'](client, profile, initial_line='cat '), 'cat /docs/intro')
|
||||||
|
|
||||||
|
def test_vi_local_commands_and_project_stream_or_file(self):
|
||||||
|
client = Client('https://example.test', 'secret-tok')
|
||||||
|
profile = type('P', (), {'name': 'test', 'data': {'cwd': '/', 'expires': time.time() + 600}})()
|
||||||
|
|
||||||
|
# 1. vi resolves local vi (falling back to $EDITOR) and commits via CAS; completions work for vi/$cmd/!cmd.
|
||||||
|
snapshot_state = {
|
||||||
|
'object_uuid': '00000000-0000-0000-0000-000000000001',
|
||||||
|
'lang': 'en', 'head_revision_uuid': 'rev-1', 'etag': '"rev-1"',
|
||||||
|
'content_type': 'text/plain', 'body': 'before\n', 'markdown': 'before\n',
|
||||||
|
}
|
||||||
|
runs = []
|
||||||
|
def fake_sub_run(cmd, check=False, **kwargs):
|
||||||
|
runs.append(cmd)
|
||||||
|
if cmd and cmd[0] in ('/usr/bin/vi', 'nano'):
|
||||||
|
Path(cmd[-1]).write_text('after\n', encoding='utf-8')
|
||||||
|
return type('R', (), {'returncode': 0})()
|
||||||
|
|
||||||
|
with patch.object(client, 'snapshot', return_value=snapshot_state), \
|
||||||
|
patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}) as save_mock, \
|
||||||
|
patch.object(m['shutil'], 'which', return_value='/usr/bin/vi'), \
|
||||||
|
patch.object(m['subprocess'], 'run', side_effect=fake_sub_run), \
|
||||||
|
patch.dict(os.environ, {'EDITOR': 'nano'}), \
|
||||||
|
contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
m['execute'](client, profile, ['vi', '/note'])
|
||||||
|
self.assertEqual(runs[0][0], '/usr/bin/vi')
|
||||||
|
save_mock.assert_called_once()
|
||||||
|
|
||||||
|
runs.clear()
|
||||||
|
with patch.object(client, 'snapshot', return_value=snapshot_state), \
|
||||||
|
patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}), \
|
||||||
|
patch.object(m['shutil'], 'which', return_value=None), \
|
||||||
|
patch.object(m['subprocess'], 'run', side_effect=fake_sub_run), \
|
||||||
|
patch.dict(os.environ, {'EDITOR': 'nano'}), \
|
||||||
|
contextlib.redirect_stdout(io.StringIO()), \
|
||||||
|
contextlib.redirect_stderr(io.StringIO()) as err:
|
||||||
|
m['execute'](client, profile, ['vi', '/note'])
|
||||||
|
self.assertEqual(runs[0][0], 'nano')
|
||||||
|
self.assertIn('falling back to $EDITOR', err.getvalue())
|
||||||
|
|
||||||
|
with patch.object(client, 'listing', return_value={'entries': [{'name': 'guide', 'path': '/guide', 'kind': 'file'}]}):
|
||||||
|
self.assertEqual(m['shell_completions'](client, '/', 'vi g'), ['vi guide'])
|
||||||
|
self.assertEqual(m['shell_completions'](client, '/', '$vlc g'), ['$vlc guide'])
|
||||||
|
self.assertEqual(m['shell_completions'](client, '/', '$ --stream '), [])
|
||||||
|
self.assertEqual(m['shell_completions'](client, '/', '!ls g'), [])
|
||||||
|
self.assertIn('vi', m['shell_completions'](client, '/', 'v'))
|
||||||
|
|
||||||
|
# 2. !cmd runs locally with shell=False and !cd changes local working directory.
|
||||||
|
orig_cwd = os.getcwd()
|
||||||
|
with tempfile.TemporaryDirectory() as local_tmp:
|
||||||
|
real_tmp = os.path.realpath(local_tmp)
|
||||||
|
try:
|
||||||
|
with contextlib.redirect_stdout(io.StringIO()) as out:
|
||||||
|
m['run_local_command']('!cd ' + m['shlex'].quote(real_tmp))
|
||||||
|
self.assertEqual(os.path.realpath(os.getcwd()), real_tmp)
|
||||||
|
self.assertEqual(out.getvalue().strip(), real_tmp)
|
||||||
|
finally:
|
||||||
|
os.chdir(orig_cwd)
|
||||||
|
runs.clear()
|
||||||
|
with patch.object(m['subprocess'], 'run', side_effect=fake_sub_run):
|
||||||
|
m['run_local_command']('!echo hello world')
|
||||||
|
self.assertEqual(runs[-1], ['echo', 'hello', 'world'])
|
||||||
|
with self.assertRaisesRegex(Failure, 'Local command not found'):
|
||||||
|
m['run_local_command']('!definitely-missing-pages-binary-xyz')
|
||||||
|
|
||||||
|
# 3. $cmd stream mode (loopback HTTP Range proxy) and file mode (verified 0400 temp file).
|
||||||
|
import urllib.error as url_error
|
||||||
|
import urllib.request as url_request
|
||||||
|
media_bytes = b'0123456789ABCDEF' * 1024
|
||||||
|
media_sha = hashlib.sha256(media_bytes).hexdigest()
|
||||||
|
doc_bytes = b'{"title": "hello"}\n'
|
||||||
|
doc_sha = hashlib.sha256(doc_bytes).hexdigest()
|
||||||
|
upstream_auths = []
|
||||||
|
|
||||||
|
class RawHandler(BaseHTTPRequestHandler):
|
||||||
|
protocol_version = 'HTTP/1.1'
|
||||||
|
def log_message(self, format, *args): return
|
||||||
|
def _serve(self, head_only=False):
|
||||||
|
upstream_auths.append(self.headers.get('Authorization'))
|
||||||
|
path_only = m['url'].urlsplit(self.path).path
|
||||||
|
if path_only == '/v/raw/path:/movies/clip.mp4':
|
||||||
|
payload, ctype, sha, etag = media_bytes, 'video/mp4', media_sha, '"m1"'
|
||||||
|
elif path_only == '/v/raw/path:/data/doc.json':
|
||||||
|
payload, ctype, sha, etag = doc_bytes, 'application/json', doc_sha, '"d1"'
|
||||||
|
else:
|
||||||
|
self.send_response(404); self.send_header('Content-Length', '0'); self.end_headers(); return
|
||||||
|
rng = self.headers.get('Range')
|
||||||
|
if rng == 'bytes=2-5':
|
||||||
|
part = payload[2:6]
|
||||||
|
self.send_response(206)
|
||||||
|
self.send_header('Content-Type', ctype)
|
||||||
|
self.send_header('Content-Range', f'bytes 2-5/{len(payload)}')
|
||||||
|
self.send_header('Content-Length', str(len(part)))
|
||||||
|
self.send_header('ETag', etag)
|
||||||
|
self.send_header('X-PagesWiki-Document-SHA256', sha)
|
||||||
|
self.end_headers()
|
||||||
|
if not head_only:
|
||||||
|
self.wfile.write(part)
|
||||||
|
return
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header('Content-Type', ctype)
|
||||||
|
self.send_header('Accept-Ranges', 'bytes')
|
||||||
|
self.send_header('Content-Length', str(len(payload)))
|
||||||
|
self.send_header('ETag', etag)
|
||||||
|
self.send_header('X-PagesWiki-Document-SHA256', sha)
|
||||||
|
self.end_headers()
|
||||||
|
if not head_only:
|
||||||
|
self.wfile.write(payload)
|
||||||
|
def do_GET(self): self._serve(False)
|
||||||
|
def do_HEAD(self): self._serve(True)
|
||||||
|
|
||||||
|
class Server(ThreadingHTTPServer):
|
||||||
|
daemon_threads = True
|
||||||
|
|
||||||
|
srv = Server(('127.0.0.1', 0), RawHandler)
|
||||||
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||||
|
try:
|
||||||
|
srv_client = Client(f'http://127.0.0.1:{srv.server_port}', 'secret-tok')
|
||||||
|
# Stream mode with vlc auto-detection and Range request through loopback proxy.
|
||||||
|
seen_argv = []
|
||||||
|
def stream_child(argv, check=False):
|
||||||
|
seen_argv.extend(argv)
|
||||||
|
target_url = argv[-1]
|
||||||
|
self.assertTrue(target_url.startswith('http://127.0.0.1:'))
|
||||||
|
self.assertTrue(target_url.endswith('/clip.mp4'))
|
||||||
|
self.assertNotIn('secret-tok', ' '.join(argv))
|
||||||
|
with url_request.urlopen(target_url, timeout=5) as r:
|
||||||
|
self.assertEqual(r.status, 200)
|
||||||
|
self.assertEqual(r.read(), media_bytes)
|
||||||
|
req = url_request.Request(target_url, headers={'Range': 'bytes=2-5'})
|
||||||
|
with url_request.urlopen(req, timeout=5) as r:
|
||||||
|
self.assertEqual(r.status, 206)
|
||||||
|
self.assertEqual(r.read(), media_bytes[2:6])
|
||||||
|
bad_url = target_url.rsplit('/', 2)[0] + '/wrong-token/clip.mp4'
|
||||||
|
with self.assertRaises(url_error.HTTPError) as ctx:
|
||||||
|
url_request.urlopen(bad_url, timeout=5)
|
||||||
|
self.assertEqual(ctx.exception.code, 404)
|
||||||
|
ctx.exception.close()
|
||||||
|
post_req = url_request.Request(target_url, data=b'x', method='POST')
|
||||||
|
with self.assertRaises(url_error.HTTPError) as ctx2:
|
||||||
|
url_request.urlopen(post_req, timeout=5)
|
||||||
|
self.assertEqual(ctx2.exception.code, 405)
|
||||||
|
ctx2.exception.close()
|
||||||
|
|
||||||
|
with patch.object(srv_client, 'listing', return_value={'entries': [{'name': 'movies', 'path': '/movies', 'kind': 'folder'}]}):
|
||||||
|
m['run_project_command'](srv_client, '/', '$vlc movies/clip.mp4', runner=stream_child)
|
||||||
|
self.assertEqual(seen_argv[0], 'vlc')
|
||||||
|
self.assertTrue(all(a == 'Bearer secret-tok' for a in upstream_auths))
|
||||||
|
# Proxy closes immediately on child exit.
|
||||||
|
with self.assertRaises(url_error.URLError):
|
||||||
|
url_request.urlopen(seen_argv[-1], timeout=2)
|
||||||
|
|
||||||
|
# File mode for jq (read-only 0400 temp file, cleaned up afterward) and explicit --file on vlc.
|
||||||
|
observed_paths = []
|
||||||
|
def file_child(argv, check=False):
|
||||||
|
observed_paths.append(list(argv))
|
||||||
|
fpath = Path(argv[2])
|
||||||
|
self.assertTrue(fpath.exists())
|
||||||
|
self.assertEqual(fpath.name, 'doc.json')
|
||||||
|
self.assertEqual(stat.S_IMODE(fpath.parent.stat().st_mode), 0o700)
|
||||||
|
self.assertEqual(stat.S_IMODE(fpath.stat().st_mode), 0o400)
|
||||||
|
self.assertEqual(fpath.read_bytes(), doc_bytes)
|
||||||
|
raise RuntimeError('simulated child error')
|
||||||
|
|
||||||
|
with patch.object(srv_client, 'listing', return_value={'entries': [{'name': 'data', 'path': '/data', 'kind': 'folder'}]}):
|
||||||
|
with self.assertRaisesRegex(RuntimeError, 'simulated child error'):
|
||||||
|
m['run_project_command'](srv_client, '/', '$jq .title /data/doc.json local:/tmp/keep.json', runner=file_child)
|
||||||
|
self.assertEqual(observed_paths[0][:2], ['jq', '.title'])
|
||||||
|
# Temporary file and directory are removed even when the child fails.
|
||||||
|
temp_file = Path(observed_paths[0][2])
|
||||||
|
self.assertEqual(observed_paths[0][3], '/tmp/keep.json')
|
||||||
|
self.assertFalse(temp_file.exists())
|
||||||
|
self.assertFalse(temp_file.parent.exists())
|
||||||
|
|
||||||
|
# Explicit --file overrides STREAM_PROJECT_APPS (vlc receives a verified local file instead of HTTP URL).
|
||||||
|
explicit_file_argv = []
|
||||||
|
def explicit_file_child(argv, check=False):
|
||||||
|
explicit_file_argv.extend(argv)
|
||||||
|
self.assertTrue(Path(argv[1]).name == 'clip.mp4')
|
||||||
|
self.assertEqual(Path(argv[1]).read_bytes(), media_bytes)
|
||||||
|
|
||||||
|
m['run_project_command'](srv_client, '/', '$ --file vlc /movies/clip.mp4', runner=explicit_file_child)
|
||||||
|
self.assertEqual(explicit_file_argv[0], 'vlc')
|
||||||
|
self.assertFalse(Path(explicit_file_argv[1]).exists())
|
||||||
|
finally:
|
||||||
|
srv.shutdown()
|
||||||
|
srv.server_close()
|
||||||
|
|
||||||
|
|
||||||
def oidc_integration():
|
def oidc_integration():
|
||||||
fixture=json.load(sys.stdin)
|
fixture=json.load(sys.stdin)
|
||||||
|
|||||||
Reference in new issue
Block a user