111 lines
8.9 KiB
Python
111 lines
8.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Real native subscriptions, each relay/exit, and saved-client revocation."""
|
|
import argparse,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'
|
|
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):
|
|
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)
|
|
assert fetch(c,'sing-box','deliberately-invalid-subscription')[0]==403
|
|
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'
|
|
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_downloaded':True}
|
|
def start(d):
|
|
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,'--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'
|
|
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():assert run(['systemctl','stop',UNIT]).returncode==0,'QA client stop failed'
|
|
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):
|
|
progress=d/('revoked-progress.json'if revoked else'network-progress.json')
|
|
result=json.loads(progress.read_text())if progress.exists()else{}
|
|
assert set(result).issubset(c['nodes']),'Foreign progress'
|
|
start(d)
|
|
try:
|
|
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:
|
|
assert ip.returncode!=0 and not ip.stdout,'Saved revoked identity still connected: '+key
|
|
row={'saved_config_rejected':True,'node_tls_still_alive':tls}
|
|
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(result,indent=2));print(json.dumps({'phase':c['phase'],'key':key,**row}),flush=True)
|
|
finally:stop()
|
|
return result
|
|
def main():
|
|
os.umask(0o077);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'
|
|
code,_=fetch(c,'sing-box');assert code==(200 if c['phase']=='exhausted'else 403),'Unexpected native subscription status'
|
|
result={'phase':c['phase'],'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':result.update(phase=c['phase'],nodes=network(c,d),temporary_client_stopped=True);(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()
|