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
This commit is contained in:
Anya Tokugawa committed 2026-11-30 22:27:52 +09:00
1 parent a7ef59f8c0
commit 13a4416af9
4 files changed
+690 -32

No files matched your search

+317 -9
View File
@@ -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)