#!/usr/bin/env python3 """Real native subscriptions, each relay/exit, and saved-client revocation.""" import argparse,fcntl,gzip,hashlib,json,os,pathlib,secrets,socket,ssl,subprocess,time,urllib.error,urllib.parse,urllib.request BASE=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/launch-ready-20261105/client') BIN=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104/bin/sing-box') SHA='768d31fa7f68debc067bb4626539498a1e8751d36a7b99e1a54bee6a23815f93' SOCKS=19876;CONTROL=29090;UNIT='fuc-xb-launch-client' STARTED=False def digest(value):return hashlib.sha256(json.dumps(value,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest() def identity(c):return {'user_id':c['user_id'],'uuid_sha256':hashlib.sha256(c['qa_uuid'].encode()).hexdigest(),'phase':c['phase'],'manifest_sha256':c['manifest_sha256'],'nodes_sha256':digest({k:{'node_id':n['node_id'],'machine_id':n['machine_id'],'token_sha256':hashlib.sha256(n['machine_token'].encode()).hexdigest(),'spec':n['spec']}for k,n in c['nodes'].items()}),'binary_sha256':SHA} def binding(c,d): b=json.loads((d/'binding.json').read_text());assert b['identity']==identity(c)and time.time()-b['created_at']<3600,'Stale/foreign QA progress' assert hashlib.sha256(BIN.read_bytes()).hexdigest()==b['identity']['binary_sha256'],'Client binary changed since positive test' assert hashlib.sha256((d/'client-full.json').read_bytes()).hexdigest()==b['config_sha256']and hashlib.sha256((d/'controller.json').read_bytes()).hexdigest()==b['controller_sha256'],'Saved client configuration changed' return b def run(args,timeout=45):return subprocess.run(args,capture_output=True,timeout=timeout) def context(): p=run(['php',str(pathlib.Path(__file__).with_name('client-context.php'))]);assert p.returncode==0,'Client context unavailable' c=json.loads(p.stdout);assert c['owner']=='fuc-xb-launch-20261105'and len(c['nodes'])==22 return c def fetch(c,flag,token=None): # The staging gate is intentionally not embedded in subscriptions or clients. url=c['source']+'/api/v1/client/subscribe?'+urllib.parse.urlencode({'token':token if token is not None else c['subscribe_token'],'flag':flag}) req=urllib.request.Request(url,headers={'Cookie':'fuc_stage_access='+c['gate_cookie'],'User-Agent':'sing-box/1.14.3'if flag=='sing-box'else'clash.meta/1.19.32','Accept':'*/*'}) try:r=urllib.request.urlopen(req,timeout=30) except urllib.error.HTTPError as e:r=e with r: raw=r.read(8*1024*1024) if r.headers.get('Content-Encoding')=='gzip':raw=gzip.decompress(raw) return r.status,raw def api(c,path,params): if path.startswith('machine/'): req=urllib.request.Request(c['source']+'/api/v2/server/'+path,data=json.dumps(params).encode(),headers={'Accept':'application/json','Content-Type':'application/json'},method='POST') else:req=urllib.request.Request(c['source']+'/api/v2/server/'+path+'?'+urllib.parse.urlencode(params),headers={'Accept':'application/json'}) try:r=urllib.request.urlopen(req,timeout=25) except urllib.error.HTTPError as e:r=e with r:return r.status,r.read(2*1024*1024) def auth_matrix(c,empty=False): receipts=[];ids={n['node_id']for n in c['nodes'].values()} for key,n in c['nodes'].items(): args={'machine_id':n['machine_id'],'token':n['machine_token']} code,body=api(c,'machine/nodes',args);rows=json.loads(body).get('nodes',[]) assert code==200 and [x['id']for x in rows]==[n['node_id']],'Machine binding incorrect: '+key code,body=api(c,'user',{**args,'node_id':n['node_id']});users=json.loads(body).get('users',[]) assert code==200 and len(users)==(0 if empty else 1),'Unexpected native user list: '+key if not empty:assert int(users[0]['id'])==c['user_id'],'A migrated customer reached QA node' wrong=next(i for i in ids if i!=n['node_id']) assert api(c,'machine/nodes',{**args,'token':'deliberately-invalid'})[0]==403 assert api(c,'config',{**args,'node_id':wrong})[0]in [400,401,403] receipts.append({'key':key,'exact_owned_node':True,'available_users':len(users),'wrong_token_rejected':True,'unowned_node_rejected':True,'no_web_gate_cookie_used':True}) return receipts def prepare(c,d): assert hashlib.sha256(BIN.read_bytes()).hexdigest()==SHA,'Client binary drift' code,raw=fetch(c,'sing-box');assert code==200,'Native full subscription failed' cfg=json.loads(raw);proxies=[x for x in cfg['outbounds']if x.get('type')=='anytls'];assert len(proxies)==22,'Native node count mismatch' found={} for key,n in c['nodes'].items(): row=n['spec'];matches=[x for x in proxies if x['server']==row['relay_host']and x['server_port']==row['relay_port']];assert len(matches)==1,'Native route mismatch: '+key p=matches[0];assert p['password']==c['qa_uuid']and p['tls']['enabled']and p['tls'].get('insecure')is False and p['tls']['server_name']==row['sni'],'Native TLS/identity mismatch' found[key]=p['tag'] (d/'subscription-singbox.json').write_bytes(raw) code,clash=fetch(c,'meta');assert code==200 and b'anytls'in clash and c['qa_uuid'].encode()in clash,'Native Clash subscription failed';(d/'subscription-clash.yaml').write_bytes(clash) php=r"require '/var/www/wwwroot/fuc-xb-test/current/vendor/autoload.php';echo json_encode(Symfony\Component\Yaml\Yaml::parse(stream_get_contents(STDIN)));" parsed=subprocess.run(['php','-r',php],input=clash,capture_output=True,timeout=20);assert parsed.returncode==0,'Native Clash YAML parse failed' meta=json.loads(parsed.stdout);meta_nodes=[p for p in meta['proxies']if p.get('type')=='anytls'];assert len(meta_nodes)==22,'Clash Meta node count mismatch' for key,n in c['nodes'].items(): spec=n['spec'];matches=[p for p in meta_nodes if p['server']==spec['relay_host']and p['port']==spec['relay_port']];assert len(matches)==1,'Clash route mismatch: '+key p=matches[0];assert p['password']==c['qa_uuid']and p.get('skip-cert-verify',False)is False and p.get('sni')==spec['sni'],'Clash TLS/identity mismatch: '+key assert fetch(c,'sing-box','deliberately-invalid-subscription')[0]==403 if(d/'binding.json').exists(): old=binding(c,d);assert old['native_sha256']==hashlib.sha256(raw).hexdigest(),'Native subscription changed during resumed test' return {'native_full_config_checked':True,'binding':old,'resumed_same_configuration':True,'clash_meta_nodes_checked':22} cfg['inbounds']=[{'type':'mixed','tag':'qa-local','listen':'127.0.0.1','listen_port':SOCKS}] control_secret=secrets.token_hex(24);cfg.setdefault('experimental',{})['clash_api']={'external_controller':'127.0.0.1:'+str(CONTROL),'secret':control_secret,'default_mode':'global'} (d/'client-full.json').write_text(json.dumps(cfg,ensure_ascii=False));(d/'controller.json').write_text(json.dumps({'secret':control_secret,'tags':found})) checked=run([str(BIN),'check','-c',str(d/'client-full.json')]);(d/'config-check.stderr').write_bytes(checked.stderr) assert checked.returncode==0,'Native config rejected by real client; diagnostic private' b={'identity':identity(c),'created_at':int(time.time()),'native_sha256':hashlib.sha256(raw).hexdigest(),'config_sha256':hashlib.sha256((d/'client-full.json').read_bytes()).hexdigest(),'controller_sha256':hashlib.sha256((d/'controller.json').read_bytes()).hexdigest()};(d/'binding.json').write_text(json.dumps(b,indent=2)) return {'native_full_config_checked':True,'native_anytls_nodes':22,'all_tls_strict':True,'native_outbounds_dns_rules_retained':True,'only_inbounds_and_loopback_controller_changed':True,'invalid_subscription_rejected':True,'clash_meta_nodes_checked':22,'binding':b} def start(d): global STARTED STARTED=False for port in [SOCKS,CONTROL]:assert not run(['ss','-H','-ltn','sport = :'+str(port)]).stdout.strip(),'QA listener collision' p=run(['systemd-run','--quiet','--collect','--unit='+UNIT,'--description=FUC-XB launch restricted QA client','--property=RuntimeMaxSec=1200','--property=MemoryMax=384M','--property=CPUQuota=40%','--working-directory='+str(d),str(BIN),'run','-D',str(d),'-c',str(d/'client-full.json')]);assert p.returncode==0,'QA client did not start';STARTED=True for _ in range(50): try: with socket.create_connection(('127.0.0.1',CONTROL),timeout=.3):return except OSError:time.sleep(.2) raise RuntimeError('QA controller unavailable') def stop(): global STARTED if not STARTED:return props=run(['systemctl','show',UNIT,'-p','Description','-p','LoadState','-p','MainPID']).stdout.decode() state=dict(line.split('=',1)for line in props.splitlines()if '='in line) gone=state.get('LoadState')=='not-found'and state.get('MainPID')=='0' if not gone: assert state.get('Description')=='FUC-XB launch restricted QA client','QA unit ownership changed' assert run(['systemctl','stop',UNIT]).returncode==0,'QA client stop failed' for port in [SOCKS,CONTROL]:assert not run(['ss','-H','-ltn','sport = :'+str(port)]).stdout.strip(),'QA listener remains active' STARTED=False def select(d,key): c=json.loads((d/'controller.json').read_text());request=urllib.request.Request('http://127.0.0.1:'+str(CONTROL)+'/proxies/'+urllib.parse.quote('节点选择',safe=''),data=json.dumps({'name':c['tags'][key]},ensure_ascii=False).encode(),headers={'Authorization':'Bearer '+c['secret'],'Content-Type':'application/json'},method='PUT') with urllib.request.urlopen(request,timeout=10)as r:assert r.status in [200,204],'Client selector failed' def tls_alive(spec): with socket.create_connection((spec['relay_host'],spec['relay_port']),timeout=8)as raw: with ssl.create_default_context().wrap_socket(raw,server_hostname=spec['sni'])as tls:return tls.version() def network(c,d,revoked=False): b=binding(c,d) progress=d/('revoked-progress.json'if revoked else'network-progress.json') old=json.loads(progress.read_text())if progress.exists()else{'binding':b,'nodes':{}};assert old['binding']==b,'Progress belongs to another client';result=old['nodes'] assert set(result).issubset(c['nodes']),'Foreign progress' try: start(d) if revoked: with urllib.request.urlopen('https://api.ipify.org?format=json',timeout=12)as r:assert r.status==200 and json.loads(r.read()).get('ip'),'Public target health unavailable' for key,n in c['nodes'].items(): if key in result:continue select(d,key);spec=n['spec'];tls=tls_alive(spec) base=['curl','-sS','--proxy','socks5h://127.0.0.1:'+str(SOCKS),'--connect-timeout','5','--max-time','12'if revoked else'25'] ip=run(base+['https://api.ipify.org?format=json'],35) if revoked: (d/('rejected-'+key+'.stderr')).write_bytes(ip.stderr) assert ip.returncode in [35,52,56,97] and not ip.stdout,'No definite saved-client rejection: '+key row={'saved_config_rejected':True,'curl_exit':ip.returncode,'node_tls_still_alive':tls,'target_health_confirmed':True,'stderr_sha256':hashlib.sha256(ip.stderr).hexdigest()} else: assert ip.returncode==0 and json.loads(ip.stdout)['ip']==spec['expected_exit'],'Real exit mismatch: '+key down=run(base+['https://speed.cloudflare.com/__down?bytes=65536'],35);assert down.returncode==0 and len(down.stdout)==65536,'Download failed: '+key body=b'FUC-XB-QA-ONLY\n'*2048;(d/'upload.bin').write_bytes(body) up=run(base+['-H','Content-Type: application/octet-stream','--data-binary','@'+str(d/'upload.bin'),'https://httpbin.org/post'],35);assert up.returncode==0 and json.loads(up.stdout).get('data','').encode()==body,'Upload echo failed: '+key row={'actual_exit':spec['expected_exit'],'tls':tls,'download_bytes':len(down.stdout),'upload_bytes':len(body),'native_selector_used':True} result[key]=row;progress.write_text(json.dumps({'binding':b,'nodes':result},indent=2));print(json.dumps({'phase':c['phase'],'key':key,**row}),flush=True) finally:stop() return result def traffic(c,before): for _ in range(25): after=context();assert identity(after)==identity(c),'QA identity changed while waiting for reports' delta={k:{s:after['nodes'][k][s]-before['nodes'][k][s]for s in ['u','d']}for k in c['nodes']} user={s:after[s]-before[s]for s in ['u','d']};raw={s:sum(n[s]for n in delta.values())for s in ['u','d']} if not after['pending_traffic']and not after['pending_stat']and all(n['u']>0 and n['d']>0 for n in delta.values())and all(user[s]==2*raw[s]for s in ['u','d']): return {'all_22_nodes_reported_upload_download':True,'rate':2,'raw_bytes':raw,'rated_user_bytes':user,'native_user_and_server_counts_exact':True,'per_node_delta':delta} time.sleep(2) raise RuntimeError('Native traffic reports/rate not reconciled') def main(): os.umask(0o077);BASE.mkdir(mode=0o700,parents=True,exist_ok=True);lock=(BASE/'operation.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','run','revoked','api']);args=p.parse_args();c=context();d=BASE/c['phase'];d.mkdir(mode=0o700,parents=True,exist_ok=True) if args.action=='api':result={'phase':c['phase'],'authentication':auth_matrix(c,any(n['available_users']==0 for n in c['nodes'].values()))} elif args.action=='revoked': assert(d/'network-result.json').is_file(),'Positive test missing' positive=json.loads((d/'network-result.json').read_text());assert positive['binding']==binding(c,d),'Revocation configuration differs from positive test' code,_=fetch(c,'sing-box');assert code==(200 if c['phase']=='exhausted'else 403),'Unexpected native subscription status' result={'phase':c['phase'],'binding':binding(c,d),'subscription_status':code,'authentication':auth_matrix(c,True),'nodes':network(c,d,True),'temporary_client_stopped':True};(d/'revocation-result.json').write_text(json.dumps(result,indent=2)) else: assert not(d/'network-result.json').exists(),'Existing completed test; inspect rather than repeat' result=prepare(c,d);result['authentication']=auth_matrix(c) if args.action=='run': before_file=d/'traffic-before.json' if before_file.exists():before=json.loads(before_file.read_text());assert before['binding']==binding(c,d),'Traffic baseline changed' else: before={'binding':binding(c,d),'user_id':c['user_id'],'u':c['u'],'d':c['d'],'nodes':{k:{'u':n['u'],'d':n['d']}for k,n in c['nodes'].items()}};before_file.write_text(json.dumps(before,indent=2)) result.update(phase=c['phase'],nodes=network(c,d),temporary_client_stopped=True);result['traffic']=traffic(c,before);(d/'network-result.json').write_text(json.dumps(result,indent=2)) print(json.dumps({'passed':True,'phase':c['phase'],'action':args.action,'nodes_checked':len(result.get('nodes',result.get('authentication',[])))})) if __name__=='__main__':main()