|
|
@@ -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,605 @@ class RemoteTests(unittest.TestCase):
|
|
|
|
self.assertIn('Discarded recovery draft', out.getvalue())
|
|
|
|
self.assertIn('Discarded recovery draft', out.getvalue())
|
|
|
|
self.assertFalse(discard_dir.exists())
|
|
|
|
self.assertFalse(discard_dir.exists())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_streaming_download_chunks_integrity_limits_cancel_and_deadline(self):
|
|
|
|
|
|
|
|
large = (b'0123456789abcdef' * 12800) # 204,800 bytes (> 3 * CHUNK_SIZE)
|
|
|
|
|
|
|
|
large_digest = hashlib.sha256(large).hexdigest()
|
|
|
|
|
|
|
|
mode = {'data': large, 'digest': large_digest, 'send_cl': True}
|
|
|
|
|
|
|
|
def handle(h):
|
|
|
|
|
|
|
|
h.send_response(200)
|
|
|
|
|
|
|
|
h.send_header('Content-Type', 'application/octet-stream')
|
|
|
|
|
|
|
|
if mode['send_cl']:
|
|
|
|
|
|
|
|
h.send_header('Content-Length', str(len(mode['data'])))
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Revision-UUID', 'rev-large')
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Document-SHA256', mode['digest'])
|
|
|
|
|
|
|
|
h.end_headers()
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
|
|
for idx in range(0, len(mode['data']), 16384):
|
|
|
|
|
|
|
|
h.wfile.write(mode['data'][idx:idx + 16384])
|
|
|
|
|
|
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
with server(handle) as base, tempfile.TemporaryDirectory() as root:
|
|
|
|
|
|
|
|
client = Client(base)
|
|
|
|
|
|
|
|
profile = Profile('stream', root)
|
|
|
|
|
|
|
|
dest = Path(root) / 'large.bin'
|
|
|
|
|
|
|
|
with contextlib.redirect_stdout(io.StringIO()):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['get', '/large.bin', str(dest)])
|
|
|
|
|
|
|
|
self.assertEqual(dest.read_bytes(), large)
|
|
|
|
|
|
|
|
self.assertEqual(stat.S_IMODE(dest.stat().st_mode), 0o600)
|
|
|
|
|
|
|
|
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# SHA-256 mismatch leaves neither destination nor temp file.
|
|
|
|
|
|
|
|
mode['digest'] = '0' * 64
|
|
|
|
|
|
|
|
bad_dest = Path(root) / 'bad.bin'
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'SHA-256 mismatch'):
|
|
|
|
|
|
|
|
client.download('path:/bad.bin', str(bad_dest))
|
|
|
|
|
|
|
|
self.assertFalse(bad_dest.exists())
|
|
|
|
|
|
|
|
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
|
|
|
|
|
|
|
|
mode['digest'] = large_digest
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Limit rejected early via Content-Length and mid-stream without Content-Length.
|
|
|
|
|
|
|
|
mode['data'] = b'x' * 200
|
|
|
|
|
|
|
|
mode['digest'] = hashlib.sha256(mode['data']).hexdigest()
|
|
|
|
|
|
|
|
for send_cl in (True, False):
|
|
|
|
|
|
|
|
mode['send_cl'] = send_cl
|
|
|
|
|
|
|
|
over_dest = Path(root) / f'over-{send_cl}.bin'
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'exceeds client limit'):
|
|
|
|
|
|
|
|
client.download('path:/over', str(over_dest), limit=100)
|
|
|
|
|
|
|
|
self.assertFalse(over_dest.exists())
|
|
|
|
|
|
|
|
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'exceeds client limit'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['get', '/over', str(Path(root) / 'cli-over.bin'), '--max-bytes', '100'])
|
|
|
|
|
|
|
|
self.assertFalse((Path(root) / 'cli-over.bin').exists())
|
|
|
|
|
|
|
|
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Cancellation (Ctrl+C / KeyboardInterrupt) cleans up temp file cleanly.
|
|
|
|
|
|
|
|
mode['data'] = large; mode['digest'] = large_digest; mode['send_cl'] = True
|
|
|
|
|
|
|
|
cancel_dest = Path(root) / 'cancel.bin'
|
|
|
|
|
|
|
|
with patch.object(m['os'], 'fsync', side_effect=KeyboardInterrupt()):
|
|
|
|
|
|
|
|
with self.assertRaises(KeyboardInterrupt):
|
|
|
|
|
|
|
|
client.download('path:/cancel', str(cancel_dest))
|
|
|
|
|
|
|
|
self.assertFalse(cancel_dest.exists())
|
|
|
|
|
|
|
|
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Total transfer deadline cleans up temp file cleanly.
|
|
|
|
|
|
|
|
ticks = iter([0.0, 0.0, 10.0])
|
|
|
|
|
|
|
|
deadline_dest = Path(root) / 'slow.bin'
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'total time deadline'):
|
|
|
|
|
|
|
|
client.download('path:/slow', str(deadline_dest), deadline_seconds=5, clock=lambda: next(ticks, 10.0))
|
|
|
|
|
|
|
|
self.assertFalse(deadline_dest.exists())
|
|
|
|
|
|
|
|
self.assertEqual(list(Path(root).glob('.pages-get-*')), [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_streaming_upload_chunks_deadline_and_put_precheck(self):
|
|
|
|
|
|
|
|
received = []
|
|
|
|
|
|
|
|
def handle(h):
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
|
|
length = int(h.headers.get('Content-Length', 0))
|
|
|
|
|
|
|
|
data = h.rfile.read(length)
|
|
|
|
|
|
|
|
received.append((h.command, length, data))
|
|
|
|
|
|
|
|
reply(h, 200, {'status': 'ok'})
|
|
|
|
|
|
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
payload = b'stream-chunk-' * 12000 # 156,000 bytes
|
|
|
|
|
|
|
|
with server(handle) as base:
|
|
|
|
|
|
|
|
client = Client(base, 'token')
|
|
|
|
|
|
|
|
raw, _ = client.stream_request(
|
|
|
|
|
|
|
|
'/upload', method='PUT', data=io.BytesIO(payload),
|
|
|
|
|
|
|
|
content_length=len(payload), content_type='application/octet-stream',
|
|
|
|
|
|
|
|
max_request_bytes=1 << 20)
|
|
|
|
|
|
|
|
self.assertEqual(json.loads(raw), {'status': 'ok'})
|
|
|
|
|
|
|
|
self.assertEqual(received[0][0], 'PUT')
|
|
|
|
|
|
|
|
self.assertEqual(received[0][1], len(payload))
|
|
|
|
|
|
|
|
self.assertEqual(received[0][2], payload)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ticks = iter([0.0, 0.0, 10.0])
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'total time deadline'):
|
|
|
|
|
|
|
|
client.stream_request(
|
|
|
|
|
|
|
|
'/upload', method='PUT', data=io.BytesIO(payload),
|
|
|
|
|
|
|
|
content_length=len(payload), content_type='application/octet-stream',
|
|
|
|
|
|
|
|
max_request_bytes=1 << 20, deadline_seconds=5, clock=lambda: next(ticks, 10.0))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with tempfile.TemporaryDirectory() as root:
|
|
|
|
|
|
|
|
profile = Profile('test', root)
|
|
|
|
|
|
|
|
profile.data = {'cwd': '/'}
|
|
|
|
|
|
|
|
too_big = Path(root) / 'big.txt'
|
|
|
|
|
|
|
|
too_big.write_bytes(b'a' * ((1 << 20) + 1))
|
|
|
|
|
|
|
|
client = Client('https://example.test', 'token')
|
|
|
|
|
|
|
|
with patch.object(client, 'snapshot') as snap_mock, patch.object(client, 'save') as save_mock:
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, '1 MiB client limit'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['put', str(too_big), '/page', '--base', 'rev-1'])
|
|
|
|
|
|
|
|
snap_mock.assert_not_called()
|
|
|
|
|
|
|
|
save_mock.assert_not_called()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_resumable_file_download_pieces_range_and_full_rehash(self):
|
|
|
|
|
|
|
|
data_v1 = (b'piece-v1-' * 20000) # 180,000 bytes
|
|
|
|
|
|
|
|
sha_v1 = hashlib.sha256(data_v1).hexdigest()
|
|
|
|
|
|
|
|
etag_v1 = '"' + sha_v1 + '"'
|
|
|
|
|
|
|
|
data_v2 = (b'piece-v2-' * 22000) # 198,000 bytes
|
|
|
|
|
|
|
|
sha_v2 = hashlib.sha256(data_v2).hexdigest()
|
|
|
|
|
|
|
|
etag_v2 = '"' + sha_v2 + '"'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
state = {'body': data_v1, 'sha': sha_v1, 'etag': etag_v1, 'rev': 'rev-1', 'interrupt_after': None}
|
|
|
|
|
|
|
|
requests = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def handle(h):
|
|
|
|
|
|
|
|
requests.append((h.command, h.path, h.headers.get('Range'), h.headers.get('If-Range')))
|
|
|
|
|
|
|
|
body = state['body']
|
|
|
|
|
|
|
|
rng = h.headers.get('Range')
|
|
|
|
|
|
|
|
if_rng = h.headers.get('If-Range')
|
|
|
|
|
|
|
|
if rng and rng.startswith('bytes=') and (if_rng is None or if_rng == state['etag']):
|
|
|
|
|
|
|
|
start = int(rng.split('=', 1)[1].split('-', 1)[0])
|
|
|
|
|
|
|
|
part = body[start:]
|
|
|
|
|
|
|
|
h.send_response(206)
|
|
|
|
|
|
|
|
h.send_header('Content-Type', 'application/octet-stream')
|
|
|
|
|
|
|
|
h.send_header('Content-Length', str(len(part)))
|
|
|
|
|
|
|
|
h.send_header('Content-Range', f'bytes {start}-{len(body) - 1}/{len(body)}')
|
|
|
|
|
|
|
|
h.send_header('ETag', state['etag'])
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Revision-UUID', state['rev'])
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Document-SHA256', state['sha'])
|
|
|
|
|
|
|
|
h.end_headers()
|
|
|
|
|
|
|
|
h.wfile.write(part)
|
|
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
h.send_response(200)
|
|
|
|
|
|
|
|
h.send_header('Content-Type', 'application/octet-stream')
|
|
|
|
|
|
|
|
h.send_header('Content-Length', str(len(body)))
|
|
|
|
|
|
|
|
h.send_header('ETag', state['etag'])
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Revision-UUID', state['rev'])
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Document-SHA256', state['sha'])
|
|
|
|
|
|
|
|
h.end_headers()
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
|
|
limit_bytes = state['interrupt_after']
|
|
|
|
|
|
|
|
to_send = body[:limit_bytes] if limit_bytes is not None else body
|
|
|
|
|
|
|
|
for idx in range(0, len(to_send), 16384):
|
|
|
|
|
|
|
|
h.wfile.write(to_send[idx:idx + 16384])
|
|
|
|
|
|
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with server(handle) as base, tempfile.TemporaryDirectory() as root:
|
|
|
|
|
|
|
|
client = Client(base)
|
|
|
|
|
|
|
|
profile = Profile('resume', root)
|
|
|
|
|
|
|
|
dest = Path(root) / 'file.bin'
|
|
|
|
|
|
|
|
part_file = Path(root) / '.file.bin.pages-part'
|
|
|
|
|
|
|
|
meta_file = Path(root) / '.file.bin.pages-part.json'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Test A: interrupt mid-download, keep private 0600 pieces, then resume via Range/If-Range.
|
|
|
|
|
|
|
|
state['interrupt_after'] = 65536
|
|
|
|
|
|
|
|
with contextlib.redirect_stderr(io.StringIO()) as err:
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'Incomplete transfer'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['get', '/file.bin', str(dest), '--resume'])
|
|
|
|
|
|
|
|
self.assertFalse(dest.exists())
|
|
|
|
|
|
|
|
self.assertTrue(part_file.exists() and meta_file.exists())
|
|
|
|
|
|
|
|
self.assertEqual(stat.S_IMODE(part_file.stat().st_mode), 0o600)
|
|
|
|
|
|
|
|
self.assertEqual(stat.S_IMODE(meta_file.stat().st_mode), 0o600)
|
|
|
|
|
|
|
|
self.assertEqual(part_file.stat().st_size, 65536)
|
|
|
|
|
|
|
|
self.assertIn('Partial download retained', err.getvalue())
|
|
|
|
|
|
|
|
meta = json.loads(meta_file.read_text(encoding='utf-8'))
|
|
|
|
|
|
|
|
self.assertEqual(meta['expected_sha256'], sha_v1)
|
|
|
|
|
|
|
|
self.assertEqual(meta['total_bytes'], len(data_v1))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
state['interrupt_after'] = None
|
|
|
|
|
|
|
|
requests.clear()
|
|
|
|
|
|
|
|
with contextlib.redirect_stdout(io.StringIO()):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['get', '/file.bin', str(dest), '--resume'])
|
|
|
|
|
|
|
|
self.assertEqual(requests[0][2], 'bytes=65536-')
|
|
|
|
|
|
|
|
self.assertEqual(requests[0][3], etag_v1)
|
|
|
|
|
|
|
|
self.assertEqual(dest.read_bytes(), data_v1)
|
|
|
|
|
|
|
|
self.assertEqual(stat.S_IMODE(dest.stat().st_mode), 0o600)
|
|
|
|
|
|
|
|
self.assertFalse(part_file.exists())
|
|
|
|
|
|
|
|
self.assertFalse(meta_file.exists())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Test B: mid-file corruption in .pages-part is caught by full re-hash before commit.
|
|
|
|
|
|
|
|
dest_b = Path(root) / 'corrupt.bin'
|
|
|
|
|
|
|
|
part_b = Path(root) / '.corrupt.bin.pages-part'
|
|
|
|
|
|
|
|
meta_b = Path(root) / '.corrupt.bin.pages-part.json'
|
|
|
|
|
|
|
|
state['interrupt_after'] = 65536
|
|
|
|
|
|
|
|
with contextlib.redirect_stderr(io.StringIO()):
|
|
|
|
|
|
|
|
with self.assertRaises(Failure):
|
|
|
|
|
|
|
|
client.download('path:/corrupt.bin', str(dest_b), resume=True)
|
|
|
|
|
|
|
|
raw_part = bytearray(part_b.read_bytes())
|
|
|
|
|
|
|
|
raw_part[0] ^= 0xFF
|
|
|
|
|
|
|
|
part_b.write_bytes(bytes(raw_part))
|
|
|
|
|
|
|
|
state['interrupt_after'] = None
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'SHA-256 mismatch'):
|
|
|
|
|
|
|
|
client.download('path:/corrupt.bin', str(dest_b), resume=True)
|
|
|
|
|
|
|
|
self.assertFalse(dest_b.exists())
|
|
|
|
|
|
|
|
self.assertFalse(part_b.exists())
|
|
|
|
|
|
|
|
self.assertFalse(meta_b.exists())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Test C: If-Range mismatch when remote page changed restarts cleanly from offset 0.
|
|
|
|
|
|
|
|
dest_c = Path(root) / 'updated.bin'
|
|
|
|
|
|
|
|
part_c = Path(root) / '.updated.bin.pages-part'
|
|
|
|
|
|
|
|
meta_c = Path(root) / '.updated.bin.pages-part.json'
|
|
|
|
|
|
|
|
state['interrupt_after'] = 65536
|
|
|
|
|
|
|
|
with contextlib.redirect_stderr(io.StringIO()):
|
|
|
|
|
|
|
|
with self.assertRaises(Failure):
|
|
|
|
|
|
|
|
client.download('path:/updated.bin', str(dest_c), resume=True)
|
|
|
|
|
|
|
|
state.update({'body': data_v2, 'sha': sha_v2, 'etag': etag_v2, 'rev': 'rev-2', 'interrupt_after': None})
|
|
|
|
|
|
|
|
requests.clear()
|
|
|
|
|
|
|
|
client.download('path:/updated.bin', str(dest_c), resume=True)
|
|
|
|
|
|
|
|
self.assertEqual(requests[0][2], 'bytes=65536-')
|
|
|
|
|
|
|
|
self.assertEqual(requests[0][3], etag_v1)
|
|
|
|
|
|
|
|
self.assertEqual(dest_c.read_bytes(), data_v2)
|
|
|
|
|
|
|
|
self.assertFalse(part_c.exists())
|
|
|
|
|
|
|
|
self.assertFalse(meta_c.exists())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Test D: insecure staging permission or mismatched origin is rejected before any HTTP call.
|
|
|
|
|
|
|
|
dest_d = Path(root) / 'badperm.bin'
|
|
|
|
|
|
|
|
part_d = Path(root) / '.badperm.bin.pages-part'
|
|
|
|
|
|
|
|
meta_d = Path(root) / '.badperm.bin.pages-part.json'
|
|
|
|
|
|
|
|
part_d.write_bytes(b'abc'); part_d.chmod(0o644)
|
|
|
|
|
|
|
|
meta_d.write_text(json.dumps({'origin': base, 'address': 'path:/badperm.bin', 'lang': 'auto',
|
|
|
|
|
|
|
|
'expected_sha256': sha_v2, 'total_bytes': len(data_v2), 'etag': etag_v2}))
|
|
|
|
|
|
|
|
meta_d.chmod(0o600)
|
|
|
|
|
|
|
|
requests.clear()
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, '0600'):
|
|
|
|
|
|
|
|
client.download('path:/badperm.bin', str(dest_d), resume=True)
|
|
|
|
|
|
|
|
self.assertEqual(requests, [])
|
|
|
|
|
|
|
|
part_d.chmod(0o600)
|
|
|
|
|
|
|
|
meta_d.write_text(json.dumps({'origin': 'https://other.invalid', 'address': 'path:/badperm.bin', 'lang': 'auto',
|
|
|
|
|
|
|
|
'expected_sha256': sha_v2, 'total_bytes': len(data_v2), 'etag': etag_v2}))
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'mismatched partial'):
|
|
|
|
|
|
|
|
client.download('path:/badperm.bin', str(dest_d), resume=True)
|
|
|
|
|
|
|
|
self.assertEqual(requests, [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_streaming_cat_incremental_output_and_post_checksum_and_truncation(self):
|
|
|
|
|
|
|
|
payload = (b'stream-line-data\n' * 10000) # 170,000 bytes
|
|
|
|
|
|
|
|
digest = hashlib.sha256(payload).hexdigest()
|
|
|
|
|
|
|
|
mode = {'body': payload, 'digest': digest, 'cl': len(payload), 'truncate_at': None}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def handle(h):
|
|
|
|
|
|
|
|
h.send_response(200)
|
|
|
|
|
|
|
|
h.send_header('Content-Type', 'text/plain; charset=utf-8')
|
|
|
|
|
|
|
|
if mode['cl'] is not None:
|
|
|
|
|
|
|
|
h.send_header('Content-Length', str(mode['cl']))
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Revision-UUID', 'rev-cat')
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Document-SHA256', mode['digest'])
|
|
|
|
|
|
|
|
h.end_headers()
|
|
|
|
|
|
|
|
to_send = mode['body'][:mode['truncate_at']] if mode['truncate_at'] is not None else mode['body']
|
|
|
|
|
|
|
|
for idx in range(0, len(to_send), 32768):
|
|
|
|
|
|
|
|
h.wfile.write(to_send[idx:idx + 32768])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with server(handle) as base, tempfile.TemporaryDirectory() as root:
|
|
|
|
|
|
|
|
client = Client(base)
|
|
|
|
|
|
|
|
profile = Profile('cat', root)
|
|
|
|
|
|
|
|
writes = []
|
|
|
|
|
|
|
|
class FakeStdout:
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
|
|
self.buffer = self
|
|
|
|
|
|
|
|
def isatty(self):
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
def write(self, data):
|
|
|
|
|
|
|
|
writes.append(data)
|
|
|
|
|
|
|
|
return len(data)
|
|
|
|
|
|
|
|
def flush(self):
|
|
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fake_out = FakeStdout()
|
|
|
|
|
|
|
|
with patch.object(m['sys'], 'stdout', fake_out):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['cat', '/doc.txt', '--stream'])
|
|
|
|
|
|
|
|
self.assertGreater(len(writes), 1)
|
|
|
|
|
|
|
|
self.assertEqual(b''.join(writes), payload)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Corrupt checksum triggers non-zero failure warning after streaming.
|
|
|
|
|
|
|
|
writes.clear()
|
|
|
|
|
|
|
|
mode['digest'] = '0' * 64
|
|
|
|
|
|
|
|
with patch.object(m['sys'], 'stdout', fake_out):
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'must not be trusted'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['cat', '/doc.txt', '--stream'])
|
|
|
|
|
|
|
|
mode['digest'] = digest
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Premature EOF (shorter than Content-Length) fails explicitly.
|
|
|
|
|
|
|
|
writes.clear()
|
|
|
|
|
|
|
|
mode['cl'] = len(payload)
|
|
|
|
|
|
|
|
mode['truncate_at'] = 5000
|
|
|
|
|
|
|
|
with patch.object(m['sys'], 'stdout', fake_out):
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'Incomplete transfer'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['cat', '/doc.txt', '--stream'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_mget_remote_glob_recursive_dry_run_no_clobber_and_traversal_guard(self):
|
|
|
|
|
|
|
|
tree = {
|
|
|
|
|
|
|
|
'/docs': {
|
|
|
|
|
|
|
|
'entries': [
|
|
|
|
|
|
|
|
{'name': 'a.md', 'path': '/docs/a.md', 'kind': 'file'},
|
|
|
|
|
|
|
|
{'name': 'b.txt', 'path': '/docs/b.txt', 'kind': 'file'},
|
|
|
|
|
|
|
|
{'name': 'sub', 'path': '/docs/sub', 'kind': 'folder'},
|
|
|
|
|
|
|
|
],
|
|
|
|
|
|
|
|
'truncated': False,
|
|
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
'/docs/sub': {
|
|
|
|
|
|
|
|
'entries': [
|
|
|
|
|
|
|
|
{'name': 'deep.md', 'path': '/docs/sub/deep.md', 'kind': 'file'},
|
|
|
|
|
|
|
|
],
|
|
|
|
|
|
|
|
'truncated': False,
|
|
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
'/evil': {
|
|
|
|
|
|
|
|
'entries': [
|
|
|
|
|
|
|
|
{'name': '../escape', 'path': '/evil/../escape', 'kind': 'file'},
|
|
|
|
|
|
|
|
],
|
|
|
|
|
|
|
|
'truncated': False,
|
|
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
'/trunc': {
|
|
|
|
|
|
|
|
'entries': [
|
|
|
|
|
|
|
|
{'name': 'only.md', 'path': '/trunc/only.md', 'kind': 'file'},
|
|
|
|
|
|
|
|
],
|
|
|
|
|
|
|
|
'truncated': True,
|
|
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
contents = {
|
|
|
|
|
|
|
|
'/docs/a.md': b'alpha',
|
|
|
|
|
|
|
|
'/docs/b.txt': b'bravo',
|
|
|
|
|
|
|
|
'/docs/sub/deep.md': b'delta',
|
|
|
|
|
|
|
|
'/trunc/only.md': b'only',
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
raw_calls = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def handle(h):
|
|
|
|
|
|
|
|
parsed = m['url'].urlsplit(h.path)
|
|
|
|
|
|
|
|
if parsed.path == '/_/api/v1/path-picker':
|
|
|
|
|
|
|
|
qs = m['url'].parse_qs(parsed.query)
|
|
|
|
|
|
|
|
p = qs.get('path', ['/'])[0]
|
|
|
|
|
|
|
|
reply(h, 200, tree.get(p, {'entries': [], 'truncated': False}))
|
|
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
if parsed.path.startswith('/v/raw/path:'):
|
|
|
|
|
|
|
|
rpath = m['url'].unquote(parsed.path[len('/v/raw/path:'):])
|
|
|
|
|
|
|
|
raw_calls.append(rpath)
|
|
|
|
|
|
|
|
body = contents.get(rpath)
|
|
|
|
|
|
|
|
if body is None:
|
|
|
|
|
|
|
|
reply(h, 404, {'error': 'not_found'})
|
|
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
digest = hashlib.sha256(body).hexdigest()
|
|
|
|
|
|
|
|
h.send_response(200)
|
|
|
|
|
|
|
|
h.send_header('Content-Type', 'text/plain; charset=utf-8')
|
|
|
|
|
|
|
|
h.send_header('Content-Length', str(len(body)))
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Revision-UUID', 'rev-' + rpath.rsplit('/', 1)[-1])
|
|
|
|
|
|
|
|
h.send_header('X-PagesWiki-Document-SHA256', digest)
|
|
|
|
|
|
|
|
h.end_headers()
|
|
|
|
|
|
|
|
h.wfile.write(body)
|
|
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
reply(h, 404, {'error': 'unknown'})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with server(handle) as base, tempfile.TemporaryDirectory() as root:
|
|
|
|
|
|
|
|
client = Client(base)
|
|
|
|
|
|
|
|
profile = Profile('mget', root)
|
|
|
|
|
|
|
|
profile.data = {'cwd': '/'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --dry-run makes zero /v/raw calls and creates no directory.
|
|
|
|
|
|
|
|
dry_dir = Path(root) / 'dry-out'
|
|
|
|
|
|
|
|
with contextlib.redirect_stdout(io.StringIO()) as out:
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mget', '/docs/*.md', str(dry_dir), '--dry-run'])
|
|
|
|
|
|
|
|
self.assertIn('DRY-RUN\t/docs/a.md', out.getvalue())
|
|
|
|
|
|
|
|
self.assertNotIn('/docs/b.txt', out.getvalue())
|
|
|
|
|
|
|
|
self.assertEqual(raw_calls, [])
|
|
|
|
|
|
|
|
self.assertFalse(dry_dir.exists())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Non-recursive glob downloads matching files only with 0600 permissions.
|
|
|
|
|
|
|
|
out_dir = Path(root) / 'out'
|
|
|
|
|
|
|
|
with contextlib.redirect_stdout(io.StringIO()) as out:
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mget', '/docs/*.md', str(out_dir)])
|
|
|
|
|
|
|
|
self.assertEqual((out_dir / 'a.md').read_bytes(), b'alpha')
|
|
|
|
|
|
|
|
self.assertEqual(stat.S_IMODE((out_dir / 'a.md').stat().st_mode), 0o600)
|
|
|
|
|
|
|
|
self.assertFalse((out_dir / 'b.txt').exists())
|
|
|
|
|
|
|
|
self.assertFalse((out_dir / 'sub').exists())
|
|
|
|
|
|
|
|
self.assertIn('1 downloaded, 0 failed', out.getvalue())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Recursive mget preserves subdirectories and enforces no-clobber on existing files.
|
|
|
|
|
|
|
|
(out_dir / 'a.md').write_bytes(b'existing-protected')
|
|
|
|
|
|
|
|
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err:
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, '1 failure'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mget', '/docs', str(out_dir), '--recursive'])
|
|
|
|
|
|
|
|
self.assertEqual((out_dir / 'a.md').read_bytes(), b'existing-protected')
|
|
|
|
|
|
|
|
self.assertEqual((out_dir / 'b.txt').read_bytes(), b'bravo')
|
|
|
|
|
|
|
|
self.assertEqual((out_dir / 'sub/deep.md').read_bytes(), b'delta')
|
|
|
|
|
|
|
|
self.assertEqual(stat.S_IMODE((out_dir / 'sub').stat().st_mode), 0o700)
|
|
|
|
|
|
|
|
self.assertIn('no-clobber', err.getvalue())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Truncated listing emits warning on stderr.
|
|
|
|
|
|
|
|
trunc_dir = Path(root) / 'trunc-out'
|
|
|
|
|
|
|
|
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err:
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mget', '/trunc', str(trunc_dir)])
|
|
|
|
|
|
|
|
self.assertIn('WARNING:', err.getvalue())
|
|
|
|
|
|
|
|
self.assertEqual((trunc_dir / 'only.md').read_bytes(), b'only')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Traversal entry name is rejected before any download.
|
|
|
|
|
|
|
|
raw_calls.clear()
|
|
|
|
|
|
|
|
evil_dir = Path(root) / 'evil-out'
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'Unsafe remote entry'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mget', '/evil/*', str(evil_dir)])
|
|
|
|
|
|
|
|
self.assertEqual(raw_calls, [])
|
|
|
|
|
|
|
|
self.assertFalse((Path(root) / 'escape').exists())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_mput_local_glob_create_only_conflict_dry_run_and_guards(self):
|
|
|
|
|
|
|
|
with tempfile.TemporaryDirectory() as root:
|
|
|
|
|
|
|
|
notes = Path(root) / 'notes'
|
|
|
|
|
|
|
|
sub = notes / 'sub'
|
|
|
|
|
|
|
|
sub.mkdir(parents=True)
|
|
|
|
|
|
|
|
(notes / 'a.md').write_text('# Alpha\n', encoding='utf-8')
|
|
|
|
|
|
|
|
(notes / 'readme.txt').write_text('plain text\n', encoding='utf-8')
|
|
|
|
|
|
|
|
(sub / 'b.md').write_text('# Sub Beta\n', encoding='utf-8')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
client = Client('https://example.test', 'token', 'auto')
|
|
|
|
|
|
|
|
profile = Profile('mput', root)
|
|
|
|
|
|
|
|
profile.data = {'cwd': '/'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --dry-run lists planned creates without network calls.
|
|
|
|
|
|
|
|
with patch.object(client, 'create_page') as create_mock, \
|
|
|
|
|
|
|
|
contextlib.redirect_stdout(io.StringIO()) as out, \
|
|
|
|
|
|
|
|
contextlib.redirect_stderr(io.StringIO()) as err:
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mput', str(notes / '*.md'), str(notes / '*.txt'), '/docs', '--strip-ext', '--dry-run'])
|
|
|
|
|
|
|
|
create_mock.assert_not_called()
|
|
|
|
|
|
|
|
self.assertIn('WARNING:', err.getvalue())
|
|
|
|
|
|
|
|
self.assertIn('->\t/docs/a\t(markdown, lang=und', out.getvalue())
|
|
|
|
|
|
|
|
self.assertIn('->\t/docs/readme\t(raw, lang=und', out.getvalue())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Local glob upload creates matching pages via create_page (create-only CAS) with und warning.
|
|
|
|
|
|
|
|
with patch.object(client, 'create_page', return_value={'revision_uuid': 'rev-1'}) as create_mock, \
|
|
|
|
|
|
|
|
contextlib.redirect_stdout(io.StringIO()) as out, \
|
|
|
|
|
|
|
|
contextlib.redirect_stderr(io.StringIO()) as err:
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mput', str(notes / '*.md'), '/docs'])
|
|
|
|
|
|
|
|
self.assertIn('WARNING:', err.getvalue())
|
|
|
|
|
|
|
|
create_mock.assert_called_once_with('path:/docs/a.md', '# Alpha\n', True, lang='und', filename='a.md')
|
|
|
|
|
|
|
|
self.assertIn('1 created, 0 failed', out.getvalue())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Recursive directory + --strip-ext + explicit --lang ja suppresses warning and maps subdirs.
|
|
|
|
|
|
|
|
with patch.object(client, 'create_page', return_value={'revision_uuid': 'rev-2'}) as create_mock, \
|
|
|
|
|
|
|
|
contextlib.redirect_stdout(io.StringIO()) as out, \
|
|
|
|
|
|
|
|
contextlib.redirect_stderr(io.StringIO()) as err:
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mput', str(notes), '/wiki', '--recursive', '--strip-ext', '--lang', 'ja'])
|
|
|
|
|
|
|
|
self.assertEqual(err.getvalue(), '')
|
|
|
|
|
|
|
|
called_addrs = [c.args[0] for c in create_mock.call_args_list]
|
|
|
|
|
|
|
|
self.assertEqual(called_addrs, ['path:/wiki/a', 'path:/wiki/readme', 'path:/wiki/sub/b'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 412 conflict on one target reports FAIL, continues others, and raises summary Failure.
|
|
|
|
|
|
|
|
with patch.object(client, 'create_page', side_effect=[Failure('Exists', 412), {'revision_uuid': 'rev-3'}, {'revision_uuid': 'rev-4'}]) as create_mock, \
|
|
|
|
|
|
|
|
contextlib.redirect_stdout(io.StringIO()) as out, \
|
|
|
|
|
|
|
|
contextlib.redirect_stderr(io.StringIO()) as err:
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, '1 failure'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mput', str(notes), '/wiki', '--recursive', '--lang', 'ja'])
|
|
|
|
|
|
|
|
self.assertEqual(create_mock.call_count, 3)
|
|
|
|
|
|
|
|
self.assertIn('FAIL\t', err.getvalue())
|
|
|
|
|
|
|
|
self.assertIn('2 created, 1 failed', out.getvalue())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 405 unsupported server stops immediately on first request.
|
|
|
|
|
|
|
|
with patch.object(client, 'create_page', side_effect=Failure('Unavailable', 405)) as create_mock, \
|
|
|
|
|
|
|
|
contextlib.redirect_stdout(io.StringIO()):
|
|
|
|
|
|
|
|
with self.assertRaises(Failure) as caught:
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mput', str(notes), '/wiki', '--recursive', '--lang', 'ja'])
|
|
|
|
|
|
|
|
self.assertEqual(caught.exception.status, 405)
|
|
|
|
|
|
|
|
self.assertEqual(create_mock.call_count, 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Guards reject duplicate target paths, symlinks, binary files, and >1 MiB files before any HTTP call.
|
|
|
|
|
|
|
|
dup_dir = Path(root) / 'dup'
|
|
|
|
|
|
|
|
dup_dir.mkdir()
|
|
|
|
|
|
|
|
(dup_dir / 'same.md').write_text('a', encoding='utf-8')
|
|
|
|
|
|
|
|
(dup_dir / 'same.txt').write_text('b', encoding='utf-8')
|
|
|
|
|
|
|
|
with patch.object(client, 'create_page') as create_mock:
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'Duplicate target remote Path'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mput', str(dup_dir), '/wiki', '--recursive', '--strip-ext', '--lang', 'ja'])
|
|
|
|
|
|
|
|
link_file = Path(root) / 'link.md'
|
|
|
|
|
|
|
|
link_file.symlink_to(notes / 'a.md')
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'symlink'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mput', str(link_file), '/wiki', '--lang', 'ja'])
|
|
|
|
|
|
|
|
bin_file = Path(root) / 'bin.dat'
|
|
|
|
|
|
|
|
bin_file.write_bytes(b'\xff\xfe\x00\x01')
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'Binary or non-UTF-8'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mput', str(bin_file), '/wiki', '--lang', 'ja'])
|
|
|
|
|
|
|
|
big_file = Path(root) / 'big.md'
|
|
|
|
|
|
|
|
big_file.write_bytes(b'x' * ((1 << 20) + 1))
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, '1 MiB client limit'):
|
|
|
|
|
|
|
|
m['execute'](client, profile, ['mput', str(big_file), '/wiki', '--lang', 'ja'])
|
|
|
|
|
|
|
|
create_mock.assert_not_called()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_shell_completions_quotes_mid_cursor_and_commands(self):
|
|
|
|
|
|
|
|
client = Client('https://example.test', 'token')
|
|
|
|
|
|
|
|
def fake_listing(path, prefix=''):
|
|
|
|
|
|
|
|
data = {
|
|
|
|
|
|
|
|
'/': [
|
|
|
|
|
|
|
|
{'name': 'my folder', 'path': '/my folder', 'kind': 'folder'},
|
|
|
|
|
|
|
|
{'name': 'my doc', 'path': '/my doc', 'kind': 'file'},
|
|
|
|
|
|
|
|
{'name': 'docs', 'path': '/docs', 'kind': 'folder'},
|
|
|
|
|
|
|
|
{'name': 'bad\x1bctrl', 'path': '/bad\x1bctrl', 'kind': 'file'},
|
|
|
|
|
|
|
|
],
|
|
|
|
|
|
|
|
'/docs': [
|
|
|
|
|
|
|
|
{'name': 'guide', 'path': '/docs/guide', 'kind': 'file'},
|
|
|
|
|
|
|
|
{'name': 'sub dir', 'path': '/docs/sub dir', 'kind': 'folder'},
|
|
|
|
|
|
|
|
],
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
entries = [e for e in data.get(path, []) if e['name'].startswith(prefix)]
|
|
|
|
|
|
|
|
return {'entries': entries}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with patch.object(client, 'listing', side_effect=fake_listing):
|
|
|
|
|
|
|
|
self.assertEqual(m['shell_completions'](client, '/', 'ed'), ['edit'])
|
|
|
|
|
|
|
|
self.assertEqual(m['shell_completions'](client, '/', 'm'), ['mget', 'mput'])
|
|
|
|
|
|
|
|
self.assertEqual(m['shell_completions'](client, '/', 'task pr'), ['task preferences', 'task project-add', 'task projects'])
|
|
|
|
|
|
|
|
self.assertEqual(m['shell_completions'](client, '/', 'cd "my fol'), ['cd "my folder/'])
|
|
|
|
|
|
|
|
self.assertEqual(m['shell_completions'](client, '/', "edit 'my d"), ["edit 'my doc'"])
|
|
|
|
|
|
|
|
unquoted = m['shell_completions'](client, '/', 'cat my')
|
|
|
|
|
|
|
|
self.assertEqual(unquoted, ["cat 'my folder/'", "cat 'my doc'"])
|
|
|
|
|
|
|
|
self.assertEqual(m['shell_completions'](client, '/', 'edit docs/gu'), ['edit docs/guide'])
|
|
|
|
|
|
|
|
self.assertEqual(m['shell_completions'](client, '/docs', 'ls sub'), ["ls 'sub dir/'"])
|
|
|
|
|
|
|
|
self.assertEqual(m['shell_completions'](client, '/', 'edit --l'), [])
|
|
|
|
|
|
|
|
self.assertEqual(m['shell_completions'](client, '/', 'cat uuid:123'), [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_fuzzy_pick_ctrl_p_and_opt_in_history(self):
|
|
|
|
|
|
|
|
client = Client('https://example.test', 'token')
|
|
|
|
|
|
|
|
suggest_items = [
|
|
|
|
|
|
|
|
{'path': '/docs/guide', 'label': 'User Guide', 'kind': 'page'},
|
|
|
|
|
|
|
|
{'path': '/notes/design', 'label': 'Architecture', 'kind': 'page'},
|
|
|
|
|
|
|
|
{'path': '/evil\x07path', 'label': 'Evil', 'kind': 'page'},
|
|
|
|
|
|
|
|
]
|
|
|
|
|
|
|
|
listing_items = [
|
|
|
|
|
|
|
|
{'name': 'local-note', 'path': '/local-note', 'kind': 'file'},
|
|
|
|
|
|
|
|
]
|
|
|
|
|
|
|
|
def fake_json(route, **kwargs):
|
|
|
|
|
|
|
|
self.assertTrue(route.startswith('/_/api/v1/search/suggest?'))
|
|
|
|
|
|
|
|
return {'items': suggest_items}
|
|
|
|
|
|
|
|
with patch.object(client, 'json', side_effect=fake_json), \
|
|
|
|
|
|
|
|
patch.object(client, 'listing', return_value={'entries': listing_items}):
|
|
|
|
|
|
|
|
cands = m['_gather_pick_candidates'](client, '/', 'dg')
|
|
|
|
|
|
|
|
paths = [c['path'] for c in cands]
|
|
|
|
|
|
|
|
self.assertEqual(paths[0], '/docs/guide')
|
|
|
|
|
|
|
|
self.assertNotIn('/evil\x07path', paths)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
profile = type('P', (), {'name': 'test', 'data': {'cwd': '/', 'expires': time.time() + 600}})()
|
|
|
|
|
|
|
|
fake_tty = type('TTY', (), {'isatty': lambda self: True})()
|
|
|
|
|
|
|
|
with patch.object(m['sys'], 'stdin', fake_tty), \
|
|
|
|
|
|
|
|
patch.object(client, 'json', return_value={'items': suggest_items}), \
|
|
|
|
|
|
|
|
patch.object(client, 'listing', return_value={'entries': listing_items}):
|
|
|
|
|
|
|
|
with patch('builtins.input', side_effect=['1']), contextlib.redirect_stdout(io.StringIO()):
|
|
|
|
|
|
|
|
res = m['fuzzy_pick'](client, profile, initial_query='dg', initial_line='edit ')
|
|
|
|
|
|
|
|
self.assertEqual(res, 'edit /docs/guide')
|
|
|
|
|
|
|
|
with patch('builtins.input', side_effect=['dg', '1', 'c']), \
|
|
|
|
|
|
|
|
patch.dict(m['fuzzy_pick'].__globals__, {'execute': lambda c, p, w: p.data.__setitem__('cwd', w[1])}), \
|
|
|
|
|
|
|
|
contextlib.redirect_stdout(io.StringIO()):
|
|
|
|
|
|
|
|
res2 = m['fuzzy_pick'](client, profile)
|
|
|
|
|
|
|
|
self.assertIsNone(res2)
|
|
|
|
|
|
|
|
self.assertEqual(profile.data['cwd'], '/docs/guide')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with patch.object(m['sys'], 'stdin', io.StringIO('')):
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, 'requires a TTY'):
|
|
|
|
|
|
|
|
m['fuzzy_pick'](client, profile)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class FakeReadline:
|
|
|
|
|
|
|
|
def __init__(self, items=None):
|
|
|
|
|
|
|
|
self.items = list(items or [])
|
|
|
|
|
|
|
|
self.delims = ''
|
|
|
|
|
|
|
|
def set_history_length(self, n): pass
|
|
|
|
|
|
|
|
def set_completer_delims(self, d): self.delims = d
|
|
|
|
|
|
|
|
def set_completer(self, fn): pass
|
|
|
|
|
|
|
|
def parse_and_bind(self, s): pass
|
|
|
|
|
|
|
|
def set_completion_display_matches_hook(self, fn): pass
|
|
|
|
|
|
|
|
def set_pre_input_hook(self, fn): pass
|
|
|
|
|
|
|
|
def get_current_history_length(self): return len(self.items)
|
|
|
|
|
|
|
|
def get_history_item(self, i): return self.items[i - 1]
|
|
|
|
|
|
|
|
def add_history(self, s): self.items.append(s)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with tempfile.TemporaryDirectory() as root:
|
|
|
|
|
|
|
|
fake_rl = FakeReadline()
|
|
|
|
|
|
|
|
with patch.dict('sys.modules', {'readline': fake_rl}), \
|
|
|
|
|
|
|
|
patch('builtins.input', side_effect=['pwd', 'exit']), \
|
|
|
|
|
|
|
|
contextlib.redirect_stdout(io.StringIO()):
|
|
|
|
|
|
|
|
m['shell'](client, profile, persist_history=False, history_root=root)
|
|
|
|
|
|
|
|
self.assertFalse((Path(root) / 'pages-cli/history').exists())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fake_rl2 = FakeReadline(['ls /docs', 'login', 'cat /a Bearer secret', 'pwd', 'edit pw_api_123'])
|
|
|
|
|
|
|
|
with patch.dict('sys.modules', {'readline': fake_rl2}), \
|
|
|
|
|
|
|
|
patch('builtins.input', side_effect=['\x1fedit dg', 'exit']), \
|
|
|
|
|
|
|
|
patch.dict(m['shell'].__globals__, {'fuzzy_pick': lambda c, p, initial_query='', initial_line='': initial_line + '/docs/guide'}), \
|
|
|
|
|
|
|
|
contextlib.redirect_stdout(io.StringIO()):
|
|
|
|
|
|
|
|
m['shell'](client, profile, persist_history=True, history_root=root)
|
|
|
|
|
|
|
|
hist_file = Path(root) / 'pages-cli/history/test.history'
|
|
|
|
|
|
|
|
self.assertTrue(hist_file.exists())
|
|
|
|
|
|
|
|
self.assertEqual(stat.S_IMODE(hist_file.parent.stat().st_mode), 0o700)
|
|
|
|
|
|
|
|
self.assertEqual(stat.S_IMODE(hist_file.stat().st_mode), 0o600)
|
|
|
|
|
|
|
|
saved_lines = hist_file.read_text(encoding='utf-8').splitlines()
|
|
|
|
|
|
|
|
self.assertEqual(saved_lines, ['ls /docs', 'pwd'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
loader_rl = FakeReadline()
|
|
|
|
|
|
|
|
m['_load_shell_history'](loader_rl, hist_file)
|
|
|
|
|
|
|
|
self.assertEqual(loader_rl.items, ['ls /docs', 'pwd'])
|
|
|
|
|
|
|
|
hist_file.chmod(0o644)
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(Failure, '0600'):
|
|
|
|
|
|
|
|
m['_load_shell_history'](FakeReadline(), hist_file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def oidc_integration():
|
|
|
|
def oidc_integration():
|
|
|
|
fixture=json.load(sys.stdin)
|
|
|
|
fixture=json.load(sys.stdin)
|
|
|
|