121 lines
6.0 KiB
Python
121 lines
6.0 KiB
Python
"""Read-only checks for review-scope-20260930: baseline / candidate / deployed.
|
|
|
|
Prints hashes and status only; never reads chat content, patients or credentials.
|
|
"""
|
|
from pathlib import Path
|
|
import argparse, hashlib, json, subprocess, urllib.error, urllib.request
|
|
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('mode', choices=['baseline', 'candidate', 'deployed'])
|
|
args = parser.parse_args()
|
|
RELEASE = 'review-scope-20260930'
|
|
folder = Path(__file__).resolve().parent
|
|
project = Path('/opt/im-admin')
|
|
base = json.loads((folder / 'server-baseline.json').read_text())
|
|
plan = json.loads((folder / 'release-plan.json').read_text())
|
|
manifest = json.loads((folder / 'manifest.json').read_text())
|
|
payload_rows = [row for row in manifest if row['path'].startswith('payload/')]
|
|
frontend = plan['frontendDir']
|
|
added = [frontend + '/' + rel for rel in plan['frontendAdded']]
|
|
sha = lambda data: hashlib.sha256(data).hexdigest()
|
|
image = lambda ref: subprocess.check_output(['docker', 'image', 'inspect', ref, '--format', '{{.Id}}'], text=True).strip()
|
|
API = 'im-admin-api-1'
|
|
# 本次只重建 api;网关和知识库 worker 继续跑,部署前后核对它们没被动过。
|
|
UNTOUCHED = ['im-admin-gateway-1', 'im-admin-knowledge-worker-1']
|
|
|
|
# The unpacked bundle itself must be intact.
|
|
for row in manifest:
|
|
path = (folder / row['path']).resolve()
|
|
assert path.is_relative_to(folder), row['path']
|
|
assert path.stat().st_size == row['bytes'] and sha(path.read_bytes()) == row['sha256'], row['path']
|
|
|
|
# project-relative path -> expected sha256
|
|
if args.mode == 'baseline':
|
|
expected = dict(base['expected'])
|
|
else:
|
|
expected = {row['path'][len('payload/'):]: row['sha256'] for row in payload_rows}
|
|
|
|
HASHES = ('from pathlib import Path;import hashlib,json,sys;names=json.load(sys.stdin);'
|
|
'print(json.dumps({n:(hashlib.sha256((Path("/app")/n).read_bytes()).hexdigest() '
|
|
'if (Path("/app")/n).is_file() else None) for n in names}))')
|
|
|
|
|
|
def in_container(code, target, container=None, ref=None):
|
|
command = (['docker', 'run', '--rm', '-i', '--network=none', '--entrypoint', 'python', ref, '-c', code]
|
|
if ref else ['docker', 'exec', '-i', container, 'python', '-c', code])
|
|
return json.loads(subprocess.check_output(command, input=json.dumps(target).encode()))
|
|
|
|
|
|
def inspect(container):
|
|
raw = json.loads(subprocess.check_output(['docker', 'inspect', container]))[0]
|
|
return {'id': raw['Id'], 'image': raw['Image'], 'running': raw['State']['Running'],
|
|
'restarts': raw['RestartCount'], 'health': raw['State'].get('Health', {}).get('Status', 'not_configured')}
|
|
|
|
|
|
current = image('zyt/wecom-admin:current')
|
|
result = {'mode': args.mode, 'release': RELEASE, 'image': current}
|
|
|
|
if args.mode == 'baseline':
|
|
api = inspect(API)
|
|
assert api['image'] == current == base['images']['api'], 'api is not on the recorded current image'
|
|
assert api['running'] and api['health'] == 'healthy', 'api is not healthy'
|
|
others = {container: inspect(container) for container in UNTOUCHED}
|
|
for container, state in others.items():
|
|
assert state['running'], 'Not running: ' + container
|
|
result['api'] = api
|
|
result['others'] = others
|
|
for name in added:
|
|
assert not (project / name).exists(), 'Would overwrite an existing file: ' + name
|
|
|
|
if args.mode in ('baseline', 'deployed'):
|
|
for name, wanted in expected.items():
|
|
assert sha((project / name).read_bytes()) == wanted, 'Host drift: ' + name
|
|
actual = in_container(HASHES, sorted(expected), container=API)
|
|
assert actual == expected, 'Running api container differs from expected code'
|
|
result['files'] = len(expected)
|
|
|
|
if args.mode == 'candidate':
|
|
candidate = 'zyt/wecom-admin:' + RELEASE
|
|
actual = in_container(HASHES, sorted(expected), ref=candidate)
|
|
assert actual == expected, 'Candidate image differs from manifest'
|
|
result['candidate'] = image(candidate)
|
|
result['files'] = len(expected)
|
|
|
|
if args.mode == 'deployed':
|
|
wanted = image('zyt/wecom-admin:' + RELEASE)
|
|
assert current == wanted, 'current tag does not point at the release image'
|
|
state = inspect(API)
|
|
assert state['image'] == wanted and state['running'] and state['restarts'] == 0, state
|
|
assert state['health'] == 'healthy', state
|
|
recorded = folder / 'baseline-check.json'
|
|
if recorded.exists():
|
|
before = json.loads(recorded.read_text())['others']
|
|
for container in UNTOUCHED:
|
|
now = inspect(container)
|
|
assert now['id'] == before[container]['id'] and now['running'], 'Unrelated container changed: ' + container
|
|
result['others_unchanged'] = UNTOUCHED
|
|
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, url
|
|
entry = next(rel for rel in plan['frontendAdded'] if rel.startswith('jse/index-index-'))
|
|
with urllib.request.urlopen('http://127.0.0.1:18766/', timeout=15) as response:
|
|
assert entry.encode() in response.read(), 'admin index.html is not the new build'
|
|
# 配置接口仍然拒绝匿名访问;不做任何登录。
|
|
for path in ['/api/v2/config', '/api/v2/desktop/config']:
|
|
try:
|
|
urllib.request.urlopen('http://127.0.0.1:18766' + path, timeout=15)
|
|
except urllib.error.HTTPError as exc:
|
|
assert exc.code == 401, (path, exc.code)
|
|
else:
|
|
raise AssertionError('Accessible without authentication: ' + path)
|
|
# 本次行为在运行中的容器里直接核对(不读数据库)。
|
|
code = ("import json,admin_backend as b,admin_api as a;k='AI_REVIEW_EVERY_REPLY';"
|
|
"print(json.dumps({'key':k in b.CONFIG_KEYS,'bool':k in b.BOOL_KEYS,"
|
|
"'default':b.effective_config({})[k],'body':k in a.ConfigBody.model_fields}))")
|
|
behaviour = json.loads(subprocess.check_output(['docker', 'exec', '-i', API, 'python', '-c', code]))
|
|
assert behaviour == {'key': True, 'bool': True, 'default': False, 'body': True}, behaviour
|
|
result['behaviour'] = behaviour
|
|
|
|
result['status'] = 'passed'
|
|
print(json.dumps(result, ensure_ascii=False))
|