Files
kefu/deploy/perm-button-20261008/server-bundle/remote_server_guard.py
T
2026-11-16 09:39:42 +08:00

207 lines
11 KiB
Python
Raw 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.
"""Read-only checks for perm-button-20261008: baseline / candidate / deployed / backup.
Prints hashes, counts and status only; never reads chat content, knowledge text, patients, users or credentials.
`backup` dumps the three RBAC tables (role codes/names, permission codes, grants) to rbac-before.json.
`deployed` checks that every role kept every grant it had and gained exactly the button codes split from codes it held.
"""
from pathlib import Path
import argparse, hashlib, json, os, subprocess, urllib.error, urllib.request
parser = argparse.ArgumentParser()
parser.add_argument('mode', choices=['baseline', 'candidate', 'deployed', 'backup'])
args = parser.parse_args()
RELEASE = 'perm-button-20261008'
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()
SERVICES = {'api': 'im-admin-api-1', 'gateway': 'im-admin-gateway-1', 'knowledge-worker': 'im-admin-knowledge-worker-1'}
HEALTHCHECKED = {'api', 'gateway'}
# 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}
backend_expected = {k: v for k, v in expected.items() if k.startswith('wechat_rpa/')}
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'], 'started': raw['State']['StartedAt'],
'restarts': raw['RestartCount'], 'health': raw['State'].get('Health', {}).get('Status', 'not_configured')}
def healthy(name, state):
return state['running'] and (state['health'] == 'healthy' if name in HEALTHCHECKED else True)
# RBAC 表的只读快照(只碰 roles、permissions、role_permissions 三张表)
RBAC_DUMP = r'''
import json, sqlite3
db = sqlite3.connect("file:/data/backend.db?mode=ro", uri=True)
def rows(sql):
cur = db.execute(sql); cols = [c[0] for c in cur.description]
return [dict(zip(cols, r)) for r in cur.fetchall()]
print(json.dumps({"roles": rows("SELECT * FROM roles"), "permissions": rows("SELECT * FROM permissions"),
"role_permissions": rows("SELECT * FROM role_permissions")}, ensure_ascii=False))
'''
def rbac_dump():
raw = subprocess.check_output(['docker', 'exec', '-i', SERVICES['api'], 'python', '-c', RBAC_DUMP])
return raw, json.loads(raw)
def grants_of(dump):
out = {}
for row in dump['role_permissions']:
out.setdefault(row['role_code'], set()).add(row['permission_code'])
return out
current = image('zyt/wecom-admin:current')
result = {'mode': args.mode, 'release': RELEASE, 'image': current}
if args.mode == 'backup':
target = folder / 'rbac-before.json'
assert not target.exists(), 'backup already taken'
raw, data = rbac_dump()
fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'wb') as handle:
handle.write(raw)
result['backup'] = {key: len(value) for key, value in data.items()}
result['backup_sha256'] = sha(raw)
result['status'] = 'passed'
print(json.dumps(result, ensure_ascii=False))
raise SystemExit(0)
if args.mode == 'baseline':
states = {name: inspect(container) for name, container in SERVICES.items()}
for name, state in states.items():
assert state['image'] == base['images'][name], f'{name} is not on the recorded image'
assert healthy(name, state), 'Not healthy: ' + name
assert states['api']['image'] == current, 'current tag moved'
result['services'] = states
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=SERVICES['api'])
assert actual == expected, 'Running api container differs from expected code'
if args.mode == 'deployed':
for service in ('gateway', 'knowledge-worker'):
actual = in_container(HASHES, sorted(backend_expected), container=SERVICES[service])
assert actual == backend_expected, f'Running {service} 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'
states = {}
for service, container in SERVICES.items():
state = inspect(container)
assert state['image'] == wanted and state['restarts'] == 0 and healthy(service, state), (service, state)
states[service] = state
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'
# 改了权限判断的接口不登录一律 401。不尝试登录。
for method, path in [('GET', '/api/v2/permissions'), ('POST', '/api/v2/roles'), ('DELETE', '/api/v2/roles/x'),
('GET', '/api/v2/users'), ('PUT', '/api/v2/users/1'), ('POST', '/api/v2/models'),
('POST', '/api/v2/models/test'), ('POST', '/api/v2/agents'),
('POST', '/api/v2/release/package/prepare'), ('GET', '/api/v2/archive/storage'),
('POST', '/api/v2/archive/exports'), ('POST', '/api/v2/knowledge/items/x/reject'),
('POST', '/api/v2/knowledge/search'), ('PUT', '/api/v2/knowledge/settings')]:
request = urllib.request.Request('http://127.0.0.1:18766' + path, method=method,
data=b'{}' if method in ('POST', 'PUT') else None,
headers={'Content-Type': 'application/json'})
try:
urllib.request.urlopen(request, 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,rbac,knowledge_review as r;"
"print(json.dumps({'total':len(rbac.PERMISSION_CODES),"
"'implied':{p.code:list(p.implied_by) for p in rbac.PERMISSIONS if p.implied_by},"
"'review':sorted(r.REVIEW_PERMISSIONS)}))")
behaviour = {}
for service, container in SERVICES.items():
behaviour[service] = json.loads(subprocess.check_output(['docker', 'exec', '-i', container, 'python', '-c', code]))
assert behaviour['api'] == behaviour['gateway'] == behaviour['knowledge-worker'], behaviour
behaviour = behaviour['api']
assert behaviour['total'] == 65, behaviour['total']
assert behaviour['review'] == ['im:content:read', 'knowledge:read', 'knowledge:review:auto'], behaviour['review']
# 授权:每个角色原有的授权一条不少;新增的恰好是「它持有的旧码拆出来的按钮码」;管理员持有全部
before_dump = json.loads((folder / 'rbac-before.json').read_text())
before = grants_of(before_dump)
before_codes = {row['code'] for row in before_dump['permissions']}
_, now_dump = rbac_dump()
now = grants_of(now_dump)
codes = {row['code']: row['source'] for row in now_dump['permissions']}
assert sum(1 for source in codes.values() if source == 'builtin') == 65, 'builtin count'
assert 'discovered' not in codes.values(), [c for c, s in codes.items() if s == 'discovered']
assert set(before) == set(now), 'roles changed'
# 只有这次新登记的码会按旧码补授(已有的码,比如 release:read、role:read,seed 不会再动)
implied = {code: sources for code, sources in behaviour['implied'].items() if code not in before_codes}
assert len(set(codes) - before_codes) == 37, sorted(set(codes) - before_codes)
report = {}
for role, had in before.items():
assert had <= now[role], (role, sorted(had - now[role]))
if role == 'admin':
assert now[role] == set(codes), 'admin is missing codes'
continue
want = set(had)
for _ in range(3): # 链式补授(user:read → role:read → permission:read)
want |= {code for code, sources in implied.items() if set(sources) & want}
assert now[role] == want, (role, sorted(now[role] ^ want))
report[role] = {'before': len(had), 'after': len(now[role])}
assert not [row for row in now_dump['role_permissions'] if row['permission_code'] not in codes], 'orphan grants'
logs = subprocess.run(['docker', 'logs', '--since', states['knowledge-worker']['started'], SERVICES['knowledge-worker']],
capture_output=True, text=True)
assert '知识加工 Worker 已启动' in logs.stdout + logs.stderr and 'Traceback' not in logs.stdout + logs.stderr, \
'knowledge worker did not start cleanly'
for service in ('api', 'gateway'):
logs = subprocess.run(['docker', 'logs', '--since', states[service]['started'], SERVICES[service]],
capture_output=True, text=True)
assert 'Traceback' not in logs.stdout + logs.stderr, service + ' logged a traceback after the switch'
result['rbac'] = {'builtin': 65, 'roles': report}
result['status'] = 'passed'
print(json.dumps(result, ensure_ascii=False))