import contextlib import base64 from email.message import Message import hashlib import io import json import os from pathlib import Path import runpy import stat import sys import tempfile import threading import time import unittest from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest.mock import patch m = runpy.run_path(str(Path(__file__).with_name('pages'))) Client, Failure, Profile = m['Client'], m['Failure'], m['Profile'] @contextlib.contextmanager def server(callback): class Handler(BaseHTTPRequestHandler): def do_GET(self): callback(self) def do_POST(self): callback(self) def do_PUT(self): callback(self) def log_message(self, *args): pass instance = ThreadingHTTPServer(('127.0.0.1', 0), Handler) thread = threading.Thread(target=instance.serve_forever, daemon=True) thread.start() try: yield 'http://127.0.0.1:%d' % instance.server_port finally: instance.shutdown(); instance.server_close(); thread.join() def reply(h, status, body, mime='application/json'): raw = json.dumps(body).encode() if isinstance(body, dict) else body h.send_response(status); h.send_header('Content-Type', mime); h.end_headers(); h.wfile.write(raw) class RemoteTests(unittest.TestCase): def test_oidc_polling_pkce_and_no_secret_output(self): now = [0] waits, calls = [], [] started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43, 'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5} client = Client('https://wiki.example') def sleep(seconds): waits.append(seconds); now[0] += seconds def request(route, **kwargs): calls.append((route, kwargs)) if route.endswith('/start'): return started polls = len(calls)-1 if polls == 1: raise Failure('pending',400,{'error':'authorization_pending'}) if polls == 2: raise Failure('slow',400,{'error':'slow_down'}) return {'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'anya'} with patch.object(client,'json',side_effect=request), patch.object(m['webbrowser'],'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out: expires, name = client.login_oidc(sleep=sleep,clock=lambda:now[0]) self.assertEqual(name,'anya'); self.assertGreater(expires,time.time()) self.assertEqual(waits,[5,5,10]); browser.assert_not_called() proof = calls[1][1]['form']['code_verifier'] expected=base64.urlsafe_b64encode(hashlib.sha256(proof.encode()).digest()).decode().rstrip('=') self.assertEqual(calls[0][1]['form']['code_challenge'],expected) self.assertNotIn(proof,out.getvalue()); self.assertNotIn(started['device_code'],out.getvalue()); self.assertNotIn(client.token,out.getvalue()) self.assertIn('ABCD-1234',out.getvalue()) def test_oidc_unavailable_server_explained_without_retry(self): for status in (404, 405, 501): with self.subTest(status=status): client = Client('https://wiki.example') with patch.object(client, 'json', side_effect=Failure('Not found or not readable.', status)) as api, patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out: with self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught: client.login_oidc(open_browser=True) self.assertEqual(caught.exception.status, status) api.assert_called_once() browser.assert_not_called() self.assertEqual(out.getvalue(), '') self.assertEqual(client.token, '') def test_oidc_disabled_and_other_start_errors(self): client = Client('https://wiki.example') with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})): with self.assertRaisesRegex(Failure, 'not enabled for this domain'): client.login_oidc() for error in (Failure('Connection/TLS failure.'), Failure('Access denied.', 403), Failure('Unavailable.', 503)): with patch.object(client, 'json', side_effect=error) as api: with self.assertRaises(Failure) as caught: client.login_oidc() self.assertIs(caught.exception, error) api.assert_called_once() def test_oidc_rejects_external_url_and_wrong_account(self): client=Client('https://wiki.example') started={'device_code':'D'*43,'verification_uri':'https://evil.example/','user_code':'ABCD-1234','expires_in':300,'interval':5} with patch.object(client,'json',return_value=started),patch.object(m['webbrowser'],'open') as browser: with self.assertRaises(Failure): client.login_oidc(open_browser=True) browser.assert_not_called() started['verification_uri']='/_/auth/cli/verify?request='+'R'*43 token={'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'other'} with patch.object(client,'json',side_effect=[started,token,{}]) as api, contextlib.redirect_stdout(io.StringIO()): with self.assertRaises(Failure): client.login_oidc(expected_username='anya',sleep=lambda _:None,clock=lambda:0) self.assertEqual(api.call_args.args[0],'/_/auth/logout') self.assertEqual(client.token,'') def test_oidc_cancellation_denial_and_ambiguous_exchange(self): started={'device_code':'D'*43,'verification_uri':'/_/auth/cli/verify?request='+'R'*43,'user_code':'ABCD-1234','expires_in':300,'interval':5} for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]: client=Client('https://wiki.example') with patch.object(client,'json',side_effect=[started,error]) as api,contextlib.redirect_stdout(io.StringIO()): with self.assertRaises(Failure): client.login_oidc(sleep=lambda _:None,clock=lambda:0) self.assertEqual(api.call_count,2) client=Client('https://wiki.example') with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()): def interrupt(_): raise KeyboardInterrupt() with self.assertRaises(KeyboardInterrupt): client.login_oidc(sleep=interrupt,clock=lambda:0) self.assertEqual(api.call_count,1) def test_oidc_main_without_configured_username(self): with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}): self.configure(None,'--origin','https://wiki.example') calls=[] def login(client,*args,**kwargs): calls.append((args,kwargs)) client.token='pw_api_'+'s'*43; return time.time()+600,'anya' with patch.object(Client,'login_oidc',login),contextlib.redirect_stdout(io.StringIO()): m['main'](['login','--oidc']) m['main'](['status']) self.configure(None,'--lang','ja') self.assertIs(calls[-1][0][0],False) with Profile('default').locked() as profile: self.assertEqual(profile.data['username'],'anya') self.assertEqual(profile.data['configured_username'],'') with self.assertRaises(Failure): self.configure(None,'--username','other') def test_oidc_browser_opening_is_opt_in(self): started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43, 'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5} result = {'access_token': 'pw_api_'+'S'*43, 'token_type': 'Bearer', 'expires_in': 3600, 'username': 'anya'} client = Client('https://wiki.example') with patch.object(client, 'json', side_effect=[started, result]), patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()): client.login_oidc(sleep=lambda _: None, clock=lambda: 0) browser.assert_not_called() client = Client('https://wiki.example') with patch.object(client, 'json', side_effect=[started, result]), patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()): client.login_oidc(open_browser=True, sleep=lambda _: None, clock=lambda: 0) browser.assert_called_once_with('https://wiki.example/_/auth/cli/verify?request='+'R'*43, new=2) with tempfile.TemporaryDirectory() as root, patch.dict(os.environ, {'XDG_CONFIG_HOME': root}): self.configure(None, '--origin', 'https://wiki.example') calls = [] def login(client_arg, *args, **kwargs): calls.append((args, kwargs)) client_arg.token = 'pw_api_'+'s'*43 return time.time()+600, 'anya' with patch.object(Client, 'login_oidc', login), contextlib.redirect_stdout(io.StringIO()): m['main'](['login', '--oidc', '--with-open-browser']) self.assertIs(calls[-1][0][0], True) with patch.object(Client, 'login_oidc') as login_mock, contextlib.redirect_stderr(io.StringIO()): for bad_args in (['login', '--with-open-browser'], ['login', '--oidc', '--no-browser']): with self.assertRaises(SystemExit) as exited: m['main'](bad_args) self.assertNotEqual(exited.exception.code, 0) login_mock.assert_not_called() def configure(self, root, *args): with contextlib.redirect_stdout(io.StringIO()) as output: m['configure'](list(args), root) return output.getvalue() def test_configuration_defaults_and_switch(self): with tempfile.TemporaryDirectory() as root: self.configure(root,'--origin','https://one.example','--username','anya') self.configure(root,'set','--profile','work','--origin','https://two.example','--username','worker','--lang','ja') self.configure(root,'use','work') settings=json.loads(self.configure(root,'show')) self.assertEqual(settings['default_profile'],'work') self.assertEqual(settings['profiles']['default']['lang'],'auto') self.assertEqual(settings['profiles']['work']['lang'],'ja') self.configure(root,'--lang','en-US') settings=json.loads(self.configure(root,'show')) self.assertEqual(settings['profiles']['work']['lang'],'en-US') self.configure(root,'--lang','und') settings=json.loads(self.configure(root,'show')) self.assertEqual(settings['profiles']['work']['lang'],'und') with m['Configuration'](root).locked() as cfg: self.assertEqual(stat.S_IMODE(cfg.path.stat().st_mode),0o600) with self.assertRaises(Failure): self.configure(root,'use','missing') with self.assertRaises(Failure): self.configure(root,'--lang','ja_JP') def test_active_credentials_cannot_be_retargeted_or_shown(self): with tempfile.TemporaryDirectory() as root: self.configure(root,'--origin','https://one.example','--username','anya') with Profile('default',root).locked() as profile: profile.data={'origin':'https://one.example','username':'anya','token':'private-token'}; profile.save() for args in [('--origin','https://other.example'),('--username','other')]: with self.assertRaises(Failure): self.configure(root,*args) self.assertNotIn('private-token',self.configure(root,'show')) self.assertNotIn('private-token',self.configure(root,'list')) self.configure(root,'--lang','ja') with Profile('default',root).locked(): with self.assertRaises(Failure): self.configure(root,'--lang','en') with Profile('default',root).locked() as profile: profile.data.pop('token'); profile.save() self.configure(root,'--origin','https://other.example') def test_main_uses_saved_defaults_and_rejects_manual_retarget(self): with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}): self.configure(root,'set','--profile','work','--origin','https://work.example','--username','worker','--lang','ja') with Profile('work',root).locked() as profile: profile.data={'origin':'https://work.example','username':'worker','token':'session-token','expires':time.time()+100,'cwd':'/notes'}; profile.save() # Patch the globals used by main rather than running a real request. globals=m['main'].__globals__ with patch.dict(globals,{'execute':lambda client,profile,args: self.assertEqual((client.base,client.lang,args),('https://work.example','ja',['ls']))}): m['main'](['ls']) with patch.dict(globals,{'execute':lambda client,profile,args: self.assertEqual(client.lang,'en')}): m['main'](['--lang','en','ls']) with m['Configuration'](root).locked() as cfg: cfg.data['profiles']['work']['origin']='https://evil.example'; cfg.save() with self.assertRaises(Failure): m['main'](['ls']) def test_bad_configuration_is_not_printed(self): with tempfile.TemporaryDirectory() as root: with m['Configuration'](root).locked() as cfg: cfg.data={'version':1,'default_profile':'default','profiles':{'default':{'origin':'https://example.test','token':'secret'}}}; cfg.save() with self.assertRaises(Failure): self.configure(root,'show') for invalid in [None,42,[],{}]: with self.assertRaises(Failure): m['profile_name'](invalid) with self.assertRaises(Failure): m['language'](invalid) with self.assertRaises(Failure): m['origin'](invalid) def test_origin_and_paths(self): for value in ['http://example.com', 'https://user:pass@example.com', 'https://example.com/a', 'https://example.com?token=x']: with self.assertRaises(Failure): m['origin'](value) self.assertEqual(m['address']('../日本語 #?%', '/docs/deep'), 'path:/docs/日本語 #?%') self.assertEqual(m['semantic']('../../..', '/'), '/') for value in ['https://evil.test', 'asset:x:y', 'rev:bad', '/bad\x1b[31m']: with self.assertRaises(Failure): m['address'](value) self.assertNotIn('\x1b', m['safe_text']('\x1b]52;clipboard\x07')) self.assertNotIn('\u202e', m['safe_text']('abc\u202e')) def test_redirect_never_receives_bearer(self): seen = [] with server(lambda h: (seen.append(h.headers.get('Authorization')), reply(h, 200, {}))) as sink: def redirect(h): h.send_response(302); h.send_header('Location', sink); h.end_headers() with server(redirect) as base: with self.assertRaises(Failure) as error: Client(base, 'secret').json('/test') self.assertEqual(error.exception.status, 302) self.assertEqual(seen, []) def test_protocol_failures_and_limits(self): for status, body, mime in [(200,b'login','text/html'), (200,b'not-json','application/json'), (403,b'private internal error','text/plain')]: with server(lambda h: reply(h,status,body,mime)) as base: with self.assertRaises(Failure) as error: Client(base).json('/test') self.assertNotIn('private internal', str(error.exception)) with server(lambda h: reply(h,200,b'x'*100)) as base: with self.assertRaises(Failure): Client(base).request('/large',limit=10) def test_password_totp_contract(self): requests = [] def handle(h): requests.append((h.path, h.rfile.read(int(h.headers['Content-Length'])).decode())) if h.path.endswith('/login'): reply(h,401,{'mfa_required':True,'challenge_token':'short-lived'}) else: reply(h,200,{'access_token':'a'*32,'token_type':'Bearer','expires_in':3600}) with server(handle) as base: client = Client(base) client.login('someone','secret',lambda prompt:'123456') self.assertEqual(client.token,'a'*32) self.assertIn('challenge_token=short-lived',requests[1][1]) self.assertNotIn('password',requests[1][1]) def test_private_profile_lock_and_symlinks(self): with tempfile.TemporaryDirectory() as root: with Profile('work',root).locked() as profile: profile.data={'token':'secret'}; profile.save() self.assertEqual(stat.S_IMODE(profile.path.stat().st_mode),0o600) self.assertEqual(stat.S_IMODE(profile.root.stat().st_mode),0o700) with self.assertRaises(Failure): with Profile('work',root).locked(): pass with Profile('work',root).locked() as loaded: self.assertEqual(loaded.data['token'],'secret') profile.path.chmod(0o644) with self.assertRaises(Failure): with Profile('work',root).locked(): pass profile.path.unlink(); profile.path.symlink_to(Path(root)/'missing') with self.assertRaises(Failure): with Profile('work',root).locked(): pass def test_cas_and_authoring_contract(self): state={'object_uuid':'object','head_revision_uuid':'base','principal_uuid':'person','lang':'ja', 'content_type':'text/html','filename':'a.html','body':'old'} client=Client('https://example.test') calls=[] def api(route, **kwargs): calls.append((route,kwargs['data'])) return {'html':'
new
'} if route.endswith('/markdown') else {'revision_uuid':'new'} with patch.object(client,'json',side_effect=api): client.save(state,'new',True) self.assertTrue(calls[0][1]['authoring']); self.assertFalse(calls[0][1]['projection']) self.assertEqual(calls[1][1]['base_revision_uuid'],'base') self.assertEqual(calls[1][1]['editor_principal_uuid'],'person') self.assertEqual(calls[1][1]['lang'],'ja') with patch.object(client,'json',side_effect=Failure('conflict',409)): with self.assertRaises(Failure): client.save(state,'new') def test_download_private_and_no_clobber(self): 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') state={'lang':'ja','head_revision_uuid':'current-ja','content_type':'text/plain','filename':'x.txt','body':'new','markdown':'new','editable':True,'principal_uuid':'owner'} headers={'X-PagesWiki-Object-UUID':'object','X-PagesWiki-Revision-UUID':'visible-ja'} with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[{'lang':'ja'},state]) as api: result=client.snapshot('path:/x') self.assertEqual(result['lang'],'ja') self.assertEqual(result['head_revision_uuid'],'current-ja') self.assertIn('revision=visible-ja',api.call_args_list[0].args[0]) self.assertIn('lang=ja',api.call_args_list[1].args[0]) self.assertNotIn('revision=',api.call_args_list[1].args[0]) def test_fork_uses_empty_base_and_preserves_source(self): client=Client('https://example.test','token','en') target={'lang':'en','head_revision_uuid':'','content_type':'text/html','filename':'','body':'','markdown':'','editable':True,'principal_uuid':'owner'} source=dict(target,lang='ja',body='' + req['markdown'].strip() + '
'}) return if mode['status'] != 201: reply(h, mode['status'], {'error': 'rejected'}) return digest = hashlib.sha256(body).hexdigest() headers = { 'Content-Type': 'application/json; charset=utf-8', 'Location': '/o/uuid:00000000-0000-4000-8000-000000000001', 'ETag': '"' + digest + '"', 'Content-Language': h.headers.get('Content-Language', 'und'), 'X-PagesWiki-Object-UUID': '00000000-0000-4000-8000-000000000001', 'X-PagesWiki-Revision-UUID': '00000000-0000-4000-8000-000000000002', 'X-PagesWiki-Document-SHA256': digest, } if mode['headers'] is not None: headers = mode['headers'](digest) h.send_response(201) for k, v in headers.items(): h.send_header(k, v) h.end_headers() with server(handle) as base: client = Client(base, 'secret-token', 'auto') created = client.create_page('path:/docs/新規 ガイド', '# Title\n', markdown=True) self.assertEqual(created['path'], '/docs/新規 ガイド') self.assertEqual(created['lang'], 'und') self.assertEqual(created['object_uuid'], '00000000-0000-4000-8000-000000000001') self.assertEqual(created['revision_uuid'], '00000000-0000-4000-8000-000000000002') self.assertEqual(recorded[0][0], 'POST') self.assertEqual(recorded[0][1], '/_/api/v1/render/markdown') method, path, hdrs, raw = recorded[1] self.assertEqual(method, 'PUT') self.assertEqual(path, '/_/api/v1/pages/path:/docs/%E6%96%B0%E8%A6%8F%20%E3%82%AC%E3%82%A4%E3%83%89') self.assertEqual(hdrs.get('Authorization'), 'Bearer secret-token') self.assertEqual(hdrs.get('If-None-Match'), '*') self.assertEqual(hdrs.get('Content-Language'), 'und') self.assertEqual(hdrs.get('Content-Type'), 'text/html; charset=utf-8') self.assertEqual(hdrs.get('X-PagesWiki-Commit-Message'), 'Remote%20CLI%20create') self.assertEqual(raw, b'# Title
') recorded.clear() raw_created = client.create_page('path:/notes/memo.txt', 'hello', markdown=False, lang='ja', filename='メモ.txt') self.assertEqual(raw_created['lang'], 'ja') self.assertEqual(len(recorded), 1) self.assertEqual(recorded[0][0], 'PUT') self.assertEqual(recorded[0][2].get('Content-Type'), 'text/plain; charset=utf-8') self.assertEqual(recorded[0][2].get('Content-Language'), 'ja') self.assertEqual(recorded[0][2].get('X-PagesWiki-Filename'), '%E3%83%A1%E3%83%A2.txt') self.assertEqual(recorded[0][3], b'hello') before = len(recorded) for bad in ('path:/', 'uuid:00000000-0000-0000-0000-000000000000', 'rev:00000000-0000-0000-0000-000000000000'): with self.assertRaises(Failure): client.create_page(bad, 'x') with self.assertRaises(Failure): client.create_page('path:/too-big', 'a' * ((1 << 20) + 1)) self.assertEqual(len(recorded), before) mode['headers'] = lambda d: {'X-PagesWiki-Object-UUID': '00000000-0000-4000-8000-000000000001'} with self.assertRaisesRegex(Failure, 'missing document identity'): client.create_page('path:/bad-headers', 'x') mode['headers'] = None for status, pattern in ((200, 'Unexpected HTTP status'), (412, 'already exists'), (428, 'If-None-Match'), (404, 'unavailable'), (405, 'unavailable'), (501, 'unavailable'), (403, 'Access denied')): recorded.clear() mode['status'] = status with self.assertRaisesRegex(Failure, pattern) as caught: client.create_page('path:/err', 'x') self.assertEqual(caught.exception.status, status) self.assertEqual(len(recorded), 1) def test_editor_creates_new_page_with_confirmation_and_und_warning(self): client = Client('https://example.test', 'token', 'auto') with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \ patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: False}), \ patch.object(client, 'create_page') as create_mock, \ patch('subprocess.run') as run_mock, \ contextlib.redirect_stdout(io.StringIO()) as out: m['editor'](client, 'path:/docs/new', 'auto') self.assertIn('Aborted.', out.getvalue()) run_mock.assert_not_called() create_mock.assert_not_called() def edit_ok(args, **kwargs): Path(args[-1]).write_text('# Hello\n', encoding='utf-8') return type('R', (), {'returncode': 0})() with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \ patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \ patch.object(client, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-1', 'revision_uuid': 'rev-1'}) as create_mock, \ patch('subprocess.run', side_effect=edit_ok) as run_mock, \ contextlib.redirect_stdout(io.StringIO()) as out, \ contextlib.redirect_stderr(io.StringIO()) as err: m['editor'](client, 'path:/docs/new', 'auto') self.assertIn("WARNING: Creating a new page with language 'und'", err.getvalue()) self.assertIn('Created page: /docs/new', out.getvalue()) self.assertTrue(run_mock.call_args.args[0][-1].endswith('document.md')) self.assertFalse(Path(run_mock.call_args.args[0][-1]).exists()) create_mock.assert_called_once_with('path:/docs/new', '# Hello\n', True, lang='und') client_ja = Client('https://example.test', 'token', 'ja') with patch.object(client_ja, 'snapshot', side_effect=Failure('Not found', 404)), \ patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \ patch.object(client_ja, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-1', 'revision_uuid': 'rev-1'}) as create_mock, \ patch('subprocess.run', side_effect=edit_ok), \ contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()) as err: m['editor'](client_ja, 'path:/docs/new', 'raw') self.assertEqual(err.getvalue(), '') create_mock.assert_called_once_with('path:/docs/new', '# Hello\n', False, lang='ja') confirm_calls = [] def record_confirm(addr, status): confirm_calls.append((addr, status)) return True with patch.object(client_ja, 'snapshot', side_effect=Failure('Access denied', 403)), \ patch.dict(m['editor'].__globals__, {'confirm_create': record_confirm}), \ patch.object(client_ja, 'create_page', return_value={'path': '/docs/create-only', 'object_uuid': 'obj-2', 'revision_uuid': 'rev-2'}), \ patch('subprocess.run', side_effect=edit_ok), \ contextlib.redirect_stdout(io.StringIO()): m['editor'](client_ja, 'path:/docs/create-only', 'auto') self.assertEqual(confirm_calls, [('path:/docs/create-only', 403)]) for non_creatable in ('uuid:00000000-0000-0000-0000-000000000000', 'rev:00000000-0000-0000-0000-000000000000', 'path:/'): with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \ patch.dict(m['editor'].__globals__, {'confirm_create': lambda *_: self.fail('should not prompt')}): with self.assertRaises(Failure): m['editor'](client, non_creatable, 'auto') non_tty = io.StringIO('y\n') with patch.object(m['sys'], 'stdin', non_tty), \ patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)): with self.assertRaises(Failure) as caught: m['editor'](client, 'path:/docs/new', 'auto') self.assertEqual(caught.exception.status, 404) def test_editor_new_page_empty_aborts_and_failure_retains_private_recovery(self): client = Client('https://example.test', 'secret-token', 'auto') with tempfile.TemporaryDirectory() as root: directory = Path(root) / 'empty'; directory.mkdir(mode=0o700) with patch('tempfile.mkdtemp', return_value=str(directory)), \ patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \ patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \ patch.object(client, 'create_page') as create_mock, \ patch('subprocess.run', return_value=type('R', (), {'returncode': 0})()), \ contextlib.redirect_stdout(io.StringIO()) as out, \ contextlib.redirect_stderr(io.StringIO()): m['editor'](client, 'path:/docs/empty', 'auto') create_mock.assert_not_called() self.assertIn('was not created', out.getvalue()) self.assertFalse(directory.exists()) working = Path(root) / 'race'; working.mkdir(mode=0o700) def edit_write(args, **kwargs): Path(args[-1]).write_text('draft body', encoding='utf-8') return type('R', (), {'returncode': 0})() with patch('tempfile.mkdtemp', return_value=str(working)), \ patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \ patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \ patch.object(client, 'create_page', side_effect=Failure('Conflict', 412)), \ patch('subprocess.run', side_effect=edit_write), \ patch.object(m['sys'], 'stdin', io.StringIO('')), \ contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()) as err: with self.assertRaises(Failure) as caught: m['editor'](client, 'path:/docs/race', 'auto') self.assertEqual(caught.exception.status, 412) self.assertNotIn('secret-token', err.getvalue()) self.assertEqual((working / 'document.md').read_text(encoding='utf-8'), 'draft body') self.assertEqual(stat.S_IMODE((working / 'document.md').stat().st_mode), 0o600) recovery_text = (working / 'recovery.json').read_text(encoding='utf-8') self.assertNotIn('secret-token', recovery_text) recovery = json.loads(recovery_text) self.assertEqual(recovery['mode'], 'create') self.assertEqual(recovery['address'], 'path:/docs/race') self.assertEqual(recovery['lang'], 'und') self.assertEqual(recovery['format'], 'markdown') self.assertEqual(stat.S_IMODE((working / 'recovery.json').stat().st_mode), 0o600) def test_editor_409_interactive_edit_and_force_save(self): state = {'object_uuid': 'object', 'head_revision_uuid': 'base-rev', 'principal_uuid': 'person', 'lang': 'und', 'content_type': 'text/plain', 'filename': 'x.txt', 'body': 'base\n', 'markdown': 'base\n'} latest = {'object_uuid': 'object', 'head_revision_uuid': 'latest-rev', 'principal_uuid': 'person', 'lang': 'und', 'content_type': 'text/plain', 'filename': 'x.txt', 'body': 'remote line\n', 'markdown': 'remote line\n'} client = Client('https://example.test', 'token') with tempfile.TemporaryDirectory() as root: working = Path(root) / 'merge'; working.mkdir(mode=0o700) seen_buffers = [] call_count = [0] def run_ed(args, **kwargs): call_count[0] += 1 p = Path(args[-1]) if call_count[0] == 1: p.write_text('local line\n', encoding='utf-8') else: seen_buffers.append(p.read_text(encoding='utf-8')) p.write_text('merged line\n', encoding='utf-8') return type('R', (), {'returncode': 0})() with patch('tempfile.mkdtemp', return_value=str(working)), \ patch('subprocess.run', side_effect=run_ed), \ patch.object(client, 'snapshot', side_effect=[state, latest]), \ patch.object(client, 'save', side_effect=[Failure('conflict', 409), {'revision_uuid': 'merged-rev'}]) as save_mock, \ patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \ contextlib.redirect_stdout(io.StringIO()) as out: m['editor'](client, 'path:/x', 'auto') self.assertIn('<<<<<<< local\nlocal line\n=======\nremote line\n>>>>>>> remote (rev: latest-rev)\n', seen_buffers[0]) self.assertEqual(save_mock.call_args_list[1].args, (latest, 'merged line\n', False)) self.assertIn('Saved revision: merged-rev', out.getvalue()) self.assertFalse(working.exists()) markers = Path(root) / 'markers'; markers.mkdir(mode=0o700) call_count[0] = 0 def leave_markers(args, **kwargs): call_count[0] += 1 if call_count[0] == 1: Path(args[-1]).write_text('local line\n', encoding='utf-8') return type('R', (), {'returncode': 0})() with patch('tempfile.mkdtemp', return_value=str(markers)), \ patch('subprocess.run', side_effect=leave_markers), \ patch.object(client, 'snapshot', side_effect=[state, latest]), \ patch.object(client, 'save', side_effect=Failure('conflict', 409)) as save_mock, \ patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \ contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()) as err: with self.assertRaises(Failure) as caught: m['editor'](client, 'path:/x', 'auto') self.assertEqual(caught.exception.status, 409) self.assertEqual(save_mock.call_count, 1) self.assertIn('Conflict markers remain', err.getvalue()) self.assertTrue((markers / 'recovery.json').exists()) force_dir = Path(root) / 'force'; force_dir.mkdir(mode=0o700) def edit_local(args, **kwargs): Path(args[-1]).write_text('forced body\n', encoding='utf-8') return type('R', (), {'returncode': 0})() with patch('tempfile.mkdtemp', return_value=str(force_dir)), \ patch('subprocess.run', side_effect=edit_local) as run_mock, \ patch.object(client, 'snapshot', side_effect=[state, latest]), \ patch.object(client, 'save', side_effect=[Failure('conflict', 409), {'revision_uuid': 'forced-rev'}]) as save_mock, \ patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'f'}), \ contextlib.redirect_stdout(io.StringIO()) as out: m['editor'](client, 'path:/x', 'auto') self.assertEqual(run_mock.call_count, 1) self.assertEqual(save_mock.call_args_list[1].args, (latest, 'forced body\n', False)) self.assertIn('Saved revision: forced-rev', out.getvalue()) self.assertFalse(force_dir.exists()) def test_editor_412_interactive_pick_path_and_merge(self): client = Client('https://example.test', 'token', 'auto') with tempfile.TemporaryDirectory() as root: pick_dir = Path(root) / 'pick'; pick_dir.mkdir(mode=0o700) def edit_new(args, **kwargs): Path(args[-1]).write_text('# New Draft\n', encoding='utf-8') return type('R', (), {'returncode': 0})() with patch('tempfile.mkdtemp', return_value=str(pick_dir)), \ patch('subprocess.run', side_effect=edit_new), \ patch.object(client, 'snapshot', side_effect=[Failure('Not found', 404), Failure('Forbidden', 403)]), \ patch.object(client, 'create_page', side_effect=[Failure('Exists', 412), {'path': '/docs/alt', 'object_uuid': 'obj-2', 'revision_uuid': 'rev-2'}]) as create_mock, \ patch.dict(m['editor'].__globals__, { 'confirm_create': lambda addr, st: True, 'choose_conflict_action': lambda kind, has_remote=True: 'p', 'prompt_new_path': lambda cwd='/': 'path:/docs/alt', }), \ contextlib.redirect_stdout(io.StringIO()) as out, \ contextlib.redirect_stderr(io.StringIO()): m['editor'](client, 'path:/docs/orig', 'auto') self.assertEqual(create_mock.call_args_list[1].args[0], 'path:/docs/alt') self.assertIn('Created page: /docs/alt', out.getvalue()) self.assertFalse(pick_dir.exists()) merge_dir = Path(root) / 'merge-create'; merge_dir.mkdir(mode=0o700) existing = {'object_uuid': 'obj-existing', 'head_revision_uuid': 'rev-existing', 'principal_uuid': 'person', 'lang': 'ja', 'content_type': 'text/html', 'filename': '', 'body': 'Existing
', 'markdown': 'Existing\n'} call_count = [0] seen_buffers = [] def edit_merge(args, **kwargs): call_count[0] += 1 p = Path(args[-1]) if call_count[0] == 1: p.write_text('My new page\n', encoding='utf-8') else: seen_buffers.append(p.read_text(encoding='utf-8')) p.write_text('Combined page\n', encoding='utf-8') return type('R', (), {'returncode': 0})() with patch('tempfile.mkdtemp', return_value=str(merge_dir)), \ patch('subprocess.run', side_effect=edit_merge), \ patch.object(client, 'snapshot', side_effect=[Failure('Not found', 404), existing]), \ patch.object(client, 'create_page', side_effect=Failure('Exists', 412)), \ patch.object(client, 'save', return_value={'revision_uuid': 'rev-combined'}) as save_mock, \ patch.dict(m['editor'].__globals__, { 'confirm_create': lambda addr, st: True, 'choose_conflict_action': lambda kind, has_remote=True: 'e', }), \ contextlib.redirect_stdout(io.StringIO()) as out, \ contextlib.redirect_stderr(io.StringIO()): m['editor'](client, 'path:/docs/race', 'auto') self.assertIn('<<<<<<< local\nMy new page\n=======\nExisting\n>>>>>>> remote (rev: rev-existing)\n', seen_buffers[0]) save_mock.assert_called_once_with(existing, 'Combined page\n', True) self.assertIn('Saved revision: rev-combined', out.getvalue()) self.assertFalse(merge_dir.exists()) def test_recover_list_resume_conflict_discard_and_security(self): client = Client('https://example.test', 'token', 'auto') profile = type('P', (), {'data': {'cwd': '/notes'}})() def make_draft(base_dir, name, meta, doc_text, *, dir_mode=0o700, file_mode=0o600): d = Path(base_dir) / name d.mkdir(mode=0o700) doc_name = 'document.md' if meta['format'] == 'markdown' else 'document.txt' doc = d / doc_name doc.touch(mode=0o600); doc.write_text(doc_text, encoding='utf-8'); doc.chmod(file_mode) meta_file = d / 'recovery.json' meta_file.touch(mode=0o600); meta_file.write_text(json.dumps(meta), encoding='utf-8'); meta_file.chmod(file_mode) d.chmod(dir_mode) return d, doc, meta_file with tempfile.TemporaryDirectory() as root: good_dir, good_doc, _ = make_draft(root, 'pageswiki-edit-good', { 'origin': 'https://example.test', 'address': 'uuid:obj-1', 'base_revision_uuid': 'rev-1', 'lang': 'ja', 'format': 'raw', }, 'recovered text\n') make_draft(root, 'pageswiki-edit-badperm', { 'origin': 'https://example.test', 'address': 'uuid:obj-2', 'base_revision_uuid': 'rev-2', 'lang': 'ja', 'format': 'raw', }, 'ignored\n', dir_mode=0o755) bad_link = Path(root) / 'pageswiki-edit-symlink' bad_link.symlink_to(good_dir) out = io.StringIO() with contextlib.redirect_stdout(out): m['recover'](client, profile, list_only=True, temp_root=root) lines = out.getvalue().strip().splitlines() self.assertEqual(len(lines), 1) self.assertIn(str(good_dir), lines[0]) self.assertNotIn('badperm', out.getvalue()) self.assertNotIn('symlink', out.getvalue()) bad_link.unlink() # Resume update when head still matches. state = {'object_uuid': 'obj-1', 'head_revision_uuid': 'rev-1', 'principal_uuid': 'person', 'lang': 'ja', 'content_type': 'text/plain', 'filename': 'a.txt', 'body': 'old', 'markdown': 'old'} with patch.object(client, 'snapshot', return_value=state), \ patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}) as save_mock, \ contextlib.redirect_stdout(io.StringIO()) as out: m['recover'](client, profile, str(good_doc)) save_mock.assert_called_once_with(state, 'recovered text\n', False) self.assertIn('Saved revision: rev-2', out.getvalue()) self.assertFalse(good_dir.exists()) # Resume update when remote head changed: non-interactive keeps draft; interactive 'e' merges. moved_dir, moved_doc, _ = make_draft(root, 'pageswiki-edit-moved', { 'origin': 'https://example.test', 'address': 'uuid:obj-1', 'base_revision_uuid': 'rev-1', 'lang': 'ja', 'format': 'raw', }, 'draft edit\n') newer = {'object_uuid': 'obj-1', 'head_revision_uuid': 'rev-9', 'principal_uuid': 'person', 'lang': 'ja', 'content_type': 'text/plain', 'filename': 'a.txt', 'body': 'newer remote\n', 'markdown': 'newer remote\n'} with patch.object(client, 'snapshot', return_value=newer), \ patch.object(client, 'save') as save_mock, \ patch.object(m['sys'], 'stdin', io.StringIO('')), \ contextlib.redirect_stdout(io.StringIO()): with self.assertRaises(Failure) as caught: m['recover'](client, profile, str(moved_dir)) self.assertEqual(caught.exception.status, 409) save_mock.assert_not_called() self.assertTrue(moved_doc.exists()) def resolve_in_ed(args, **kwargs): p = Path(args[-1]) self.assertIn('<<<<<<< local\ndraft edit\n=======\nnewer remote\n>>>>>>> remote (rev: rev-9)\n', p.read_text(encoding='utf-8')) p.write_text('resolved draft\n', encoding='utf-8') return type('R', (), {'returncode': 0})() with patch.object(client, 'snapshot', return_value=newer), \ patch.object(client, 'save', return_value={'revision_uuid': 'rev-10'}) as save_mock, \ patch('subprocess.run', side_effect=resolve_in_ed), \ patch.dict(m['recover'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \ contextlib.redirect_stdout(io.StringIO()): m['recover'](client, profile, str(moved_dir)) save_mock.assert_called_once_with(newer, 'resolved draft\n', False) self.assertFalse(moved_dir.exists()) # Resume create draft. create_dir, _, _ = make_draft(root, 'pageswiki-edit-create', { 'origin': 'https://example.test', 'mode': 'create', 'address': 'path:/docs/new', 'lang': 'und', 'format': 'markdown', }, '# Created from recovery\n') with patch.object(client, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-new', 'revision_uuid': 'rev-new'}) as create_mock, \ contextlib.redirect_stdout(io.StringIO()) as out: m['recover'](client, profile, str(create_dir)) create_mock.assert_called_once_with('path:/docs/new', '# Created from recovery\n', True, lang='und') self.assertIn('Created page: /docs/new', out.getvalue()) self.assertFalse(create_dir.exists()) # Reject wrong origin with zero network calls. other_dir, _, _ = make_draft(root, 'pageswiki-edit-other', { 'origin': 'https://other.example', 'address': 'uuid:obj-1', 'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw', }, 'other\n') with patch.object(client, 'snapshot') as snap_mock, patch.object(client, 'save') as save_mock: with self.assertRaisesRegex(Failure, 'different server origin'): m['recover'](client, profile, str(other_dir)) snap_mock.assert_not_called(); save_mock.assert_not_called() # Reject insecure permissions and discard safety check. _, insecure_doc, _ = make_draft(root, 'pageswiki-edit-insecure', { 'origin': 'https://example.test', 'address': 'uuid:obj-1', 'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw', }, 'x\n', file_mode=0o644) with self.assertRaisesRegex(Failure, '0600'): m['recover'](client, profile, str(insecure_doc)) outside_dir, _, _ = make_draft(root, 'custom-dir', { 'origin': 'https://example.test', 'address': 'uuid:obj-1', 'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw', }, 'x\n') with self.assertRaisesRegex(Failure, 'Refusing to discard'): m['recover'](client, profile, str(outside_dir), discard=True) self.assertTrue(outside_dir.exists()) discard_dir, _, _ = make_draft(root, 'pageswiki-edit-discard', { 'origin': 'https://example.test', 'address': 'uuid:obj-1', 'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw', }, 'x\n') with contextlib.redirect_stdout(io.StringIO()) as out: m['recover'](client, profile, str(discard_dir), discard=True) 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 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(): fixture=json.load(sys.stdin) original=Client.json grant={} def capture(client,route,**kwargs): result=original(client,route,**kwargs) if route=='/_/auth/cli/start': grant.update(result) return result def browser(target,**kwargs): ident=m['url'].parse_qs(m['url'].urlsplit(target).query)['request'][0] original(Client(fixture['origin']),'/__test/cli-approve',method='POST',form={'request':ident,'code':grant['user_code']}) return True with tempfile.TemporaryDirectory() as root,patch.dict(os.environ,{'XDG_CONFIG_HOME':root}),contextlib.redirect_stdout(io.StringIO()) as output: m['main'](['configure','--origin',fixture['origin']]) with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc','--with-open-browser']) with Profile('default',root).locked() as session: token=session.data['token']; assert session.data['username']=='admin' m['main'](['ls']); m['main'](['status']) client=Client(fixture['origin'],token) state=client.snapshot('path:/editor-fixture') client.save(state,'# OIDC edit\n\n{{children}}\n',True) assert '{{children}}' in client.snapshot('path:/editor-fixture')['markdown'] m['main'](['logout']) assert token not in output.getvalue() try: client.snapshot('path:/editor-fixture') except Failure as e: assert e.status in (401,403,303) else: raise AssertionError('revoked CLI session accepted') print('OIDC CLI configure/login/list/authoring/logout integration passed') def integration(): fixture=json.load(sys.stdin) # Exercise the public entry point with persisted defaults, not only Client. with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}), contextlib.redirect_stdout(io.StringIO()) as output: m['main'](['configure','--origin',fixture['origin'],'--username','admin']) with patch('getpass.getpass',return_value='a long test password'): m['main'](['login']) with Profile('default',root).locked() as session: session_token=session.data['token'] m['main'](['ls']) m['main'](['status']) def local_editor(args, **kwargs): file=Path(args[-1]); file.write_text(file.read_text()+'\nConfigured CLI edit\n') class Result: returncode=0 return Result() with patch('subprocess.run',side_effect=local_editor): m['main'](['edit','/editor-fixture']) check=Client(fixture['origin'],session_token) assert 'Configured CLI edit' in check.snapshot('path:/editor-fixture')['body'] m['main'](['logout']) assert session_token not in output.getvalue() with Profile('default',root).locked() as session: assert 'token' not in session.data client=Client(fixture['origin'], lang='und') client.login('admin','a long test password') addr='path:/editor-fixture' state=client.snapshot(addr) assert state['lang']=='und' and state['principal_uuid'] missing=Client(fixture['origin'], client.token, 'ja') fork=missing.snapshot(addr) assert fork['lang']=='ja' and fork['head_revision_uuid']=='' and fork['new_language'] assert fork['body']==state['body'] and fork['source_language']=='und' missing.save(fork,'# Japanese draft\n\n{{children}}\n',True) assert missing.snapshot(addr)['lang']=='ja' assert client.snapshot(addr)['head_revision_uuid']==state['head_revision_uuid'] try: missing.save(fork,'competing first revision') except Failure as e: assert e.status==409 else: raise AssertionError('concurrent language creation overwrote the head') auto=Client(fixture['origin'],client.token) auto_state=auto.snapshot('path:/ja-only') assert auto_state['lang']=='ja' and auto_state['head_revision_uuid'] def edit_japanese(args, **kwargs): path=Path(args[-1]); path.write_text(path.read_text()+'\nJapanese edit\n') class Result: returncode=0 return Result() with patch('subprocess.run',side_effect=edit_japanese),contextlib.redirect_stdout(io.StringIO()): m['editor'](auto,'path:/ja-only','auto') assert 'Japanese edit' in auto.snapshot('path:/ja-only')['body'] pending=Client(fixture['origin'],client.token,'und').snapshot('path:/ja-only') assert pending['head_revision_uuid']=='' assert client.listing('/')['entries'] assert client.save(state,'# Remote\n\n{{children}}\n',True)['revision_uuid'] != state['head_revision_uuid'] latest=client.snapshot(addr) assert '{{children}}' in latest['markdown'] and '