test(fuc-xb): refresh-v2-node acceptance\n
This commit is contained in:
1 parent
6e09553f91
commit
6a7e941c8a
5 files changed
+251
No files matched your search
@@ -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()
|
||||
Reference in new issue
Block a user