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

+84 -3
View File
@@ -13,7 +13,7 @@ from unittest.mock import patch
SCRIPTS=Path(__file__).resolve().parents[2]/'scripts/node-onboarding'
sys.path.insert(0,str(SCRIPTS))
from acceptance import audit,digest,snapshot,service_change,provider_state
from acceptance import audit,digest,snapshot,service_change,provider_state,verification_scope
from ssh_pool import Pool,private_json,credentials
import batch
@@ -81,6 +81,71 @@ class EvidenceTests(unittest.TestCase):
self.assertEqual(service_change(before,dict(before,active=False)),'conflict')
self.assertEqual(service_change(before,dict(before,binary_sha256=None)),'unknown')
class ImpactAcceptanceTests(unittest.TestCase):
fixture=EvidenceTests.fixture
check=EvidenceTests.check
def scoped(self, nodes, report, qas, scope, after=None, binding_scope=None):
raw=json.dumps(report).encode();qa_raw=json.dumps(qas).encode()
binding=dict(plan_sha256='plan',snapshot_sha256=digest(snapshot(nodes)),report_sha256=hashlib.sha256(raw).hexdigest(),qa_rejections_sha256=hashlib.sha256(qa_raw).hexdigest(),verified_at=1000,scope_sha256=digest(scope if binding_scope is None else binding_scope))
return audit(nodes,nodes if after is None else after,raw,qa_raw,binding,'plan',{'new':9},now=1100,scope=scope)
def test_unknown_and_shared_impact_require_full_while_append_uses_tls(self):
nodes,report,qas=self.fixture(7)
review={'shared_changes':[],'affected_snis':[],'review':'task/impact-review.json'}
self.assertEqual(set(verification_scope(nodes).values()),{'full'})
self.assertEqual(set(verification_scope(nodes,review).values()),{'tls'})
self.assertEqual(set(verification_scope(nodes,dict(review,shared_changes=['subscription renderer'])).values()),{'full'})
scope=verification_scope(nodes,dict(review,affected_snis=[nodes[0]['sni']]))
self.assertEqual(scope['node-1'],'full');self.assertEqual(scope['node-7'],'tls')
for bad in [{},dict(review,review=''),dict(review,affected_snis=['unknown.invalid']),dict(review,shared_changes='none')]:
with self.assertRaises(ValueError):verification_scope(nodes,bad)
def test_light_results_cannot_claim_exit_and_do_not_skip_set_or_qa_checks(self):
nodes,report,qas=self.fixture(7)
scope={n['tag']:'tls' for n in nodes}
for result in report['results']:
result['verification']='tls';result.pop('exit_ip');result.pop('country')
self.assertEqual(self.scoped(nodes,report,qas,scope)['nodes'],7)
with self.assertRaises(ValueError):self.scoped(nodes,report,qas,scope,after=nodes[:-1])
with self.assertRaises(ValueError):self.scoped(nodes,dict(report,results=report['results'][:-1]),qas,scope)
with self.assertRaises(ValueError):self.scoped(nodes,report,qas,scope,binding_scope={'node-1':'tls'})
wrong=copy.deepcopy(qas);wrong['users']['new']['banned']=False
with self.assertRaises(ValueError):self.scoped(nodes,report,wrong,scope)
full=dict(scope,**{'node-1':'full'})
with self.assertRaises(ValueError):self.scoped(nodes,report,qas,full)
with self.assertRaises(ValueError):self.check(nodes,report,qas) # Old/default audits remain full.
def test_mixed_scope_requires_full_exit_validation_only_where_affected(self):
nodes,report,qas=self.fixture(2);scope={'node-1':'full','node-2':'tls'}
report['results'][1].update(verification='tls');report['results'][1].pop('exit_ip');report['results'][1].pop('country')
self.assertEqual(self.scoped(nodes,report,qas,scope)['nodes'],2)
report['results'][0]['exit_ip']='198.51.100.10'
with self.assertRaises(ValueError):self.scoped(nodes,report,qas,scope)
class ProbeDispatchTests(unittest.TestCase):
def verifier(self):
spec=importlib.util.spec_from_file_location('scope_verifier',SCRIPTS/'verify-node.py')
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module);return module
def test_mixed_probes_dispatch_without_starting_client_for_tls_nodes(self):
verifier=self.verifier();specs=[{'tag':'old','verification':'tls'},{'tag':'affected'}]
with patch.object(verifier,'run_tls',return_value={'verification':'tls'}) as light,patch.object(verifier,'run_node',return_value={'live':True}) as full:
self.assertEqual(len(verifier.run_specs({},specs,'binary',19080,'private')),2)
light.assert_called_once_with(specs[0]);full.assert_called_once_with({},specs[1],'binary',19080,'private')
def test_tls_probe_checks_hostname_and_emits_no_exit_claim(self):
from unittest.mock import MagicMock
verifier=self.verifier();context=MagicMock();stream=MagicMock()
context.wrap_socket.return_value.__enter__.return_value.version.return_value='TLSv1.3'
with patch.object(verifier.ssl,'create_default_context',return_value=context),patch.object(verifier.socket,'create_connection',return_value=stream):
report=verifier.run_tls({'tag':'old','host':'relay.invalid','port':1234,'sni':'node.invalid'})
self.assertEqual(context.wrap_socket.call_args.kwargs['server_hostname'],'node.invalid')
self.assertEqual(report['verification'],'tls');self.assertNotIn('exit_ip',report);self.assertNotIn('country',report)
with patch.object(verifier.ssl,'create_default_context',return_value=context),patch.object(verifier.socket,'create_connection',side_effect=OSError('offline')):
with self.assertRaises(OSError):verifier.run_tls({'host':'relay.invalid','port':1234,'sni':'node.invalid'})
class TransportTests(unittest.TestCase):
def test_reuse_and_every_nonwhite_host_has_jump(self):
calls=[]
@@ -224,18 +289,19 @@ class SiteAdapterTests(unittest.TestCase):
exported=json.loads((Path(d)/'new-evidence.json').read_text());self.assertEqual(exported['report_sha256'],hashlib.sha256(raw).hexdigest());self.assertEqual(exported['panel']['d'],34)
self.assertEqual(remotes['panel'].files['/backups/new/qa-report.json'],raw)
def test_formal_source_snapshot_audit_and_cached_audit_call_chain(self):
def test_formal_source_snapshot_audit_and_cached_audit_call_chain(self, impact=None, owned=False):
import contextlib
import io
from site_adapter import SiteAdapter
adapter=object.__new__(SiteAdapter)
ctx=dict(gateway_vps='gateway',qa_root='/qa',ops_root='/ops',subscription_url='https://sub.example.invalid',client_binary='/client',formal_socks_port=19999,node_backup_root='/backups',batch_backup_root='/batch')
if impact is not None:ctx['acceptance_impact']=impact
candidate=dict(key='new',formal_group_id=7,relay_host='relay.example.invalid',relay_port=47002,tls_domain='n2.example.invalid')
adapter.plan={'context':ctx,'nodes':[candidate]};adapter.ctx=ctx
adapter.directory=Path('/private/tmp/formal-chain-fixture/ledger/batch')
adapter.lock=threading.RLock();adapter.resource_lock=lambda *args:contextlib.nullcontext()
adapter.formal_done={};adapter.exit_registry={f'n{i}.example.invalid':dict(expected_exit=f'192.0.2.{i}',country='JP') for i in [1,2]}
source={'user_id':1,'owned':False,'token':'fixture-only','nodes':[dict(id=i,type='anytls',tag='node-'+str(i),relay='relay.example.invalid',relay_port=47000+i,sni=f'n{i}.example.invalid',uuid='fixture-only') for i in [1,2]]}
source={'user_id':1,'owned':owned,'token':'fixture-only','nodes':[dict(id=i,type='anytls',tag='node-'+str(i),relay='relay.example.invalid',relay_port=47000+i,sni=f'n{i}.example.invalid',uuid='fixture-only') for i in [1,2]]}
accounts=[]
def account_command(group,action,apply=False,client=None):
accounts.append(action)
@@ -243,6 +309,12 @@ class SiteAdapterTests(unittest.TestCase):
adapter.account_command=account_command
now=int(time.time())
raw=json.dumps({'state':'live_verified','verified_at':now,'results':[dict(tag='node-'+str(i),relay='relay.example.invalid',relay_port=47000+i,sni=f'n{i}.example.invalid',exit_ip=f'192.0.2.{i}',country='JP',live=True,strict_tls=True) for i in [1,2]]}).encode()
expected_scope=verification_scope([dict(x,**adapter.exit_registry[x['sni']]) for x in source['nodes']],None if owned else impact)
payload=json.loads(raw)
for result in payload['results']:
if expected_scope[result['tag']]=='tls':
result['verification']='tls';result.pop('exit_ip');result.pop('country')
raw=json.dumps(payload).encode()
files={};persisted=[];programs=[]
def execute(client,command,timeout=120):
if command.startswith("python3 - <<'DPLFORMAL'\n"):
@@ -269,6 +341,9 @@ class SiteAdapterTests(unittest.TestCase):
adapter.formal(candidate,None,gateway,php,execute,lambda client,path:files.get(path),write)
self.assertEqual(len(programs),1)
self.assertEqual(len(persisted),1)
self.assertEqual(persisted[0]['verification_scope'],expected_scope)
private=json.loads(files['/qa/formal-group-7/source-private.json'])
self.assertEqual({n['tag']:n['verification'] for n in private['expectations']},expected_scope)
self.assertEqual(len(persisted[0]['snapshot']),2,'The old node must remain in complete acceptance')
self.assertTrue(all(n['type']=='anytls' for n in persisted[0]['snapshot']))
self.assertEqual(persisted[0]['qas']['users']['new']['http_status'],403)
@@ -276,6 +351,12 @@ class SiteAdapterTests(unittest.TestCase):
self.assertEqual(adapter.formal(candidate,None,gateway,php,execute,lambda client,path:files.get(path),write)['nodes'],2)
self.assertEqual(len(programs),1,'A cached audit rechecks topology without rerunning the client')
def test_reviewed_append_formal_chain_uses_light_checks_and_preserves_all_nodes(self):
self.test_formal_source_snapshot_audit_and_cached_audit_call_chain({'shared_changes':[],'affected_snis':[],'review':'task/review'})
def test_owned_formal_account_forces_full_tests_even_for_reviewed_append(self):
self.test_formal_source_snapshot_audit_and_cached_audit_call_chain({'shared_changes':[],'affected_snis':[],'review':'task/review'},owned=True)
def test_preserved_service_review_binds_original_and_exact_observation(self):
from site_adapter import SiteAdapter
adapter=object.__new__(SiteAdapter);adapter.ctx={'preserved_service':dict(unit='XrayR',binary='/bin/xrayr',config='/etc/xrayr.yml',port=443)}