From 13a4416af9ccd455d75e3d02ce73fb7a5764ca62 Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Mon, 30 Nov 2026 22:27:52 +0900 Subject: [PATCH] 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 --- README.md | 4 +- docs/client-contract.md | 6 +- pages | 386 ++++++++++++++++++++++++++++++++++++++-- test_pages.py | 326 ++++++++++++++++++++++++++++++++- 4 files changed, 690 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 08cb2ab..63f424c 100644 --- a/README.md +++ b/README.md @@ -150,8 +150,8 @@ OSの言語からは推測しません。最初に名前付きプロファイル | コマンド | 用途 | | --- | --- | | `ls` / `cd` / `pwd` | Semantic Pathをたどる。仮想フォルダにも移動可能 | -| `cat` / `view` | 正本の出力/`$PAGER`で閲覧 | -| `get ADDRESS LOCAL` | 正本をダウンロード。既存のローカルファイルは上書きしない | +| `cat` / `view` | 正本の出力(`--stream` で逐次出力+終端SHA-256検証)/`$PAGER`で閲覧 | +| `get ADDRESS LOCAL` | 正本をファイルへ安全保存(`--resume` / `--max-bytes` / `--timeout`、既存ファイルは上書きしない) | | `edit ADDRESS` | `$EDITOR`で編集。未存在Pathは確認後に新規作成。Wikiはauthoring Markdown、他のテキストは原文 | | `put LOCAL ADDRESS --base REVISION_UUID` | 明示した基点RevisionとのCASで更新 | | `recover [PATH]` | 退避された原稿の一覧表示・再開・破棄(`--list` / `--edit` / `--discard`) | diff --git a/docs/client-contract.md b/docs/client-contract.md index 27976f4..93eb747 100644 --- a/docs/client-contract.md +++ b/docs/client-contract.md @@ -66,8 +66,10 @@ 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件を返す。 -CLIの単体・実バイナリ試験は合成データのみを使用する。サーバー側の権限・CAS・OIDC署名検証とGoのHTTP結合テストはPagesWikiリポジトリで管理する。新規Page作成には `PUT /_/api/v1/pages/path:...` に対応したサーバーが必要。Windowsの資格情報保護とロック移植、巨大ファイル転送は後続タスク。 +CLIの単体・実バイナリ試験は合成データのみを使用する。サーバー側の権限・CAS・OIDC署名検証とGoのHTTP結合テストはPagesWikiリポジトリで管理する。新規Page作成には `PUT /_/api/v1/pages/path:...` に対応したサーバーが必要。Windowsの資格情報保護とロック移植、バイナリ大容量アップロードAPI、一括転送(`mget`/`mput`)は後続タスク。 diff --git a/pages b/pages index 530fa77..ad573e0 100755 --- a/pages +++ b/pages @@ -9,6 +9,7 @@ import uuid import base64 import contextlib import difflib +import errno import fcntl import getpass import hashlib @@ -73,6 +74,24 @@ def address(value, cwd='/'): return 'path:' + semantic(value, cwd) +CHUNK_SIZE = 65536 +DEFAULT_TIMEOUT = 20 +DEFAULT_DEADLINE = 300 +DEFAULT_DOWNLOAD_LIMIT = 64 << 20 + + +def _iter_stream(stream, expected_length, deadline, clock): + remaining = expected_length + while remaining > 0: + if clock() > deadline: + raise Failure('Transfer exceeded total time deadline; no automatic write retry was attempted.') + chunk = stream.read(min(CHUNK_SIZE, remaining)) + if not chunk: + raise Failure('Local input ended before expected Content-Length.') + remaining -= len(chunk) + yield chunk + + class NoRedirect(http.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None # Never forward credentials or turn a login HTML page into success. @@ -92,9 +111,16 @@ class Client: handlers.append(http.HTTPSHandler(context=context)) self.opener = http.build_opener(*handlers) - def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None, headers=None, expect_status=None): + def stream_request(self, route, method='GET', data=None, form=None, *, + limit=4 << 20, etag=None, content_type=None, headers=None, + expect_status=None, on_headers=None, on_chunk=None, + timeout=DEFAULT_TIMEOUT, deadline_seconds=DEFAULT_DEADLINE, + content_length=None, max_request_bytes=2 << 20, clock=time.monotonic): if not route.startswith('/') or route.startswith('//'): raise Failure('Invalid API route.') + if deadline_seconds <= 0 or timeout <= 0: + raise Failure('Transfer timeout and deadline must be positive.') + deadline = clock() + deadline_seconds req_headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION} if headers: req_headers.update(headers) @@ -104,22 +130,61 @@ class Client: req_headers['Authorization'] = 'Bearer ' + self.token body = None if data is not None: - body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode() - req_headers['Content-Type'] = content_type or 'application/json' + if hasattr(data, 'read'): + if not isinstance(content_length, int) or isinstance(content_length, bool) or content_length < 0: + raise Failure('Streaming upload requires a non-negative integer Content-Length.') + if max_request_bytes is not None and content_length > max_request_bytes: + raise Failure('Request exceeds the client upload limit.') + req_headers['Content-Type'] = content_type or 'application/octet-stream' + req_headers['Content-Length'] = str(content_length) + body = _iter_stream(data, content_length, deadline, clock) + else: + body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode() + req_headers['Content-Type'] = content_type or 'application/json' + if max_request_bytes is not None and len(body) > max_request_bytes: + raise Failure('Request exceeds the 2 MiB client limit.') if form is not None: body = url.urlencode(form).encode() req_headers['Content-Type'] = 'application/x-www-form-urlencoded' - if body is not None and len(body) > 2 << 20: - raise Failure('Request exceeds the 2 MiB client limit.') + if max_request_bytes is not None and len(body) > max_request_bytes: + raise Failure('Request exceeds the 2 MiB client limit.') req = http.Request(self.base + route, body, req_headers, method=method) try: - with self.opener.open(req, timeout=20) as response: + with self.opener.open(req, timeout=min(timeout, max(0.1, deadline - clock()))) as response: if expect_status is not None and response.status != expect_status: raise Failure('Unexpected HTTP status (%d).' % response.status, response.status) - raw = response.read(limit + 1) - if len(raw) > limit: + cl_header = (response.headers.get('Content-Length') or '').strip() + expected_cl = int(cl_header) if (method != 'HEAD' and cl_header.isdigit()) else None + if expected_cl is not None and limit is not None and expected_cl > limit: raise Failure('Response exceeds client limit; use the browser for large files.') - return raw, response.headers + if on_headers is not None: + on_headers(response.status, response.headers) + buf = None if on_chunk is not None else bytearray() + total = 0 + while True: + remaining_time = deadline - clock() + if remaining_time <= 0: + raise Failure('Transfer exceeded total time deadline; no automatic write retry was attempted.') + sock = getattr(getattr(getattr(response, 'fp', None), 'raw', None), '_sock', None) + if sock is not None and hasattr(sock, 'settimeout'): + try: + sock.settimeout(min(timeout, remaining_time)) + except OSError: + pass + to_read = CHUNK_SIZE if limit is None else min(CHUNK_SIZE, (limit - total) + 1) + chunk = response.read(to_read) + if not chunk: + break + total += len(chunk) + if limit is not None and total > limit: + raise Failure('Response exceeds client limit; use the browser for large files.') + if on_chunk is not None: + on_chunk(chunk) + else: + buf.extend(chunk) + if expected_cl is not None and total != expected_cl: + raise Failure('Incomplete transfer: received %d of %d bytes.' % (total, expected_cl)) + return (None if on_chunk is not None else bytes(buf)), response.headers except urllib.error.HTTPError as e: raw = e.read(65536) e.close() @@ -131,12 +196,17 @@ class Client: payload = {} messages = {303: 'Login redirect refused; log in again.', 401: 'Session expired or authentication required.', 403: 'Access denied.', 404: 'Not found or not readable.', 409: 'Conflict: remote revision changed.', - 412: 'Conflict: remote item changed; reload before saving.', 422: 'Invalid fields; check dates, project and required settings.', + 412: 'Conflict: remote item changed; reload before saving.', 416: 'Requested byte range is not satisfiable.', + 422: 'Invalid fields; check dates, project and required settings.', 428: 'Precondition required by server.'} raise Failure(messages.get(e.code, 'HTTP request failed (%d); redirects are not followed.' % e.code), e.code, payload) from None except (urllib.error.URLError, TimeoutError, OSError): raise Failure('Connection/TLS failure; no automatic write retry was attempted.') from None + def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None, headers=None, expect_status=None): + return self.stream_request(route, method=method, data=data, form=form, limit=limit, etag=etag, + content_type=content_type, headers=headers, expect_status=expect_status) + def json(self, route, **kwargs): raw, headers = self.request(route, **kwargs) if headers.get_content_type() != 'application/json': @@ -227,14 +297,264 @@ class Client: def listing(self, path, prefix=''): return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix})) - def raw(self, addr, method='GET'): + def raw(self, addr, method='GET', *, limit=DEFAULT_DOWNLOAD_LIMIT, deadline_seconds=DEFAULT_DEADLINE): query = '' if self.lang == 'auto' else '?' + url.urlencode({'lang': self.lang}) - raw, headers = self.request('/v/raw/' + url.quote(addr, safe='/:') + query, method=method, limit=64 << 20) + raw, headers = self.stream_request( + '/v/raw/' + url.quote(addr, safe='/:') + query, method=method, + limit=limit, deadline_seconds=deadline_seconds) digest = headers.get('X-PagesWiki-Document-SHA256') if method == 'GET' and (not digest or hashlib.sha256(raw).hexdigest() != digest): raise Failure('Document SHA-256 mismatch.') return raw, headers + def stream_raw(self, addr, on_chunk, *, on_headers=None, limit=DEFAULT_DOWNLOAD_LIMIT, deadline_seconds=DEFAULT_DEADLINE, clock=time.monotonic): + if limit <= 0 or deadline_seconds <= 0: + raise Failure('Download limit and deadline must be positive.') + query = '' if self.lang == 'auto' else '?' + url.urlencode({'lang': self.lang}) + hasher = hashlib.sha256() + def handle_chunk(chunk): + hasher.update(chunk) + on_chunk(chunk) + _, headers = self.stream_request( + '/v/raw/' + url.quote(addr, safe='/:') + query, method='GET', + limit=limit, on_headers=on_headers, on_chunk=handle_chunk, + deadline_seconds=deadline_seconds, clock=clock) + digest = (headers.get('X-PagesWiki-Document-SHA256') or '').strip() + if not digest or hasher.hexdigest() != digest: + raise Failure('Document SHA-256 mismatch after streaming output; streamed bytes must not be trusted.') + return headers + + @staticmethod + def _write_private_json_atomic(path, data): + tmp = path.parent / ('.pages-meta-' + secrets.token_hex(8) + '.tmp') + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + try: + with os.fdopen(fd, 'w', encoding='utf-8') as out: + out.write(json.dumps(data)) + out.flush() + os.fsync(out.fileno()) + os.replace(tmp, path) + finally: + if tmp.exists() or tmp.is_symlink(): + tmp.unlink() + + @staticmethod + def _hash_file(path): + hasher = hashlib.sha256() + with open(path, 'rb') as src: + while True: + chunk = src.read(CHUNK_SIZE) + if not chunk: + break + hasher.update(chunk) + return hasher.hexdigest() + + @staticmethod + def _commit_no_clobber(src_path, dest): + try: + os.link(src_path, dest) + except OSError as e: + if e.errno == errno.EEXIST: + raise FileExistsError(errno.EEXIST, 'File exists', str(dest)) from None + if e.errno not in (errno.EXDEV, errno.EPERM, errno.EACCES, errno.ENOTSUP, errno.EINVAL): + raise + dst_fd = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + copied = False + try: + with os.fdopen(dst_fd, 'wb') as dst_out, open(src_path, 'rb') as src_in: + while True: + chunk = src_in.read(CHUNK_SIZE) + if not chunk: + break + dst_out.write(chunk) + dst_out.flush() + os.fsync(dst_out.fileno()) + copied = True + finally: + if not copied and dest.exists(): + dest.unlink() + + def download(self, addr, local, *, limit=DEFAULT_DOWNLOAD_LIMIT, deadline_seconds=DEFAULT_DEADLINE, resume=False, clock=time.monotonic): + if limit <= 0 or deadline_seconds <= 0: + raise Failure('Download limit and deadline must be positive.') + dest = Path(local) + if dest.exists() or dest.is_symlink(): + raise FileExistsError(errno.EEXIST, 'File exists', str(dest)) + if not dest.parent.is_dir(): + raise Failure('Destination directory does not exist.') + query = '' if self.lang == 'auto' else '?' + url.urlencode({'lang': self.lang}) + route = '/v/raw/' + url.quote(addr, safe='/:') + query + if not resume: + tmp_path = dest.parent / ('.pages-get-' + secrets.token_hex(8) + '.tmp') + fd = os.open(tmp_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + hasher = hashlib.sha256() + total = [0] + try: + with os.fdopen(fd, 'wb') as out: + def write_chunk(chunk): + hasher.update(chunk) + out.write(chunk) + total[0] += len(chunk) + _, headers = self.stream_request( + route, method='GET', limit=limit, on_chunk=write_chunk, + deadline_seconds=deadline_seconds, clock=clock) + out.flush() + os.fsync(out.fileno()) + digest = (headers.get('X-PagesWiki-Document-SHA256') or '').strip() + if not digest or hasher.hexdigest() != digest: + raise Failure('Document SHA-256 mismatch.') + self._commit_no_clobber(tmp_path, dest) + return headers, total[0] + finally: + if tmp_path.exists() or tmp_path.is_symlink(): + tmp_path.unlink() + + part_path = dest.parent / ('.' + dest.name + '.pages-part') + meta_path = dest.parent / ('.' + dest.name + '.pages-part.json') + offset = 0 + saved_meta = None + if part_path.exists() or part_path.is_symlink() or meta_path.exists() or meta_path.is_symlink(): + if not part_path.exists() or not meta_path.exists(): + raise Failure('Invalid or insecure partial download state; remove partial files before retrying.') + private_file(part_path) + private_file(meta_path) + try: + saved_meta = json.loads(meta_path.read_text(encoding='utf-8')) + except (ValueError, UnicodeError) as e: + raise Failure('Corrupt partial download metadata; remove partial files before retrying.') from e + if (not isinstance(saved_meta, dict) + or saved_meta.get('origin') != self.base + or saved_meta.get('address') != addr + or saved_meta.get('lang') != self.lang + or not isinstance(saved_meta.get('expected_sha256'), str) + or not re.fullmatch(r'[0-9a-f]{64}', saved_meta['expected_sha256']) + or not isinstance(saved_meta.get('total_bytes'), int) + or isinstance(saved_meta.get('total_bytes'), bool) + or saved_meta['total_bytes'] <= 0 + or not isinstance(saved_meta.get('etag', ''), str)): + raise Failure('Invalid or mismatched partial download metadata; remove partial files before retrying.') + if saved_meta['total_bytes'] > limit: + raise Failure('Response exceeds client limit; use the browser for large files.') + actual = part_path.stat().st_size + if actual < 0 or actual > saved_meta['total_bytes']: + raise Failure('Partial download size is inconsistent with metadata; remove partial files before retrying.') + offset = actual + else: + fd = os.open(part_path, os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + os.close(fd) + + if saved_meta is not None and offset == saved_meta['total_bytes'] and offset > 0: + if self._hash_file(part_path) != saved_meta['expected_sha256']: + for p in (part_path, meta_path): + if p.exists(): + p.unlink() + raise Failure('Document SHA-256 mismatch.') + self._commit_no_clobber(part_path, dest) + for p in (part_path, meta_path): + if p.exists(): + p.unlink() + return {'X-PagesWiki-Revision-UUID': saved_meta.get('revision_uuid', 'unknown'), + 'X-PagesWiki-Document-SHA256': saved_meta['expected_sha256']}, offset + + req_headers = {} + if offset > 0: + req_headers['Range'] = f'bytes={offset}-' + if saved_meta.get('etag'): + req_headers['If-Range'] = saved_meta['etag'] + + private_file(part_path) + fd = os.open(part_path, os.O_RDWR | os.O_NOFOLLOW) + resumed_206 = [False] + current_meta = [dict(saved_meta) if saved_meta else None] + received = [offset] + hasher = [hashlib.sha256()] + drop_partial = [False] + headers = None + with os.fdopen(fd, 'r+b') as out: + def on_headers(status, resp_headers): + resp_sha = (resp_headers.get('X-PagesWiki-Document-SHA256') or '').strip() + resp_etag = (resp_headers.get('ETag') or '').strip() + resp_rev = (resp_headers.get('X-PagesWiki-Revision-UUID') or '').strip() + if status == 206: + if offset == 0 or saved_meta is None: + raise Failure('Unexpected 206 Partial Content without a range request.', 206) + cr = (resp_headers.get('Content-Range') or '').strip() + m_cr = re.fullmatch(r'bytes (\d+)-(\d+)/(\d+)', cr) + if not m_cr: + raise Failure('Resume target returned invalid Content-Range; remove partial files to restart.', 412) + start, end, total_len = int(m_cr.group(1)), int(m_cr.group(2)), int(m_cr.group(3)) + if (start != offset or end < start or total_len != saved_meta['total_bytes'] + or total_len > limit or resp_sha != saved_meta['expected_sha256']): + raise Failure('Resume target changed or Content-Range mismatched; remove partial files to restart.', 412) + out.seek(offset) + out.truncate(offset) + resumed_206[0] = True + elif status == 200: + cl_h = (resp_headers.get('Content-Length') or '').strip() + total_len = int(cl_h) if cl_h.isdigit() else None + out.seek(0) + out.truncate(0) + received[0] = 0 + resumed_206[0] = False + hasher[0] = hashlib.sha256() + current_meta[0] = { + 'origin': self.base, 'address': addr, 'lang': self.lang, + 'revision_uuid': resp_rev, 'expected_sha256': resp_sha, + 'etag': resp_etag, 'total_bytes': total_len, 'received_bytes': 0, + } + if total_len is not None and resp_sha and re.fullmatch(r'[0-9a-f]{64}', resp_sha): + self._write_private_json_atomic(meta_path, current_meta[0]) + else: + raise Failure('Unexpected HTTP status (%d).' % status, status) + + def write_chunk(chunk): + if received[0] + len(chunk) > limit: + drop_partial[0] = True + raise Failure('Response exceeds client limit; use the browser for large files.') + out.write(chunk) + if not resumed_206[0]: + hasher[0].update(chunk) + received[0] += len(chunk) + + try: + _, headers = self.stream_request( + route, method='GET', headers=req_headers, limit=limit, + on_headers=on_headers, on_chunk=write_chunk, + deadline_seconds=deadline_seconds, clock=clock) + out.flush() + os.fsync(out.fileno()) + except (Failure, KeyboardInterrupt): + meta = current_meta[0] + if (not drop_partial[0] and received[0] > 0 and meta + and meta.get('expected_sha256') and re.fullmatch(r'[0-9a-f]{64}', meta['expected_sha256']) + and isinstance(meta.get('total_bytes'), int) and meta['total_bytes'] > 0): + try: + out.flush() + os.fsync(out.fileno()) + except OSError: + pass + meta['received_bytes'] = received[0] + self._write_private_json_atomic(meta_path, meta) + print('Partial download retained (%d/%d bytes). Re-run with --resume to continue.' % (received[0], meta['total_bytes']), file=sys.stderr) + else: + for p in (part_path, meta_path): + if p.exists() or p.is_symlink(): + p.unlink() + raise + + final_digest = self._hash_file(part_path) if resumed_206[0] else hasher[0].hexdigest() + digest = (headers.get('X-PagesWiki-Document-SHA256') or '').strip() + if not digest or final_digest != digest: + for p in (part_path, meta_path): + if p.exists() or p.is_symlink(): + p.unlink() + raise Failure('Document SHA-256 mismatch.') + self._commit_no_clobber(part_path, dest) + for p in (part_path, meta_path): + if p.exists() or p.is_symlink(): + p.unlink() + return headers, received[0] + def snapshot(self, addr, lang=None): if addr.startswith('rev:'): raise Failure('Revision addresses are immutable; edit a path: or uuid: address.') @@ -1067,7 +1387,14 @@ def execute(client, profile, words): if command == 'edit': p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto') p.add_argument('--lang', help='auto edits the visible language (or creates as und with warning); an explicit tag selects or creates a language revision') + elif command == 'cat': + p.add_argument('--stream', action='store_true', help='Stream chunks directly to stdout and verify SHA-256 at end (exits non-zero if corrupt)') + p.add_argument('--max-bytes', type=int, default=DEFAULT_DOWNLOAD_LIMIT, help='Maximum transfer size in bytes (default: 64 MiB)') + p.add_argument('--timeout', type=int, default=DEFAULT_DEADLINE, help='Total transfer deadline in seconds (default: 300)') p = sub.add_parser('get'); p.add_argument('path'); p.add_argument('local') + p.add_argument('--resume', action='store_true', help='Retain partial download pieces on interruption and resume via HTTP Range/If-Range') + p.add_argument('--max-bytes', type=int, default=DEFAULT_DOWNLOAD_LIMIT, help='Maximum download size in bytes (default: 64 MiB)') + p.add_argument('--timeout', type=int, default=DEFAULT_DEADLINE, help='Total transfer deadline in seconds (default: 300)') p = sub.add_parser('put'); p.add_argument('local'); p.add_argument('path'); p.add_argument('--base', required=True) p.add_argument('--format', choices=['raw', 'markdown'], default='raw') p = sub.add_parser('recover', help='List, resume, or discard retained local edit drafts') @@ -1116,19 +1443,40 @@ def execute(client, profile, words): editing = Client(client.base, client.token, language(args.lang), insecure=client.insecure) if args.lang else client editor(editing, addr, args.format) elif cmd == 'put': + local_path = Path(args.local) + if local_path.exists() and local_path.stat().st_size > 1 << 20: + raise Failure('Text edit exceeds the 1 MiB client limit.') state = client.snapshot(addr) if not state['head_revision_uuid']: raise Failure('No revision in the target language; use edit --lang to create a language revision.') if state['head_revision_uuid'] != args.base: raise Failure('Conflict: supplied base is not the current language head.', 409) - text = Path(args.local).read_text(encoding='utf-8') + text = local_path.read_text(encoding='utf-8') print('Revision:', safe_text(client.save(state, text, args.format == 'markdown')['revision_uuid'])) + elif cmd == 'get': + if args.max_bytes <= 0 or args.timeout <= 0: + raise Failure('Download limit and timeout must be positive.') + headers, _ = client.download(addr, args.local, limit=args.max_bytes, deadline_seconds=args.timeout, resume=args.resume) + print('Revision:', safe_text(headers.get('X-PagesWiki-Revision-UUID', 'unknown'))) + elif cmd == 'cat' and args.stream: + if args.max_bytes <= 0 or args.timeout <= 0: + raise Failure('Download limit and timeout must be positive.') + def check_stream_headers(status, headers): + if sys.stdout.isatty() and not (headers.get_content_type().startswith('text/') or headers.get_content_type() in ('application/json', 'application/xml')): + raise Failure('Binary document: use get or open.') + def write_stream_chunk(chunk): + if sys.stdout.isatty(): + sys.stdout.write(safe_text(chunk.decode('utf-8', errors='replace'))) + sys.stdout.flush() + else: + sys.stdout.buffer.write(chunk) + sys.stdout.buffer.flush() + client.stream_raw(addr, write_stream_chunk, on_headers=check_stream_headers, limit=args.max_bytes, deadline_seconds=args.timeout) else: - raw, headers = client.raw(addr) - if cmd == 'get': - fd = os.open(args.local, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) - with os.fdopen(fd, 'wb') as out: out.write(raw) - print('Revision:', safe_text(headers.get('X-PagesWiki-Revision-UUID', 'unknown'))) - elif cmd == 'cat' and not sys.stdout.isatty(): + raw_kwargs = {'limit': args.max_bytes, 'deadline_seconds': args.timeout} if cmd == 'cat' else {} + if cmd == 'cat' and (args.max_bytes <= 0 or args.timeout <= 0): + raise Failure('Download limit and timeout must be positive.') + raw, headers = client.raw(addr, **raw_kwargs) + if cmd == 'cat' and not sys.stdout.isatty(): sys.stdout.buffer.write(raw) else: if not (headers.get_content_type().startswith('text/') or headers.get_content_type() in ('application/json', 'application/xml')): diff --git a/test_pages.py b/test_pages.py index 588bc96..89c15a1 100644 --- a/test_pages.py +++ b/test_pages.py @@ -301,15 +301,29 @@ class RemoteTests(unittest.TestCase): with self.assertRaises(Failure): client.save(state,'new') def test_download_private_and_no_clobber(self): - headers=Message(); headers['X-PagesWiki-Revision-UUID']='rev' - with tempfile.TemporaryDirectory() as root: - profile=Profile('test',root) - client=Client('https://example.test') - file=str(Path(root)/'download') - with patch.object(client,'raw',return_value=(b'data',headers)), contextlib.redirect_stdout(io.StringIO()): - m['execute'](client,profile,['get','/path',file]) - self.assertEqual(stat.S_IMODE(Path(file).stat().st_mode),0o600) - with self.assertRaises(FileExistsError): m['execute'](client,profile,['get','/path',file]) + payload = b'data' + 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) + 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): client=Client('https://example.test','token') @@ -823,6 +837,300 @@ class RemoteTests(unittest.TestCase): self.assertIn('Discarded recovery draft', out.getvalue()) 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 oidc_integration(): fixture=json.load(sys.stdin)