Files
kefu/deploy/order-mcp-20260922/server-bundle/order_server_guard.py
T
2026-09-28 10:02:50 +08:00

70 lines
3.9 KiB
Python

"""Read-only baseline / candidate / deployed verification. Prints hashes and status only."""
from pathlib import Path
import argparse, hashlib, json, subprocess, urllib.request, urllib.error
parser = argparse.ArgumentParser()
parser.add_argument('mode', choices=['baseline', 'candidate', 'deployed'])
args = parser.parse_args()
RELEASE = 'order-mcp-20260922'
folder = Path(__file__).resolve().parent
project = Path('/opt/im-admin')
base = json.loads((folder / 'server-baseline-order.json').read_text())
manifest = json.loads((folder / 'order-manifest.json').read_text())
containers = ['im-admin-api-1', 'im-admin-gateway-1', 'im-admin-knowledge-worker-1']
image = lambda ref: subprocess.check_output(['docker', 'image', 'inspect', ref, '--format', '{{.Id}}'], text=True).strip()
sha = lambda data: hashlib.sha256(data).hexdigest()
# Files that must match on the host and inside the running container.
expected = dict(base['expected'])
if args.mode != 'baseline':
for row in manifest:
if row['path'].startswith('wechat_rpa/'):
expected[Path(row['path']).name] = row['sha256']
# The payload itself must be intact.
for row in manifest:
path = folder / ('payload/' + row['path'] if row['path'].startswith('wechat_rpa/') else row['path'])
assert path.resolve().is_relative_to(folder.resolve())
assert path.stat().st_size == row['bytes'] and sha(path.read_bytes()) == row['sha256'], row['path']
current = image('zyt/wecom-admin:current')
if args.mode == 'baseline':
# Code drift is the real signal; the image id is recorded, not assumed.
for container in containers:
actual = subprocess.check_output(['docker', 'inspect', container, '--format', '{{.Image}}'], text=True).strip()
assert actual == current, 'Running container is not on zyt/wecom-admin:current: ' + container
for name in base.get('must_not_exist', []):
assert not (project / 'wechat_rpa' / name).exists(), 'Unexpected existing file: ' + name
if args.mode != 'candidate':
for name, wanted in expected.items():
assert sha((project / 'wechat_rpa' / name).read_bytes()) == wanted, 'Host drift: ' + name
code = ('from pathlib import Path;import hashlib,json,sys;names=json.load(sys.stdin);'
'print(json.dumps({n:hashlib.sha256((Path("/app/wechat_rpa")/n).read_bytes()).hexdigest() for n in names}))')
actual = json.loads(subprocess.check_output(
['docker', 'exec', '-i', 'im-admin-api-1', 'python', '-c', code], input=json.dumps(list(expected)).encode()))
assert actual == expected, 'Container code differs from expected'
if args.mode == 'deployed':
wanted = image('zyt/wecom-admin:' + RELEASE)
assert current == wanted
for name in containers:
raw = json.loads(subprocess.check_output(['docker', 'inspect', name]))[0]
assert raw['Image'] == wanted and raw['State']['Running'] and raw['RestartCount'] == 0, name
assert raw['State'].get('Health', {}).get('Status', 'not_configured') in ('healthy', 'not_configured'), name
for url in ['http://127.0.0.1:18766/api/v2/health', 'http://127.0.0.1:18770/health']:
with urllib.request.urlopen(url, timeout=15) as response:
assert response.status == 200
# New order routes must exist and must reject anonymous reads. No real patient is queried.
for path in ['/api/v2/archive/desktop/patient-orders/summary', '/api/v2/archive/desktop/patient-orders',
'/api/v2/archive/desktop/patient-orders/1/tracking']:
try:
urllib.request.urlopen('http://127.0.0.1:18766' + path
+ '?external_account_id=synthetic&conversation_external_id=synthetic', timeout=15)
except urllib.error.HTTPError as exc:
assert exc.code in (401, 403), (path, exc.code)
else:
raise AssertionError('Order API accessible without authentication: ' + path)
print(json.dumps({'mode': args.mode, 'image': current, 'files': len(expected), 'status': 'passed', 'patientDataRead': False}))