Files

204 lines
9.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Check real production permissions without a model call or design mutation."""
import asyncio
import contextlib
import fcntl
import json
import os
from pathlib import Path
import sys
import tempfile
from .config import ROOT, CODEX_HOME, CODEX_BIN, EDA_BIN, BLENDER_BIN, FREEROUTING_JAR
from .rpc import SECRET_ENV_NAMES, sandbox_settings
from .eda import cli as eda_cli, EDA_LOCK, host_lock
def result(name, ok, message):
return {'name': name, 'ok': ok, 'message': message}
def writable(name, directory):
try:
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.pcb-write-check-', dir=directory) as temporary:
source = Path(temporary) / 'probe.tmp'
target = source.with_suffix('.json')
source.write_text('pcb-preflight')
source.replace(target)
if target.read_text() != 'pcb-preflight':
raise OSError('write/read verification failed')
return result(name, True, str(directory) + ' 可创建、写入和重命名文件')
except OSError as error:
return result(name, False, f'{directory} 无法写入:{error};检查容器 UID/GID、目录属主及只读挂载')
def executable(name, binary):
try:
ready = Path(binary).is_file() and os.access(binary, os.X_OK)
except OSError:
ready = False
if not ready:
return result(name, False, f'{binary} 不存在或当前用户无执行权限;检查完整 Linux 应用目录、chmod、父目录访问权限及 noexec 挂载')
return result(name, True, str(binary) + ' 存在且具备执行权限;仍需实际启动验证')
def readable(name, path):
try:
ready = path.is_file() and os.access(path, os.R_OK)
return result(name, ready, str(path) + (' 可读取' if ready else ' 不存在或当前用户无读取权限'))
except OSError as error:
return result(name, False, f'{path} 无法读取:{error}')
def safe_environment():
env = dict(os.environ, CODEX_HOME=str(CODEX_HOME))
for name in SECRET_ENV_NAMES:
env.pop(name, None)
return env
async def command(args, directory, env, timeout=30):
process = await asyncio.create_subprocess_exec(
*args, cwd=directory, env=env,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
start_new_session=True)
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout)
except (asyncio.TimeoutError, asyncio.CancelledError):
# The CLI may have children (including bubblewrap/Electron).
import signal
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGKILL)
await process.communicate()
raise
return process.returncode, (stderr or stdout).decode(errors='replace')[-1600:]
async def sandbox_check(directory, env):
try:
with tempfile.TemporaryDirectory(prefix='.pcb-sandbox-check-', dir=directory / 'tmp') as temporary:
marker = Path(temporary) / 'written.txt'
# The pinned CLI reserves -C for named permission profiles. The
# subprocess cwd already supplies the workspace for legacy settings.
args = [CODEX_BIN, 'sandbox']
settings = dict(sandbox_settings(True), **{
'sandbox_workspace_write.writable_roots': [str(directory)],
})
for key, value in settings.items():
args += ['-c', key + '=' + json.dumps(value)]
args += ['--', '/bin/sh', '-c', 'printf pcb-preflight > "$1"', 'pcb-preflight', str(marker)]
code, output = await command(args, directory, env)
if code != 0 or not marker.is_file() or marker.read_text() != 'pcb-preflight':
return result('codex_sandbox', False,
f'Codex 原生沙箱未能写入授权工作区(exit={code}):{output};'
'若包含 bwrap/namespace,需检查宿主机 user namespace、seccomp、AppArmor 策略')
return result('codex_sandbox', True, '原生 workspace-write 沙箱已实际创建文件;未调用模型')
except (OSError, asyncio.TimeoutError) as error:
return result('codex_sandbox', False, f'Codex 沙箱检测失败:{type(error).__name__}: {error}')
async def eda_check(directory, env):
try:
code, output = await command([EDA_BIN, '--help', '--no-sandbox'], directory, env)
if code != 0:
return result('eda_launch', False, f'EasyEDA --help 启动失败(exit={code}):{output}')
return result('eda_launch', True, 'EasyEDA --help 已实际启动;未创建或修改设计,不代表登录/绘板验收通过')
except (OSError, asyncio.TimeoutError) as error:
return result('eda_launch', False,
f'EasyEDA 无法启动:{type(error).__name__}: {error};检查执行权限、noexec、CPU 架构和动态库')
async def eda_bridge_check(directory, env):
"""Open only our blank diagnostic session; never touch an existing project."""
session = None
fd = None
locked = False
checks = []
options = {'binary': EDA_BIN, 'directory': ROOT, 'environment': env}
try:
await asyncio.wait_for(EDA_LOCK.acquire(), 10)
locked = True
fd = await host_lock(timeout=10)
opened = await eda_cli(['open', '--headless', 'true'], timeout=90, **options)
if not isinstance(opened, dict) or not isinstance(opened.get('sessionId'), str) or not opened['sessionId']:
raise RuntimeError('EasyEDA 未返回诊断会话 ID;未操作其他会话')
session = opened['sessionId']
value = await eda_cli(['invoke', '--session', session, '--ext-uuid', 'eda',
'--code-file', '-', '--timeout', '20000'],
'return {client: eda.sys_Environment.isClient(), version: eda.sys_Environment.getEditorCurrentVersion()};',
timeout=35, **options)
if not isinstance(value, dict) or value.get('client') is not True or not isinstance(value.get('version'), str) or not value['version'].strip():
raise RuntimeError('只读 EDA API 未返回有效的客户端标识及编辑器版本')
checks.append(result('eda_bridge', True,
f'独立空白会话及只读 EDA API 已验证,编辑器版本:{value["version"]}'))
except (OSError, RuntimeError, asyncio.TimeoutError) as error:
checks.append(result('eda_bridge', False,
f'EasyEDA 命令桥接不可用:{type(error).__name__}: {error};'
'确认客户端已激活并完成首次启动,再检查 CLI 与 pro-api 配套版本、显示服务和 HOME 日志权限'))
finally:
if session:
try:
await eda_cli(['session', 'close', '--session', session, '--destroy'], timeout=20, **options)
except (OSError, RuntimeError, asyncio.TimeoutError) as error:
checks.append(result('eda_cleanup', False, f'诊断会话未能关闭:{error};未关闭其他设计会话'))
if fd:
fcntl.flock(fd, fcntl.LOCK_UN)
fd.close()
if locked:
EDA_LOCK.release()
return checks
async def check_runtime(directory):
directory = Path(directory).resolve()
checks = [writable(name, path) for name, path in (
('runtime_write', ROOT), ('home_write', Path.home()),
('codex_home_write', CODEX_HOME), ('workspace_write', directory),
('temporary_write', directory / 'tmp'))]
programs = {name: executable(name, binary) for name, binary in (
('codex_binary', CODEX_BIN), ('eda_binary', EDA_BIN), ('blender_binary', BLENDER_BIN))}
checks.extend(programs.values())
for name, path in (('api_references', ROOT / 'resources/references/_index.md'),):
checks.append(readable(name, path))
env = safe_environment()
# EasyEDA uses the host temporary directory for its persistent IPC socket.
# A disposable probe/task directory breaks discovery across CLI calls (and
# long paths can exceed the macOS Unix-socket limit). Only sandbox probes
# need their temporary files confined to the diagnostic workspace.
sandbox_env = dict(env, TMPDIR=str(directory / 'tmp'),
TMP=str(directory / 'tmp'), TEMP=str(directory / 'tmp'))
# Run both checks even if another dependency failed, to report independent blockers.
if programs['codex_binary']['ok']:
checks.append(await sandbox_check(directory, sandbox_env))
if programs['eda_binary']['ok']:
launch = await eda_check(directory, env)
checks.append(launch)
if launch['ok']:
checks.extend(await eda_bridge_check(directory, env))
return {'ok': all(item['ok'] for item in checks), 'checks': checks,
'scope': 'filesystem, native sandbox, EDA startup and read-only bridge; no model call or design created'}
async def check_environment():
try:
# Keep probes separate from saved tasks, and remove all diagnostic files.
parent = ROOT / 'tasks'
parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.pcb-preflight-', dir=parent) as temporary:
report = await check_runtime(Path(temporary))
except OSError as error:
report = {'ok': False, 'checks': [result('workspace_write', False,
f'{ROOT / "tasks"} 无法创建诊断工作区:{error};检查 UID/GID 及挂载权限')]}
return report
async def main():
report = await check_environment()
print(json.dumps(report, ensure_ascii=False, indent=2))
return 0 if report['ok'] else 1
if __name__ == '__main__':
sys.exit(asyncio.run(main()))