feat(shell): add vi projection, !cmd local execution, and $cmd stream/file projection

This commit is contained in:
Anya Tokugawa committed 2026-11-30 23:24:46 +09:00
1 parent 9a0ebd874f
commit 7176b2c47b
2 files changed
+587 -11

No files matched your search

+400 -11
View File
@@ -803,9 +803,9 @@ def private_dir(path):
raise Failure('Recovery directory must be owned by you with mode 0700; symlinks are not accepted.') raise Failure('Recovery directory must be owned by you with mode 0700; symlinks are not accepted.')
def run_editor(file): def run_editor(file, *, command=None):
command = shlex.split(os.environ.get('EDITOR', 'vi')) cmd = list(command) if command is not None else shlex.split(os.environ.get('EDITOR', 'vi'))
if not command or subprocess.run(command + [str(file)], check=False).returncode: if not cmd or subprocess.run(cmd + [str(file)], check=False).returncode:
raise Failure('Editor exited unsuccessfully.') raise Failure('Editor exited unsuccessfully.')
@@ -956,7 +956,7 @@ def confirm_create(addr, status):
return answer.strip().lower() in ('y', 'yes') return answer.strip().lower() in ('y', 'yes')
def editor(client, addr, mode): def editor(client, addr, mode, *, editor_command=None):
creating = False creating = False
state = None state = None
try: try:
@@ -992,7 +992,7 @@ def editor(client, addr, mode):
ctx = {'creating': creating, 'addr': addr, 'state': state, 'lang': lang, 'markdown': markdown} ctx = {'creating': creating, 'addr': addr, 'state': state, 'lang': lang, 'markdown': markdown}
success = False success = False
try: try:
run_editor(file) run_editor(file, command=editor_command)
text = file.read_text(encoding='utf-8') text = file.read_text(encoding='utf-8')
if text == initial: if text == initial:
print('Unchanged; page was not created.' if creating else 'Unchanged.') print('Unchanged; page was not created.' if creating else 'Unchanged.')
@@ -1644,10 +1644,10 @@ def execute(client, profile, words):
return tasks(client,profile,words[1:]) return tasks(client,profile,words[1:])
parser = argparse.ArgumentParser(prog='pages') parser = argparse.ArgumentParser(prog='pages')
sub = parser.add_subparsers(dest='command', required=True) sub = parser.add_subparsers(dest='command', required=True)
for command in ('ls', 'cd', 'cat', 'view', 'edit', 'open'): for command in ('ls', 'cd', 'cat', 'view', 'edit', 'vi', 'open'):
p = sub.add_parser(command) p = sub.add_parser(command)
p.add_argument('path', nargs='?', default='.') p.add_argument('path', nargs='?', default='.')
if command == 'edit': if command in ('edit', 'vi'):
p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto') p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto')
p.add_argument('--lang', help='auto edits the visible language (or creates as und with warning); an explicit tag selects or creates a language revision') p.add_argument('--lang', help='auto edits the visible language (or creates as und with warning); an explicit tag selects or creates a language revision')
elif command == 'cat': elif command == 'cat':
@@ -1725,8 +1725,16 @@ def execute(client, profile, words):
elif cmd == 'open': elif cmd == 'open':
route = addr[5:] if addr.startswith('path:') else '/o/' + addr if addr.startswith('uuid:') else '/r/view/' + addr[4:] route = addr[5:] if addr.startswith('path:') else '/o/' + addr if addr.startswith('uuid:') else '/r/view/' + addr[4:]
webbrowser.open(client.base + url.quote(route, safe='/:'), new=2) webbrowser.open(client.base + url.quote(route, safe='/:'), new=2)
elif cmd == 'edit': elif cmd in ('edit', 'vi'):
editing = Client(client.base, client.token, language(args.lang), insecure=client.insecure) if args.lang else client editing = Client(client.base, client.token, language(args.lang), insecure=client.insecure) if args.lang else client
if cmd == 'vi':
vi_bin = shutil.which('vi')
if vi_bin:
editor(editing, addr, args.format, editor_command=[vi_bin])
else:
print('vi not found on PATH; falling back to $EDITOR.', file=sys.stderr)
editor(editing, addr, args.format)
else:
editor(editing, addr, args.format) editor(editing, addr, args.format)
elif cmd == 'put': elif cmd == 'put':
local_path = Path(args.local) local_path = Path(args.local)
@@ -1776,7 +1784,7 @@ def execute(client, profile, words):
SHELL_COMMANDS = ( SHELL_COMMANDS = (
'cat', 'cd', 'contacts', 'edit', 'exit', 'get', 'help', 'logout', 'cat', 'cd', 'contacts', 'edit', 'exit', 'get', 'help', 'logout',
'ls', 'mget', 'mput', 'open', 'pick', 'put', 'pwd', 'quit', 'ls', 'mget', 'mput', 'open', 'pick', 'put', 'pwd', 'quit',
'recover', 'search', 'status', 'task', 'view', 'recover', 'search', 'status', 'task', 'vi', 'view',
) )
SHELL_SUBCOMMANDS = { SHELL_SUBCOMMANDS = {
'task': ('add', 'done', 'from-mail', 'list', 'preferences', 'project-add', 'projects', 'reopen', 'report', 'retry', 'show', 'start', 'status', 'stop', 'update'), 'task': ('add', 'done', 'from-mail', 'list', 'preferences', 'project-add', 'projects', 'reopen', 'report', 'retry', 'show', 'start', 'status', 'stop', 'update'),
@@ -1850,7 +1858,30 @@ def _format_shell_token(candidate, quote_char, *, is_dir=False):
def shell_completions(client, cwd, before_cursor, *, temp_root=None): def shell_completions(client, cwd, before_cursor, *, temp_root=None):
prefix_str, completed, current, quote_char = _split_shell_context(before_cursor) prefix_str, completed, current, quote_char = _split_shell_context(before_cursor)
if not completed and not quote_char: if not completed and not quote_char:
if current.startswith(('!', '$')):
return []
return [prefix_str + cmd for cmd in SHELL_COMMANDS if cmd.startswith(current)] return [prefix_str + cmd for cmd in SHELL_COMMANDS if cmd.startswith(current)]
if completed and completed[0].startswith('!'):
return []
if completed and completed[0].startswith('$'):
if completed[0] == '$':
# Still reading optional launcher flags or the local command name itself.
tokens_after = completed[1:]
idx = 0
has_app = False
while idx < len(tokens_after):
tok = tokens_after[idx]
if tok in ('--stream', '--file'):
idx += 1
elif tok in ('--max-bytes', '--timeout'):
idx += 2
elif tok.startswith(('--max-bytes=', '--timeout=')):
idx += 1
else:
has_app = True
break
if not has_app or idx > len(tokens_after):
return []
if len(completed) == 1 and completed[0] in SHELL_SUBCOMMANDS and not quote_char: if len(completed) == 1 and completed[0] in SHELL_SUBCOMMANDS and not quote_char:
return [prefix_str + sub for sub in SHELL_SUBCOMMANDS[completed[0]] if sub.startswith(current)] return [prefix_str + sub for sub in SHELL_SUBCOMMANDS[completed[0]] if sub.startswith(current)]
if completed and completed[0] == 'recover' and not current.startswith('-'): if completed and completed[0] == 'recover' and not current.startswith('-'):
@@ -2263,10 +2294,359 @@ def _save_shell_history(readline_mod, path):
tmp.unlink() tmp.unlink()
STREAM_PROJECT_APPS = frozenset({
'vlc', 'cvlc', 'mpv', 'ffplay', 'mplayer', 'totem', 'celluloid', 'iina', 'smplayer',
})
def run_local_command(cmdline):
body = cmdline.lstrip()[1:].strip()
if not body:
print('Usage: !COMMAND [ARGS...] (or !cd DIR)')
return
argv = shlex.split(body)
if not argv:
print('Usage: !COMMAND [ARGS...] (or !cd DIR)')
return
if argv[0] == 'cd':
if len(argv) > 2:
raise Failure('Usage: !cd [DIR]')
target = os.path.expanduser(argv[1] if len(argv) == 2 else '~')
os.chdir(target)
print(safe_text(os.getcwd()))
return
try:
subprocess.run(argv, check=False)
except FileNotFoundError:
raise Failure('Local command not found: ' + argv[0]) from None
def _project_raw_route(client, addr):
query = '' if client.lang == 'auto' else '?' + url.urlencode({'lang': client.lang})
return '/v/raw/' + url.quote(addr, safe='/:') + query
def _project_filename(addr, headers=None):
name = ''
if headers is not None:
disp = headers.get('Content-Disposition') or ''
m_cd = re.search(r'filename="([^"]+)"', disp)
if m_cd:
name = m_cd.group(1)
if not name and addr.startswith('path:'):
name = posixpath.basename(addr[5:].rstrip('/'))
if not name:
name = addr.split(':', 1)[-1]
name = safe_text(name).replace('\n', '').replace('\t', '')
name = posixpath.basename(name.replace('\\', '/')).strip()
if not name or name in ('.', '..'):
return 'document'
return name
def _parse_project_line(cmdline):
body = cmdline.lstrip()[1:].strip()
if not body:
raise Failure('Usage: $[--stream|--file] COMMAND ARGS...')
tokens = shlex.split(body)
mode = 'auto'
max_bytes = DEFAULT_DOWNLOAD_LIMIT
timeout = DEFAULT_DEADLINE
idx = 0
while idx < len(tokens):
tok = tokens[idx]
if tok == '--stream':
mode = 'stream'
idx += 1
elif tok == '--file':
mode = 'file'
idx += 1
elif tok == '--max-bytes':
if idx + 1 >= len(tokens):
raise Failure('--max-bytes requires a positive integer.')
try:
max_bytes = int(tokens[idx + 1])
except ValueError:
raise Failure('--max-bytes requires a positive integer.') from None
idx += 2
elif tok.startswith('--max-bytes='):
try:
max_bytes = int(tok.split('=', 1)[1])
except ValueError:
raise Failure('--max-bytes requires a positive integer.') from None
idx += 1
elif tok == '--timeout':
if idx + 1 >= len(tokens):
raise Failure('--timeout requires a positive integer.')
try:
timeout = int(tokens[idx + 1])
except ValueError:
raise Failure('--timeout requires a positive integer.') from None
idx += 2
elif tok.startswith('--timeout='):
try:
timeout = int(tok.split('=', 1)[1])
except ValueError:
raise Failure('--timeout requires a positive integer.') from None
idx += 1
elif tok == '--':
idx += 1
break
else:
break
if max_bytes <= 0 or timeout <= 0:
raise Failure('Download limit and timeout must be positive.')
cmd_argv = tokens[idx:]
if not cmd_argv:
raise Failure('Usage: $[--stream|--file] COMMAND ARGS...')
return mode, max_bytes, timeout, cmd_argv
def _resolve_project_args(client, cwd, args):
cwd_names = None
resolved = []
targets = []
for arg in args:
if arg.startswith('local:'):
resolved.append(('literal', arg[6:]))
elif arg.startswith(('path:', 'uuid:', 'rev:')) or arg.startswith('/'):
targets.append(len(resolved))
resolved.append(('wiki', address(arg, cwd)))
elif arg.startswith('-') or '://' in arg or arg in ('.', '..'):
resolved.append(('literal', arg))
else:
if cwd_names is None:
try:
entries = client.listing(cwd).get('entries', [])
except Failure:
entries = []
cwd_names = {item.get('name', '') for item in entries if item.get('name')}
head = arg.split('/', 1)[0]
if head in cwd_names:
targets.append(len(resolved))
resolved.append(('wiki', address(arg, cwd)))
else:
resolved.append(('literal', arg))
if not targets:
raise Failure('Specify at least one Wiki path or address to project (prefix local files with local:).')
return resolved
class _LoopbackRawProxy:
def __init__(self, client):
self.client = client
self.routes = {}
self.server = None
self.thread = None
self.port = 0
def register(self, addr, filename):
token = secrets.token_urlsafe(24)
self.routes[token] = addr
return f'http://127.0.0.1:{self.port}/{token}/{url.quote(filename, safe="")}'
def __enter__(self):
proxy = self
class ProxyHandler(http_server.BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, format, *args):
return
def _relay(self, method):
if method not in ('GET', 'HEAD'):
self.send_response(405)
self.send_header('Allow', 'GET, HEAD')
self.send_header('Content-Length', '0')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
return
parts = url.urlsplit(self.path).path.lstrip('/').split('/', 1)
token = parts[0] if parts else ''
addr = None
for candidate_tok, candidate_addr in proxy.routes.items():
if secrets.compare_digest(token, candidate_tok):
addr = candidate_addr
break
if addr is None:
self.send_response(404)
self.send_header('Content-Length', '0')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
return
req_headers = {'User-Agent': 'pages-cli/' + VERSION}
if proxy.client.token:
req_headers['Authorization'] = 'Bearer ' + proxy.client.token
for hdr in ('Range', 'If-Range'):
val = self.headers.get(hdr)
if val:
req_headers[hdr] = val
upstream_url = proxy.client.base + _project_raw_route(proxy.client, addr)
req = http.Request(upstream_url, None, req_headers, method=method)
try:
resp = proxy.client.opener.open(req, timeout=DEFAULT_TIMEOUT)
except urllib.error.HTTPError as err:
status = err.code
if status in (301, 302, 303, 307, 308):
status = 502
self.send_response(status)
for hdr in ('Content-Type', 'Content-Length', 'Content-Range', 'Accept-Ranges', 'ETag'):
val = err.headers.get(hdr) if err.headers else None
if val:
self.send_header(hdr, val)
self.send_header('Cache-Control', 'private, no-store')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
err.close()
return
except (OSError, urllib.error.URLError):
self.send_response(502)
self.send_header('Content-Length', '0')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
return
try:
self.send_response(resp.status)
for hdr in ('Content-Type', 'Content-Length', 'Content-Range', 'Accept-Ranges', 'ETag', 'Last-Modified'):
val = resp.headers.get(hdr)
if val:
self.send_header(hdr, val)
self.send_header('Cache-Control', 'private, no-store')
self.send_header('Connection', 'close')
self.end_headers()
self.close_connection = True
if method == 'GET':
while True:
chunk = resp.read(CHUNK_SIZE)
if not chunk:
break
self.wfile.write(chunk)
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
pass
finally:
resp.close()
def do_GET(self):
self._relay('GET')
def do_HEAD(self):
self._relay('HEAD')
def do_POST(self):
self._relay('POST')
def do_PUT(self):
self._relay('PUT')
def do_DELETE(self):
self._relay('DELETE')
class LoopbackServer(http_server.ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
self.server = LoopbackServer(('127.0.0.1', 0), ProxyHandler)
self.port = self.server.server_port
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
return self
def __exit__(self, exc_type, exc, tb):
if self.server is not None:
self.server.shutdown()
self.server.server_close()
def run_project_command(client, cwd, cmdline, *, runner=subprocess.run):
mode, max_bytes, timeout, cmd_argv = _parse_project_line(cmdline)
resolved = _resolve_project_args(client, cwd, cmd_argv[1:])
app_name = os.path.basename(cmd_argv[0]).lower()
if mode == 'auto':
mode = 'stream' if app_name in STREAM_PROJECT_APPS else 'file'
if mode == 'stream':
meta = []
for kind, val in resolved:
if kind == 'wiki':
preflight_headers = []
client.stream_request(
_project_raw_route(client, val), method='HEAD', limit=None,
on_headers=lambda st, hdrs, box=preflight_headers: box.append(hdrs),
)
hdrs = preflight_headers[0] if preflight_headers else None
meta.append((val, _project_filename(val, hdrs)))
with _LoopbackRawProxy(client) as proxy:
final_argv = [cmd_argv[0]]
meta_iter = iter(meta)
for kind, val in resolved:
if kind == 'wiki':
addr, fname = next(meta_iter)
final_argv.append(proxy.register(addr, fname))
else:
final_argv.append(val)
try:
runner(final_argv, check=False)
except FileNotFoundError:
raise Failure('Local command not found: ' + cmd_argv[0]) from None
return
directory = Path(tempfile.mkdtemp(prefix='pageswiki-open-'))
created_files = []
try:
os.chmod(directory, 0o700)
used_names = set()
final_argv = [cmd_argv[0]]
for kind, val in resolved:
if kind != 'wiki':
final_argv.append(val)
continue
fname = _project_filename(val)
if fname in used_names:
fname = f'{len(used_names) + 1}-{fname}'
used_names.add(fname)
dest = directory / fname
client.download(val, str(dest), limit=max_bytes, deadline_seconds=timeout)
os.chmod(dest, 0o400)
created_files.append(dest)
final_argv.append(str(dest))
try:
runner(final_argv, check=False)
except FileNotFoundError:
raise Failure('Local command not found: ' + cmd_argv[0]) from None
finally:
for fpath in created_files:
if fpath.exists() and not fpath.is_symlink():
try:
os.chmod(fpath, 0o600)
except OSError:
pass
try:
fpath.unlink()
except OSError:
pass
if directory.exists():
for leftover in directory.iterdir():
if not leftover.is_symlink() and leftover.is_file():
try:
os.chmod(leftover, 0o600)
leftover.unlink()
except OSError:
pass
try:
directory.rmdir()
except OSError:
pass
def shell(client, profile, *, persist_history=False, history_root=None): def shell(client, profile, *, persist_history=False, history_root=None):
import readline import readline
print(safe_text('pages · ' + client.base + ' · ' + profile.data.get('username', '') + ' · ' + client.lang)) print(safe_text('pages · ' + client.base + ' · ' + profile.data.get('username', '') + ' · ' + client.lang))
print('Type help for commands, Tab to complete, Ctrl+P (or pick) for fuzzy search.') print('Type help for commands, !cmd for local shell, $cmd for local app projection, Ctrl+P for fuzzy TUI.')
# History remains in memory unless --history is explicitly opted in; login/password commands are not supported here. # History remains in memory unless --history is explicitly opted in; login/password commands are not supported here.
readline.set_history_length(200) readline.set_history_length(200)
hist_path = None hist_path = None
@@ -2329,11 +2709,20 @@ def shell(client, profile, *, persist_history=False, history_root=None):
if inserted: if inserted:
pre_input_text[0] = inserted pre_input_text[0] = inserted
continue continue
stripped_line = line.lstrip()
if stripped_line.startswith('!'):
run_local_command(stripped_line)
continue
if stripped_line.startswith('$'):
if profile.data.get('expires', 0) <= time.time():
raise Failure('Session expired; log in again.')
run_project_command(client, profile.data.get('cwd', '/'), stripped_line)
continue
words = shlex.split(line) words = shlex.split(line)
if not words: continue if not words: continue
if words[0] in ('exit', 'quit'): break if words[0] in ('exit', 'quit'): break
if words[0] == 'help': if words[0] == 'help':
print('Commands: ' + ', '.join(SHELL_COMMANDS) + '. Keys: Tab=complete, Ctrl+P=fuzzy pick.') print('Commands: ' + ', '.join(SHELL_COMMANDS) + '. Local: !CMD (!cd), App project: $[--stream|--file] CMD WIKI_PATH. Keys: Tab=complete, Ctrl+P=fuzzy TUI.')
continue continue
if words[0] == 'pick': if words[0] == 'pick':
inserted = fuzzy_pick(client, profile, initial_query=' '.join(words[1:])) inserted = fuzzy_pick(client, profile, initial_query=' '.join(words[1:]))
+187
View File
@@ -1521,6 +1521,193 @@ class RemoteTests(unittest.TestCase):
patch.dict(m['fuzzy_pick'].__globals__, {'_line_fuzzy_pick': lambda *a, **kw: '/docs/intro', '_tui_fuzzy_pick': lambda *a, **kw: self.fail('should not invoke TUI on TERM=dumb')}): patch.dict(m['fuzzy_pick'].__globals__, {'_line_fuzzy_pick': lambda *a, **kw: '/docs/intro', '_tui_fuzzy_pick': lambda *a, **kw: self.fail('should not invoke TUI on TERM=dumb')}):
self.assertEqual(m['fuzzy_pick'](client, profile, initial_line='cat '), 'cat /docs/intro') self.assertEqual(m['fuzzy_pick'](client, profile, initial_line='cat '), 'cat /docs/intro')
def test_vi_local_commands_and_project_stream_or_file(self):
client = Client('https://example.test', 'secret-tok')
profile = type('P', (), {'name': 'test', 'data': {'cwd': '/', 'expires': time.time() + 600}})()
# 1. vi resolves local vi (falling back to $EDITOR) and commits via CAS; completions work for vi/$cmd/!cmd.
snapshot_state = {
'object_uuid': '00000000-0000-0000-0000-000000000001',
'lang': 'en', 'head_revision_uuid': 'rev-1', 'etag': '"rev-1"',
'content_type': 'text/plain', 'body': 'before\n', 'markdown': 'before\n',
}
runs = []
def fake_sub_run(cmd, check=False, **kwargs):
runs.append(cmd)
if cmd and cmd[0] in ('/usr/bin/vi', 'nano'):
Path(cmd[-1]).write_text('after\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch.object(client, 'snapshot', return_value=snapshot_state), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}) as save_mock, \
patch.object(m['shutil'], 'which', return_value='/usr/bin/vi'), \
patch.object(m['subprocess'], 'run', side_effect=fake_sub_run), \
patch.dict(os.environ, {'EDITOR': 'nano'}), \
contextlib.redirect_stdout(io.StringIO()):
m['execute'](client, profile, ['vi', '/note'])
self.assertEqual(runs[0][0], '/usr/bin/vi')
save_mock.assert_called_once()
runs.clear()
with patch.object(client, 'snapshot', return_value=snapshot_state), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}), \
patch.object(m['shutil'], 'which', return_value=None), \
patch.object(m['subprocess'], 'run', side_effect=fake_sub_run), \
patch.dict(os.environ, {'EDITOR': 'nano'}), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
m['execute'](client, profile, ['vi', '/note'])
self.assertEqual(runs[0][0], 'nano')
self.assertIn('falling back to $EDITOR', err.getvalue())
with patch.object(client, 'listing', return_value={'entries': [{'name': 'guide', 'path': '/guide', 'kind': 'file'}]}):
self.assertEqual(m['shell_completions'](client, '/', 'vi g'), ['vi guide'])
self.assertEqual(m['shell_completions'](client, '/', '$vlc g'), ['$vlc guide'])
self.assertEqual(m['shell_completions'](client, '/', '$ --stream '), [])
self.assertEqual(m['shell_completions'](client, '/', '!ls g'), [])
self.assertIn('vi', m['shell_completions'](client, '/', 'v'))
# 2. !cmd runs locally with shell=False and !cd changes local working directory.
orig_cwd = os.getcwd()
with tempfile.TemporaryDirectory() as local_tmp:
real_tmp = os.path.realpath(local_tmp)
try:
with contextlib.redirect_stdout(io.StringIO()) as out:
m['run_local_command']('!cd ' + m['shlex'].quote(real_tmp))
self.assertEqual(os.path.realpath(os.getcwd()), real_tmp)
self.assertEqual(out.getvalue().strip(), real_tmp)
finally:
os.chdir(orig_cwd)
runs.clear()
with patch.object(m['subprocess'], 'run', side_effect=fake_sub_run):
m['run_local_command']('!echo hello world')
self.assertEqual(runs[-1], ['echo', 'hello', 'world'])
with self.assertRaisesRegex(Failure, 'Local command not found'):
m['run_local_command']('!definitely-missing-pages-binary-xyz')
# 3. $cmd stream mode (loopback HTTP Range proxy) and file mode (verified 0400 temp file).
import urllib.error as url_error
import urllib.request as url_request
media_bytes = b'0123456789ABCDEF' * 1024
media_sha = hashlib.sha256(media_bytes).hexdigest()
doc_bytes = b'{"title": "hello"}\n'
doc_sha = hashlib.sha256(doc_bytes).hexdigest()
upstream_auths = []
class RawHandler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, format, *args): return
def _serve(self, head_only=False):
upstream_auths.append(self.headers.get('Authorization'))
path_only = m['url'].urlsplit(self.path).path
if path_only == '/v/raw/path:/movies/clip.mp4':
payload, ctype, sha, etag = media_bytes, 'video/mp4', media_sha, '"m1"'
elif path_only == '/v/raw/path:/data/doc.json':
payload, ctype, sha, etag = doc_bytes, 'application/json', doc_sha, '"d1"'
else:
self.send_response(404); self.send_header('Content-Length', '0'); self.end_headers(); return
rng = self.headers.get('Range')
if rng == 'bytes=2-5':
part = payload[2:6]
self.send_response(206)
self.send_header('Content-Type', ctype)
self.send_header('Content-Range', f'bytes 2-5/{len(payload)}')
self.send_header('Content-Length', str(len(part)))
self.send_header('ETag', etag)
self.send_header('X-PagesWiki-Document-SHA256', sha)
self.end_headers()
if not head_only:
self.wfile.write(part)
return
self.send_response(200)
self.send_header('Content-Type', ctype)
self.send_header('Accept-Ranges', 'bytes')
self.send_header('Content-Length', str(len(payload)))
self.send_header('ETag', etag)
self.send_header('X-PagesWiki-Document-SHA256', sha)
self.end_headers()
if not head_only:
self.wfile.write(payload)
def do_GET(self): self._serve(False)
def do_HEAD(self): self._serve(True)
class Server(ThreadingHTTPServer):
daemon_threads = True
srv = Server(('127.0.0.1', 0), RawHandler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
srv_client = Client(f'http://127.0.0.1:{srv.server_port}', 'secret-tok')
# Stream mode with vlc auto-detection and Range request through loopback proxy.
seen_argv = []
def stream_child(argv, check=False):
seen_argv.extend(argv)
target_url = argv[-1]
self.assertTrue(target_url.startswith('http://127.0.0.1:'))
self.assertTrue(target_url.endswith('/clip.mp4'))
self.assertNotIn('secret-tok', ' '.join(argv))
with url_request.urlopen(target_url, timeout=5) as r:
self.assertEqual(r.status, 200)
self.assertEqual(r.read(), media_bytes)
req = url_request.Request(target_url, headers={'Range': 'bytes=2-5'})
with url_request.urlopen(req, timeout=5) as r:
self.assertEqual(r.status, 206)
self.assertEqual(r.read(), media_bytes[2:6])
bad_url = target_url.rsplit('/', 2)[0] + '/wrong-token/clip.mp4'
with self.assertRaises(url_error.HTTPError) as ctx:
url_request.urlopen(bad_url, timeout=5)
self.assertEqual(ctx.exception.code, 404)
ctx.exception.close()
post_req = url_request.Request(target_url, data=b'x', method='POST')
with self.assertRaises(url_error.HTTPError) as ctx2:
url_request.urlopen(post_req, timeout=5)
self.assertEqual(ctx2.exception.code, 405)
ctx2.exception.close()
with patch.object(srv_client, 'listing', return_value={'entries': [{'name': 'movies', 'path': '/movies', 'kind': 'folder'}]}):
m['run_project_command'](srv_client, '/', '$vlc movies/clip.mp4', runner=stream_child)
self.assertEqual(seen_argv[0], 'vlc')
self.assertTrue(all(a == 'Bearer secret-tok' for a in upstream_auths))
# Proxy closes immediately on child exit.
with self.assertRaises(url_error.URLError):
url_request.urlopen(seen_argv[-1], timeout=2)
# File mode for jq (read-only 0400 temp file, cleaned up afterward) and explicit --file on vlc.
observed_paths = []
def file_child(argv, check=False):
observed_paths.append(list(argv))
fpath = Path(argv[2])
self.assertTrue(fpath.exists())
self.assertEqual(fpath.name, 'doc.json')
self.assertEqual(stat.S_IMODE(fpath.parent.stat().st_mode), 0o700)
self.assertEqual(stat.S_IMODE(fpath.stat().st_mode), 0o400)
self.assertEqual(fpath.read_bytes(), doc_bytes)
raise RuntimeError('simulated child error')
with patch.object(srv_client, 'listing', return_value={'entries': [{'name': 'data', 'path': '/data', 'kind': 'folder'}]}):
with self.assertRaisesRegex(RuntimeError, 'simulated child error'):
m['run_project_command'](srv_client, '/', '$jq .title /data/doc.json local:/tmp/keep.json', runner=file_child)
self.assertEqual(observed_paths[0][:2], ['jq', '.title'])
# Temporary file and directory are removed even when the child fails.
temp_file = Path(observed_paths[0][2])
self.assertEqual(observed_paths[0][3], '/tmp/keep.json')
self.assertFalse(temp_file.exists())
self.assertFalse(temp_file.parent.exists())
# Explicit --file overrides STREAM_PROJECT_APPS (vlc receives a verified local file instead of HTTP URL).
explicit_file_argv = []
def explicit_file_child(argv, check=False):
explicit_file_argv.extend(argv)
self.assertTrue(Path(argv[1]).name == 'clip.mp4')
self.assertEqual(Path(argv[1]).read_bytes(), media_bytes)
m['run_project_command'](srv_client, '/', '$ --file vlc /movies/clip.mp4', runner=explicit_file_child)
self.assertEqual(explicit_file_argv[0], 'vlc')
self.assertFalse(Path(explicit_file_argv[1]).exists())
finally:
srv.shutdown()
srv.server_close()
def oidc_integration(): def oidc_integration():
fixture=json.load(sys.stdin) fixture=json.load(sys.stdin)