feat(nodes): scope final acceptance to reviewed change impact

This commit is contained in:
hellcat committed 2026-10-20 16:07:49 +08:00
1 parent d085e211b3
commit 4d667f37b2
9 files changed
+191 -26

No files matched your search

+43 -9
View File
@@ -31,7 +31,30 @@ def snapshot(nodes):
return sorted(result, key=lambda n: n['id'])
def audit(before, after, report_bytes, qa_bytes, binding, plan_sha, expected_qas, now=None, ttl=900):
def validate_impact(impact):
if impact is None:
return
if not isinstance(impact, dict) or set(impact) != {'shared_changes', 'affected_snis', 'review'}:
raise ValueError('Explicit reviewed impact required')
if not isinstance(impact['review'], str) or not impact['review'].strip():
raise ValueError('Impact review reference required')
for key in ('shared_changes', 'affected_snis'):
if not isinstance(impact[key], list) or any(not isinstance(x, str) or not x.strip() for x in impact[key]) or len(set(impact[key])) != len(impact[key]):
raise ValueError('Invalid impact inventory')
def verification_scope(nodes, impact=None):
"""Unknown/shared impact keeps full tests; reviewed append uses light TLS probes."""
nodes = snapshot(nodes)
if impact is None:
return {n['tag']: 'full' for n in nodes}
validate_impact(impact)
if not set(impact['affected_snis']).issubset({n['sni'] for n in nodes}):
raise ValueError('Affected node absent from current authorization set')
return {n['tag']: 'full' if impact['shared_changes'] or n['sni'] in impact['affected_snis'] else 'tls' for n in nodes}
def audit(before, after, report_bytes, qa_bytes, binding, plan_sha, expected_qas, now=None, ttl=900, scope=None):
now = time.time() if now is None else now
before, after = snapshot(before), snapshot(after)
if before != after or binding.get('snapshot_sha256') != digest(before):
@@ -45,16 +68,27 @@ def audit(before, after, report_bytes, qa_bytes, binding, plan_sha, expected_qas
for stamp in (binding.get('verified_at'), report.get('verified_at'), qas.get('captured_at')):
if type(stamp) not in (int, float) or not 0 <= now-stamp <= ttl:
raise ValueError('Evidence expired or future dated')
modes = {n['tag']: 'full' for n in before} if scope is None else scope
if set(modes) != {n['tag'] for n in before} or any(v not in ('full', 'tls') for v in modes.values()):
raise ValueError('Incomplete verification scope')
if scope is not None and binding.get('scope_sha256') != digest(modes):
raise ValueError('Verification scope binding changed')
if report.get('state') != 'live_verified' or len(report.get('results', [])) != len(before):
raise ValueError('Incomplete live verification')
expected = {(n['tag'], n['relay'], n['relay_port'], n['sni'], n['expected_exit'], n['country']) for n in before}
actual = set()
for n in report['results']:
if n.get('live') is not True or n.get('strict_tls') is not True:
raise ValueError('Live strict TLS required for every node')
actual.add(tuple(n.get(k) for k in ('tag', 'relay', 'relay_port', 'sni', 'exit_ip', 'country')))
if actual != expected:
raise ValueError('Node/endpoint/exit/country mismatch')
actual = {}
for result in report['results']:
tag = result.get('tag')
if tag in actual or tag not in modes:
raise ValueError('Unexpected or duplicate verification result')
actual[tag] = result
for node in before:
result = actual.get(node['tag'], {})
if result.get('live') is not True or result.get('strict_tls') is not True or result.get('verification', 'full') != modes[node['tag']]:
raise ValueError('Required verification mode or strict TLS missing')
if any(result.get(k) != node[k] for k in ('relay', 'relay_port', 'sni')):
raise ValueError('Node endpoint mismatch')
if modes[node['tag']] == 'full' and (result.get('exit_ip') != node['expected_exit'] or result.get('country') != node['country']):
raise ValueError('Node exit/country mismatch')
if qas.get('plan_sha256') != plan_sha or set(qas.get('users', {})) != set(expected_qas):
raise ValueError('QA evidence identity mismatch')
for key, identity in expected_qas.items():
+1 -1
View File
@@ -11,7 +11,7 @@ from site_adapter import SiteAdapter
def configure(plan,site):
allowed={'ops_root','node_root','batch_backup_root','node_backup_root','qa_root','provider_snapshot','exit_registry','ssh_config','preserved_service','formal_socks_port','gateway_containers','client_sha256'}
allowed={'ops_root','node_root','batch_backup_root','node_backup_root','qa_root','provider_snapshot','exit_registry','ssh_config','preserved_service','formal_socks_port','gateway_containers','client_sha256','acceptance_impact'}
if set(site)-allowed:raise ValueError('Unexpected site configuration fields')
library=importlib.import_module('paramiko')
if library.__version__!='5.0.0':raise ValueError('Use the reviewed Paramiko 5.0.0 environment')
+10 -7
View File
@@ -3,7 +3,7 @@ import base64,hashlib,json,os,shlex,threading,time
from pathlib import Path
from types import SimpleNamespace
from ssh_pool import Pool,private_json
from acceptance import audit,digest,snapshot,service_change,provider_state
from acceptance import audit,digest,snapshot,service_change,provider_state,verification_scope,validate_impact
class SiteAdapter:
def __init__(self,plan,directory,pool=None,atomic_writer=None,resource_lock=None):
@@ -17,6 +17,7 @@ class SiteAdapter:
value=self.ctx.get(field,'')
if not isinstance(value,str) or not value.startswith('/') or '..' in value.split('/') or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_./-' for c in value):
raise ValueError('Explicit safe absolute site path required: '+field)
validate_impact(self.ctx.get('acceptance_impact'))
config=private_json(self.ctx['ssh_config'])
for candidate in plan['nodes']:
if config['hosts'].get(candidate['vps_id'],{}).get('host')!=candidate['node_address']:raise ValueError('SSH target differs from frozen candidate address')
@@ -162,19 +163,21 @@ print(json.dumps({'unit_sha256':h(v['FragmentPath']),'binary_sha256':h(s['binary
values.append(dict(item,**self.exit_registry[item['sni']]))
return snapshot(values)
before=public(source)
owned=self.formal_done.get(group,{}).get('owned',source.get('owned',False))
scope=verification_scope(before,None if owned else ctx.get('acceptance_impact'))
# Do not run final verification while any candidate in this group is still isolated.
cohort=[x for x in self.plan['nodes'] if x['formal_group_id']==group]
wanted={(x['relay_host'],x['relay_port'],x['tls_domain']) for x in cohort}
if not wanted.issubset({(x['relay'],x['relay_port'],x['sni']) for x in before}):raise RuntimeError('formal_group_not_ready')
if group in self.formal_done:
prior=self.formal_done[group]
return audit(prior['before'],before,prior['report'],prior['qas'],prior['binding'],digest(self.plan),prior['expected_qas'])
return audit(prior['before'],before,prior['report'],prior['qas'],prior['binding'],digest(self.plan),prior['expected_qas'],scope=scope)
root=ctx['qa_root']+'/formal-group-'+str(group)
execute(gateway,'install -d -m 700 '+root)
expectations=[]
for node in before:
original=next(x for x in source['nodes'] if x['id']==node['id'])
expectations.append({'tag':node['tag'],'host':node['relay'],'port':node['relay_port'],'sni':node['sni'],'uuid':original['uuid'],'expected_exit':node['expected_exit'],'expected_country':node['country']})
expectations.append({'tag':node['tag'],'host':node['relay'],'port':node['relay_port'],'sni':node['sni'],'uuid':original['uuid'],'expected_exit':node['expected_exit'],'expected_country':node['country'],'verification':scope[node['tag']]})
# Tokens/UUIDs never leave memory except the gateway's private task files.
write(gateway,root+'/source-private.json',json.dumps({'token':source['token'],'expectations':expectations,'owned':source['owned']}))
script="""import gzip,json,urllib.request,subprocess,os,time
@@ -225,12 +228,12 @@ for attempt in range(3 if source['owned'] else 1):
if o.channel.recv_exit_status():raise RuntimeError('qa_rejection_probe_failed')
users[key]={'id':value['id'],'banned':value['banned'],'excluded':value['excluded'],'http_status':int(out.strip())}
qas=json.dumps({'users':users,'captured_at':int(time.time()),'plan_sha256':digest(self.plan)},sort_keys=True).encode()
binding={'plan_sha256':digest(self.plan),'snapshot_sha256':digest(before),'report_sha256':hashlib.sha256(report).hexdigest(),'qa_rejections_sha256':hashlib.sha256(qas).hexdigest(),'verified_at':int(time.time())}
audit(before,after,report,qas,binding,digest(self.plan),identities)
binding={'plan_sha256':digest(self.plan),'snapshot_sha256':digest(before),'report_sha256':hashlib.sha256(report).hexdigest(),'qa_rejections_sha256':hashlib.sha256(qas).hexdigest(),'verified_at':int(time.time()),'scope_sha256':digest(scope)}
audit(before,after,report,qas,binding,digest(self.plan),identities,scope=scope)
write(gateway,root+'/qa-rejections.json',qas);write(gateway,root+'/binding.json',json.dumps(binding));write(gateway,root+'/snapshot.json',json.dumps(before))
self.formal_done[group]={'before':before,'report':report,'qas':qas,'binding':binding,'expected_qas':identities}
self.formal_done[group]={'before':before,'report':report,'qas':qas,'binding':binding,'expected_qas':identities,'owned':owned}
# Persist only nonsecret, byte-bound results for coordinator/operator review.
self.atomic_json(self.directory/('formal-group-'+str(group)+'.json'),{'snapshot':before,'report':json.loads(report),'qas':json.loads(qas),'binding':binding})
self.atomic_json(self.directory/('formal-group-'+str(group)+'.json'),{'snapshot':before,'verification_scope':scope,'report':json.loads(report),'qas':json.loads(qas),'binding':binding})
def qa_evidence(self,n,raw,state):
# Bind the exact remote bytes, not a re-serialized nested report. Persist the latest
+21 -2
View File
@@ -14,6 +14,7 @@ import os
from pathlib import Path
import shutil
import socket
import ssl
import subprocess
import tempfile
import time
@@ -53,6 +54,7 @@ def validate(config, expectations, exact=True):
except ValueError as exc:
raise VerificationError('Invalid expected exit IP') from exc
require(len(spec['expected_country']) == 2 and spec['expected_country'].isalpha() and spec['expected_country'].isupper(), 'Expected country must be two uppercase letters')
require(spec.get('verification', 'full') in ('full', 'tls'), 'Unsupported verification mode')
tag = spec['tag']
require(tag in nodes and tag not in selected, 'Missing/duplicate selected node')
node = nodes[tag]
@@ -151,6 +153,23 @@ def run_node(config, spec, binary, port, diagnostic_dir):
stop(proc)
def run_tls(spec):
"""Reach the relay and validate the node certificate; no exit/traffic claim."""
context = ssl.create_default_context()
with socket.create_connection((spec['host'], spec['port']), timeout=10) as stream:
with context.wrap_socket(stream, server_hostname=spec['sni']) as secure:
protocol = secure.version()
require(protocol in ('TLSv1.2', 'TLSv1.3'), 'Unexpected TLS protocol')
return {'tag': spec['tag'], 'strict_tls': True, 'live': True,
'relay': spec['host'], 'relay_port': spec['port'], 'sni': spec['sni'],
'verification': 'tls', 'node_tls': protocol}
def run_specs(config, specs, binary, port, folder):
return [run_tls(spec) if spec.get('verification', 'full') == 'tls'
else run_node(config, spec, binary, port, folder) for spec in specs]
def write_report(path, report):
destination = Path(path)
require(destination.parent.is_dir() and destination.parent.stat().st_mode & 0o077 == 0,
@@ -212,6 +231,7 @@ def main():
specs = [{'tag': candidates[0]['tag'], 'host': qa.get('host'), 'port': qa.get('port'),
'sni': qa.get('sni'), 'uuid': qa.get('uuid'), 'expected_exit': args.expected_exit,
'expected_country': args.expected_country}]
require(bool(args.expectations) or all(s.get('verification', 'full') == 'full' for s in specs), 'Isolated QA requires full verification')
tags = validate(config, specs, exact=bool(args.expectations))
results = []
if args.run:
@@ -219,8 +239,7 @@ def main():
binary = str(Path(args.binary).resolve())
folder = Path(source).resolve().parent
require(folder.stat().st_mode & 0o077 == 0, 'Live diagnostics directory must be private')
for spec in specs:
results.append(run_node(config, spec, binary, args.port, str(folder)))
results = run_specs(config, specs, binary, args.port, str(folder))
report = {'state': 'live_verified' if args.run else 'structure_validated',
'verified_at': int(time.time()) if args.run else None,
'qa_user_id': qa_user_id, 'selected_nodes': tags, 'results': results,