test(fuc-xb): refresh-v2-node acceptance\n

This commit is contained in:
hellcat committed 2026-11-05 10:05:39 +08:00
1 parent 6e09553f91
commit 6a7e941c8a
5 files changed
+251

No files matched your search

+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""Real native subscription import and SOCKS traffic; no local desktop/TUN changes."""
import argparse,copy,gzip,hashlib,json,os,pathlib,socket,ssl,subprocess,time,urllib.error,urllib.parse,urllib.request
DIR=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/refresh-20261105/client')
BIN=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104/bin/sing-box')
SHA='768d31fa7f68debc067bb4626539498a1e8751d36a7b99e1a54bee6a23815f93'
PANEL=str(pathlib.Path(__file__).with_name('node-panel.php'))
def run(a,timeout=30):return subprocess.run(a,capture_output=True,timeout=timeout)
def context():
p=run(['php',PANEL,'export']);assert p.returncode==0
return json.loads(p.stdout)
def redact(s,c):
for k in ['machine_token','gate_cookie','subscribe_token','qa_uuid']:s=s.replace(str(c[k]),'<redacted>')
return s[:1200]
def fetch(c,flag,token=None):
url=c['alias']+'/api/v1/client/subscribe?'+urllib.parse.urlencode({'token':token if token is not None else c['subscribe_token'],'flag':flag})
r=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.0'})
try:
with urllib.request.urlopen(r,timeout=25)as o:
b=o.read(4194304);h=o.headers
if h.get('Content-Encoding')=='gzip':b=gzip.decompress(b)
return o.status,b
except urllib.error.HTTPError as e:return e.code,e.read(1024)
def prepare(c):
assert hashlib.sha256(BIN.read_bytes()).hexdigest()==SHA,'Client artifact changed'
status,raw=fetch(c,'sing-box');assert status==200,'Native subscription request failed'
cfg=json.loads(raw);nodes=[o for o in cfg['outbounds'] if o.get('type')=='anytls']
assert len(nodes)==1,'Expected exact QA-only AnyTLS subscription'
n=nodes[0];assert n['server']==c['expected_exit'] and n['server_port']==c['port'] and n['password']==c['qa_uuid'],'Native subscription identity mismatch'
assert n['tls']['enabled'] and n['tls'].get('insecure') is False and n['tls']['server_name']==c['sni'],'Strict subscription TLS mismatch'
(DIR/'subscription-singbox.json').write_bytes(raw)
status,clash=fetch(c,'meta');assert status==200 and b'anytls' in clash and c['qa_uuid'].encode() in clash,'Native Clash subscription missing QA node'
(DIR/'subscription-clash.yaml').write_bytes(clash)
assert fetch(c,'sing-box','invalid-qa-token')[0]==403,'Invalid subscription token accepted'
cfg['inbounds']=[{'type':'mixed','tag':'qa-local','listen':'127.0.0.1','listen_port':19876}]
(DIR/'client-full.json').write_text(json.dumps(cfg))
check=run([str(BIN),'check','-c',str(DIR/'client-full.json')])
result={'native_subscription_downloaded':True,'exact_qa_node_and_uuid':True,'strict_tls_in_subscription':True,'invalid_token_rejected':True,'clash_native_format_present':True,'only_inbounds_replaced':True,'native_full_config_check_passed':check.returncode==0}
if check.returncode:result['check_error']=redact(check.stderr.decode(errors='replace'),c)
(DIR/'client-prepare-result.json').write_text(json.dumps(result,indent=2))
return result,cfg
def saved_rejection(c):
assert (DIR/'client-full.json').exists(),'No saved positive client configuration'
ctx=ssl.create_default_context();result={}
def alive():
with socket.create_connection((c['expected_exit'],c['port']),timeout=8)as raw:
with ctx.wrap_socket(raw,server_hostname=c['sni'])as tls:return tls.version()
result['node_tls_before']=alive()
cmd=['systemd-run','--quiet','--collect','--unit=fuc-xb-qa-client','--property=RuntimeMaxSec=90','--property=MemoryMax=384M','--working-directory='+str(DIR),str(BIN),'run','-D',str(DIR),'-c',str(DIR/'client-full.json')]
assert run(cmd).returncode==0,'Saved client unit failed'
try:
ready=False
for _ in range(50):
try:
with socket.create_connection(('127.0.0.1',19876),timeout=.2):ready=True;break
except OSError:time.sleep(.2)
assert ready,'Saved client failed to start'
p=run(['curl','-sS','--proxy','socks5h://127.0.0.1:19876','--connect-timeout','5','--max-time','12','https://api.ipify.org?format=json'],timeout=20)
result['saved_config_rejected']=p.returncode!=0 and not p.stdout
result['node_tls_after']=alive();assert result['saved_config_rejected'],'Revoked credential still connects'
finally:
run(['systemctl','stop','fuc-xb-qa-client']);result['temporary_client_stopped']=True
(DIR/('revocation-'+c['phase']+'.json')).write_text(json.dumps(result,indent=2))
return result
def main():
os.umask(0o077);DIR.mkdir(mode=0o700,parents=True,exist_ok=True);p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','run','revoked']);args=p.parse_args();c=context()
if args.action=='revoked':
status,_=fetch(c,'sing-box');assert status==403,'Revoked subscription still accepted';result=saved_rejection(c);result.update(disabled_qa_subscription_status=status,phase=c['phase']);print(json.dumps(result));return
result,cfg=prepare(c)
if args.action=='prepare' or not result['native_full_config_check_passed']:print(json.dumps(result));return
assert c['expected_exit']=='193.111.31.52'
# A positive TLS handshake is independently verified before starting the application client.
ctx=ssl.create_default_context()
with socket.create_connection((c['expected_exit'],c['port']),timeout=8)as raw:
with ctx.wrap_socket(raw,server_hostname=c['sni'])as tls:result['node_certificate_verified']=True;result['node_tls_version']=tls.version()
s=socket.socket()
try:s.bind(('127.0.0.1',19876))
finally:s.close()
cmd=['systemd-run','--quiet','--collect','--unit=fuc-xb-qa-client','--property=RuntimeMaxSec=600','--property=MemoryMax=384M','--property=CPUQuota=30%','--working-directory='+str(DIR),str(BIN),'run','-D',str(DIR),'-c',str(DIR/'client-full.json')]
started=run(cmd);assert started.returncode==0,'QA client unit failed'
try:
ready=False
for _ in range(50):
try:
with socket.create_connection(('127.0.0.1',19876),timeout=.2):ready=True;break
except OSError:time.sleep(.2)
if not ready:
log=run(['journalctl','-u','fuc-xb-qa-client','-n','8','--no-pager'])
result['client_start_error']=redact(log.stdout.decode(errors='replace'),c)
raise RuntimeError('Native full client did not start')
base=['curl','-sS','--proxy','socks5h://127.0.0.1:19876','--connect-timeout','8','--max-time','25']
ip=run(base+['https://api.ipify.org?format=json'],timeout=30)
assert ip.returncode==0 and json.loads(ip.stdout)['ip']==c['expected_exit'],'Wrong real proxy exit'
result['actual_proxy_exit_matches']=True;result['expected_exit']=c['expected_exit']
down=run(base+['https://speed.cloudflare.com/__down?bytes=65536'],timeout=30)
assert down.returncode==0 and len(down.stdout)==65536,'Real download payload mismatch'
result['download_payload_bytes']=len(down.stdout)
(DIR/'upload-qa.bin').write_bytes(b'FUC-XB-QA-ONLY\n'*2048)
up=run(base+['-H','Content-Type: application/octet-stream','--data-binary','@'+str(DIR/'upload-qa.bin'),'https://httpbin.org/post'],timeout=30)
assert up.returncode==0 and len(json.loads(up.stdout).get('data',''))==len((DIR/'upload-qa.bin').read_bytes()),'Real upload echo mismatch'
result['upload_payload_bytes']=len((DIR/'upload-qa.bin').read_bytes())
result['real_client_network_passed']=True
finally:
run(['systemctl','stop','fuc-xb-qa-client'])
result['temporary_client_stopped']=True
(DIR/'client-run-result.json').write_text(json.dumps(result,indent=2))
print(json.dumps(result))
if __name__=='__main__':main()
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Loopback staging gate transport; retains native V2 machine-token authentication."""
import http.server,json,pathlib,ssl,threading,urllib.request,urllib.error,urllib.parse
DIR=pathlib.Path('/var/www/wwwroot/fuc-xb-acceptance/private/v2-20261105')
ALLOWED={'/api/v2/server/'+x for x in ['handshake','config','user','report','push','alive','alivelist','status','machine/nodes','machine/status']}
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self,*a,**kw):return None
def allowed(method,path,payload,content_type,cfg):
p=urllib.parse.urlsplit(path)
if p.scheme or p.netloc or p.path not in ALLOWED or method not in ['GET','POST']:return False
try:
q=urllib.parse.parse_qs(p.query,keep_blank_values=True)
body=json.loads(payload)if payload and content_type.startswith('application/json')else urllib.parse.parse_qs(payload.decode())if payload else{}
def value(key):
vals=[]
for d in [q,body]:
if key in d:vals+=d[key]if isinstance(d[key],list)else[d[key]]
return [str(x)for x in vals]
if value('machine_id')!=[str(cfg['machine_id'])]or value('token')!=[cfg['machine_token']]:return False
node=value('node_id')
return node==[str(cfg['node_id'])]or(not node and p.path in ['/api/v2/server/handshake','/api/v2/server/machine/nodes','/api/v2/server/machine/status'])
except(ValueError,TypeError,UnicodeError):return False
def main():
cfg=json.loads((DIR/'context.json').read_text());assert cfg['source']=='https://fuc-xb-test.gemcook.net'
op=urllib.request.build_opener(urllib.request.HTTPSHandler(context=ssl.create_default_context()),NoRedirect());metrics={'requests':{},'user_counts':[]};lock=threading.Lock()
class H(http.server.BaseHTTPRequestHandler):
def log_message(self,*a):pass
def do_GET(self):self.forward()
def do_POST(self):self.forward()
def forward(self):
length=int(self.headers.get('Content-Length','0'))
if self.client_address[0]!='127.0.0.1'or length<0 or length>2097152:self.send_error(403);return
b=self.rfile.read(length)if length else b'';content=self.headers.get('Content-Type','')
if not allowed(self.command,self.path,b,content,cfg):
with lock:metrics['scope_rejections']=metrics.get('scope_rejections',0)+1;(DIR/'bridge-metrics.json').write_text(json.dumps(metrics))
self.send_error(403);return
headers={'Cookie':'fuc_stage_access='+cfg['gate_cookie'],'Accept':'application/json'}
if content:headers['Content-Type']=content
if self.headers.get('If-None-Match'):headers['If-None-Match']=self.headers['If-None-Match']
try:
req=urllib.request.Request(cfg['source']+self.path,data=b if self.command=='POST'else None,headers=headers,method=self.command)
try:res=op.open(req,timeout=15)
except urllib.error.HTTPError as e:res=e
with res:status=res.status;body=res.read(2097153);rh=res.headers
if len(body)>2097152:raise ValueError('Oversized response')
path=urllib.parse.urlsplit(self.path).path
with lock:
key=path+':'+str(status);metrics['requests'][key]=metrics['requests'].get(key,0)+1
if path.endswith('/user')and status==200:metrics['user_counts']=(metrics['user_counts']+[len(json.loads(body)['users'])])[-20:]
(DIR/'bridge-metrics.json').write_text(json.dumps(metrics))
self.send_response(status)
for k in ['Content-Type','ETag']:
if rh.get(k):self.send_header(k,rh[k])
self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
except Exception:self.send_response(502);self.send_header('Content-Length','0');self.end_headers()
http.server.ThreadingHTTPServer(('127.0.0.1',28766),H).serve_forever()
if __name__=='__main__':main()
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
import pathlib,subprocess,json,os,hashlib,time,argparse
BASE=pathlib.Path('/var/www/wwwroot/fuc-xb-acceptance');DIR=BASE/'private/v2-20261105';BIN='/opt/dpl-node/xboard-node'
SHA='55bf71fa9d9f2048d3255ae7c0af929a41897ca7743f6ead34132a6ca4c79043'
def run(a):
p=subprocess.run(a,capture_output=True,text=True,timeout=40);assert p.returncode==0,'QA command failed';return p.stdout.strip()
def free(port):return not run(['ss','-H','-ltn','sport = :'+str(port)])
def baseline():
return {'dpl_pid':run(['systemctl','show','dpl-node','-p','MainPID','--value']),'xrayr_pid':run(['systemctl','show','XrayR','-p','MainPID','--value']),'binary_sha256':hashlib.sha256(pathlib.Path(BIN).read_bytes()).hexdigest(),'unit_sha256':hashlib.sha256(run(['systemctl','cat','dpl-node']).encode()).hexdigest()}
def main():
os.umask(0o077);p=argparse.ArgumentParser();p.add_argument('action',choices=['start','status','stop']);args=p.parse_args();DIR.mkdir(mode=0o700,parents=True,exist_ok=True)
if args.action=='start':
assert free(25443)and free(28766);assert not(DIR/'before.json').exists(),'Already started; inspect before retry'
before=baseline();assert before['binary_sha256']==SHA and before['dpl_pid']=='110612'and before['xrayr_pid']=='107692';(DIR/'before.json').write_text(json.dumps(before))
c=json.loads((DIR/'context.json').read_text());assert c['expected_exit']=='193.111.31.52'and c['port']==25443
cfg={'panel':{'url':'http://127.0.0.1:28766'},'machine':{'machine_id':c['machine_id'],'token_env':'FUC_XB_TEST_MACHINE_TOKEN'},'kernel':{'type':'singbox','config_dir':str(DIR/'kernel')},'log':{'level':'info'},'runtime':{'gomemlimit':'256MiB','gogc':75},'node':{'push_interval':5,'pull_interval':5}}
(DIR/'config.json').write_text(json.dumps(cfg));(DIR/'node-secret.env').write_text('FUC_XB_TEST_MACHINE_TOKEN='+c['machine_token']+'\n')
run(['systemd-run','--quiet','--collect','--unit=fuc-xb-v2-qa-api','--property=RuntimeMaxSec=1800','--property=MemoryMax=96M','/usr/bin/python3',str(pathlib.Path(__file__).with_name('node-bridge.py'))])
for _ in range(30):
if not free(28766):break
time.sleep(.2)
assert not free(28766)
run(['systemd-run','--quiet','--collect','--unit=fuc-xb-v2-qa-node','--property=RuntimeMaxSec=1800','--property=MemoryMax=384M','--property=CPUQuota=30%','--property=EnvironmentFile='+str(DIR/'node-secret.env'),'--working-directory='+str(DIR),BIN,'-c',str(DIR/'config.json')])
print(json.dumps({'started':True,'program':'Xboard-Node','native_v2_machine_interface':True,'binary_matches_dpl_hn':True,'original_unchanged':baseline()==before}))
elif args.action=='status':
before=json.loads((DIR/'before.json').read_text());print(json.dumps({'node_active':run(['systemctl','show','fuc-xb-v2-qa-node','-p','ActiveState','--value']),'api_active':run(['systemctl','show','fuc-xb-v2-qa-api','-p','ActiveState','--value']),'node_listening':not free(25443),'metrics':json.loads((DIR/'bridge-metrics.json').read_text())if(DIR/'bridge-metrics.json').exists()else{},'original_unchanged':before==baseline()}))
else:
for unit in ['fuc-xb-v2-qa-node','fuc-xb-v2-qa-api']:subprocess.run(['systemctl','stop',unit],capture_output=True,timeout=40)
assert free(25443)and free(28766);before=json.loads((DIR/'before.json').read_text());assert before==baseline()
for name in ['context.json','node-secret.env','config.json']:(DIR/name).unlink(missing_ok=True)
# Generated kernel configs contain only synthetic QA credentials; remove them as well.
import shutil
shutil.rmtree(DIR/'kernel',ignore_errors=True)
print(json.dumps({'stopped':True,'temporary_listeners_absent':True,'copied_credentials_removed':True,'original_unchanged':True}))
if __name__=='__main__':main()
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);umask(0077);ini_set('display_errors','0');
$root='/var/www/wwwroot/fuc-xb-test/current';$dir='/var/www/wwwroot/fuc-xb-test/private/refresh-20261105';$stateFile=$dir.'/node-v2-state.json';
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';require $root.'/vendor/autoload.php';$a=require $root.'/bootstrap/app.php';$a->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
use Illuminate\Support\Facades\{DB,Cache};use App\Models\{User,Server,ServerMachine,ServerGroup};
if(DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong database');
$action=$argv[1]??'';
function qaV2($group,$phase):User{return User::create(['email'=>'qa-v2-'.$phase.'[email protected]','password'=>password_hash(bin2hex(random_bytes(20)),PASSWORD_BCRYPT),'uuid'=>(string)Illuminate\Support\Str::uuid(),'token'=>bin2hex(random_bytes(16)),'group_id'=>$group,'transfer_enable'=>104857600,'expired_at'=>time()+3600,'banned'=>0,'balance'=>0,'u'=>0,'d'=>0,'device_limit'=>1,'speed_limit'=>10,'remind_expire'=>0,'remind_traffic'=>0]);}
if($action==='setup'){
if(file_exists($stateFile)||Server::count()||ServerMachine::count())throw new RuntimeException('Fixture collision');
$before=['users'=>User::count(),'groups'=>ServerGroup::count(),'nodes'=>Server::count(),'machines'=>ServerMachine::count(),'wallet'=>(int)User::sum('balance')];
$state=['before'=>$before,'settings'=>DB::table('v2_settings')->whereIn('name',['server_push_interval','server_pull_interval'])->get()->map(fn($x)=>(array)$x)->all(),'users'=>[]];
DB::transaction(function()use(&$state,$stateFile){
$g=ServerGroup::create(['name'=>'FUC-XB V2 QA 20261105']);$m=ServerMachine::create(['name'=>'fuc-xb-v2-qa-20261105','token'=>ServerMachine::generateToken(),'is_active'=>true,'notes'=>'Isolated QA only; no production users']);
$n=Server::create(['name'=>'FUC-XB V2 QA JP02 (temporary)','type'=>'anytls','host'=>'193.111.31.52','port'=>'25443','server_port'=>'25443','group_ids'=>[(string)$g->id],'route_ids'=>[],'tags'=>[],'rate'=>1,'show'=>true,'enabled'=>true,'machine_id'=>$m->id,'sort'=>9999,'protocol_settings'=>['tls'=>['server_name'=>'jp02.gembox-dns.com','allow_insecure'=>false]],'cert_config'=>['cert_mode'=>'file','domain'=>'jp02.gembox-dns.com','cert_file'=>'/etc/letsencrypt/live/jp02.gembox-dns.com/fullchain.pem','key_file'=>'/etc/letsencrypt/live/jp02.gembox-dns.com/privkey.pem']]);
$u=qaV2($g->id,'banned');$state+=['group_id'=>$g->id,'machine_id'=>$m->id,'node_id'=>$n->id,'current_user_id'=>$u->id,'phase'=>'banned'];$state['users'][]=$u->id;
app(App\Support\Setting::class)->save(['server_pull_interval'=>5,'server_push_interval'=>5]);file_put_contents($stateFile,json_encode($state));
});
echo json_encode(['isolated_setup'=>true,'native_interface'=>'api/v2/server','machine_auth'=>true,'node_type'=>'anytls','production_users_on_node'=>0]).PHP_EOL;exit;
}
$s=json_decode(file_get_contents($stateFile),true,512,JSON_THROW_ON_ERROR);$n=Server::findOrFail($s['node_id']);$m=ServerMachine::findOrFail($s['machine_id']);$u=User::findOrFail($s['current_user_id']);
if($n->name!=='FUC-XB V2 QA JP02 (temporary)'||$m->name!=='fuc-xb-v2-qa-20261105')throw new RuntimeException('Fixture identity changed');
if($action==='probe'){echo json_encode(['phase'=>$s['phase'],'available_users'=>App\Services\ServerService::getAvailableUsers($n)->count(),'qa_upload'=>$u->u,'qa_download'=>$u->d,'node_upload'=>$n->u,'node_download'=>$n->d,'last_check_at'=>$n->last_check_at,'last_push_at'=>$n->last_push_at,'machine_last_seen'=>$m->last_seen_at,'online'=>$n->online]).PHP_EOL;exit;}
if($action==='revoke'){
if($s['phase']==='banned')$u->update(['banned'=>1]);elseif($s['phase']==='expired')$u->update(['expired_at'=>time()-1]);elseif($s['phase']==='exhausted')$u->update(['u'=>$u->transfer_enable]);else throw new RuntimeException('Unknown phase');
echo json_encode(['phase'=>$s['phase'],'available_users'=>App\Services\ServerService::getAvailableUsers($n)->count(),'empty_list'=>App\Services\ServerService::getAvailableUsers($n)->isEmpty()]).PHP_EOL;exit;
}
if($action==='next'){
if(App\Services\ServerService::getAvailableUsers($n)->count())throw new RuntimeException('Revoke first');$phase=($s['phase']==='banned'?'expired':($s['phase']==='expired'?'exhausted':null));if(!$phase)throw new RuntimeException('No next phase');
$u->update(['banned'=>1]);$new=qaV2($s['group_id'],$phase);$s['phase']=$phase;$s['current_user_id']=$new->id;$s['users'][]=$new->id;file_put_contents($stateFile,json_encode($s));echo json_encode(['phase'=>$phase,'new_identity'=>true,'old_qa_remains_disabled'=>true]).PHP_EOL;exit;
}
if($action==='work'){ $before=Illuminate\Support\Facades\Queue::size('traffic_fetch')+Illuminate\Support\Facades\Queue::size('stat');if($before>100)throw new RuntimeException('Unexpected backlog');Illuminate\Support\Facades\Artisan::call('queue:work',['connection'=>'redis','--queue'=>'traffic_fetch,stat','--stop-when-empty'=>true,'--max-time'=>25,'--tries'=>1,'--sleep'=>1]);echo json_encode(['traffic_pending'=>Illuminate\Support\Facades\Queue::size('traffic_fetch'),'stat_pending'=>Illuminate\Support\Facades\Queue::size('stat')]).PHP_EOL;exit;}
if($action==='export'){$g=json_decode(file_get_contents('/var/www/wwwroot/fuc-xb-test/private/gate-credentials.json'),true);echo json_encode(['machine_id'=>$m->id,'machine_token'=>$m->token,'node_id'=>$n->id,'gate_cookie'=>$g['cookie_token'],'qa_uuid'=>$u->uuid,'subscribe_token'=>$u->token,'source'=>'https://fuc-xb-test.gemcook.net','alias'=>'https://fuc-xb-test.tomtojapan.online','port'=>25443,'sni'=>'jp02.gembox-dns.com','node_tag'=>$n->name,'phase'=>$s['phase'],'expected_exit'=>'193.111.31.52']);exit;}
if($action==='cleanup'){
if(App\Services\ServerService::getAvailableUsers($n)->count())throw new RuntimeException('Revoke first');
DB::transaction(function()use($s,$n,$m){foreach($s['users']as$id){foreach(['v2_stat_user','v2_traffic_reset_logs','fuc_vip_entries','fuc_vip_accounts']as$t)DB::table($t)->where('user_id',$id)->delete();DB::table('personal_access_tokens')->where('tokenable_id',$id)->delete();app(App\Services\DeviceStateService::class)->removeNodeDevices($n->id,$id);Illuminate\Support\Facades\Redis::srem('traffic:pending_check',(string)$id);User::whereKey($id)->delete();}DB::table('v2_stat_server')->where('server_id',$n->id)->where('server_type','anytls')->delete();DB::table('v2_server_machine_load_history')->where('machine_id',$m->id)->delete();$n->delete();$m->delete();ServerGroup::whereKey($s['group_id'])->delete();DB::table('v2_settings')->whereIn('name',['server_pull_interval','server_push_interval'])->delete();foreach($s['settings']as$row)DB::table('v2_settings')->insert($row);});Cache::store('redis')->forget(App\Support\Setting::CACHE_KEY);
$after=['users'=>User::count(),'groups'=>ServerGroup::count(),'nodes'=>Server::count(),'machines'=>ServerMachine::count(),'wallet'=>(int)User::sum('balance')];echo json_encode(['cleanup'=>true,'baseline_restored'=>$after===$s['before']]).PHP_EOL;exit;
}
throw new RuntimeException('Unknown action');
+12
View File
@@ -0,0 +1,12 @@
import importlib.util,pathlib,json,unittest
s=importlib.util.spec_from_file_location('v2bridge',pathlib.Path(__file__).with_name('node-bridge.py'));b=importlib.util.module_from_spec(s);s.loader.exec_module(b)
class Scope(unittest.TestCase):
def setUp(self):self.c={'machine_id':7,'node_id':9,'machine_token':'synthetic'}
def test_machine_discovery(self):self.assertTrue(b.allowed('POST','/api/v2/server/machine/nodes',json.dumps({'machine_id':7,'token':'synthetic'}).encode(),'application/json',self.c))
def test_exact_node(self):self.assertTrue(b.allowed('GET','/api/v2/server/user?machine_id=7&node_id=9&token=synthetic',b'','',self.c))
def test_reject_other_machine_node_token_and_duplicates(self):
for q in ['machine_id=8&node_id=9&token=synthetic','machine_id=7&node_id=8&token=synthetic','machine_id=7&node_id=9&token=wrong','machine_id=7&machine_id=7&node_id=9&token=synthetic','machine_id=7&token=synthetic']:
self.assertFalse(b.allowed('GET','/api/v2/server/user?'+q,b'','',self.c))
def test_reject_other_paths_and_methods(self):
for method,path in [('DELETE','/api/v2/server/user'),('GET','/api/v2/admin/user'),('POST','https://other.invalid/api/v2/server/machine/nodes')]:self.assertFalse(b.allowed(method,path,json.dumps({'machine_id':7,'token':'synthetic'}).encode(),'application/json',self.c))
if __name__=='__main__':unittest.main()