114 lines
7.8 KiB
Python
114 lines
7.8 KiB
Python
"""Private evaluation adapter. Never install as an OpenWebUI plugin."""
|
||
import asyncio,json,sqlite3,secrets,os,sys,time,hashlib,subprocess,shlex,re
|
||
from pathlib import Path
|
||
from types import SimpleNamespace
|
||
from aiohttp import web, ClientSession
|
||
from urllib.parse import urlparse
|
||
ROOT=Path('/tmp/strata-practice-20261011');ROOT.mkdir(exist_ok=True)
|
||
sys.path.insert(0,str(ROOT))
|
||
import orchestrator
|
||
from open_webui.models.users import Users
|
||
from open_webui.models.config import Config
|
||
from open_webui.models.tools import Tools as ToolsDB
|
||
TOKEN=(ROOT/'bridge.key').read_text().strip() if (ROOT/'bridge.key').exists() else secrets.token_hex(32); (ROOT/'bridge.key').write_text(TOKEN);os.chmod(ROOT/'bridge.key',0o600)
|
||
saved=json.loads((ROOT/'snapshot-private.json').read_text()) if (ROOT/'snapshot-private.json').exists() else {}
|
||
CACHE=saved.get('cache',{});ALLOW=set();AUDIT=saved.get('audit',[])
|
||
CACHE={k:v for k,v in CACHE.items() if not (k.startswith('terminal:yt-dlp') and '--skip-download' not in k and '--no-download' not in k)}
|
||
class MemRedis:
|
||
def __init__(self):self.d={}
|
||
async def get(self,k):return self.d.get(k)
|
||
async def set(self,k,v,*a,**kw):self.d[k]=v
|
||
async def main():
|
||
users=(await Users.get_users())['users'];admins=[u for u in users if u.role=='admin'];assert len(admins)==1;user=admins[0]
|
||
request=SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(redis=MemRedis(),EMBEDDING_FUNCTION=None)),state=SimpleNamespace(token=SimpleNamespace(credentials='')),cookies={},headers={})
|
||
engine=orchestrator.Tools();engine.valves=engine.Valves(**(await ToolsDB.get_tool_valves_by_id('tool_orchestrator') or {}));engine.valves.index_ttl_seconds=86400
|
||
engine.valves.enable_code_mode=True
|
||
await engine._ensure_index(request,user)
|
||
entries=await engine._accessible_entries(request,user)
|
||
c=sqlite3.connect('file:/app/backend/data/webui.db?mode=ro',uri=True);c.row_factory=sqlite3.Row
|
||
skills=[dict(r) for r in c.execute('select id,name,description,content from skill where is_active=1')]
|
||
row=c.execute("select specs from tool where id='tool_orchestrator'").fetchone();specs=json.loads(row['specs'])
|
||
global_cfg=await Config.get('ui.default_interface_settings') or {};system=global_cfg.get('system','')
|
||
terminal_connections=await Config.get('terminal_server.connections') or []
|
||
terminal=next(x for x in terminal_connections if '192.168.1.2:8099' in x.get('url',''))
|
||
terminal_session=ClientSession(headers={'Authorization':'Bearer '+terminal.get('key','')})
|
||
owned_processes={v['id']:k for k,v in CACHE.items() if k.startswith('terminal:') and isinstance(v,dict) and v.get('id')}
|
||
def safe_command(command):
|
||
try:a=shlex.split(command)
|
||
except ValueError:return None
|
||
if not a:return None
|
||
# Rebuild argv as escaped literal tokens; never execute supplied shell syntax.
|
||
if a[:2]==['python3','/home/user/Skripte/efa_bahn.py'] and len(a)>2 and a[2] in ['journeys','departures','stops','messages']:
|
||
if any(x.startswith('--') and x not in ['--origin','--destination','--date','--time','--limit','--station','--query','--stop','--format','--include-messages','--include-alerts'] for x in a[3:]):return None
|
||
return shlex.join(a)
|
||
if a[0]=='curl':
|
||
urls=[x for x in a[1:] if x.startswith('http')]
|
||
if len(urls)!=1:return None
|
||
u=urlparse(urls[0])
|
||
if u.hostname!='192.168.1.89' or u.port not in [None,80] or u.username or u.password:return None
|
||
if u.path not in ['/api/statusinfo','/api/timerlist','/api/getservices','/api/epgservice','/api/epgnow','/api/event','/api/about','/ajax/multiepg']:return None
|
||
if any(x in u.query.lower() for x in ['newstate','command','delete','add','zap']):return None
|
||
# Discard options except harmless GET flags; enforce timeout and no output file.
|
||
return shlex.join(['curl','--silent','--show-error','--max-time','10',urls[0]])
|
||
if a[0]=='yt-dlp':
|
||
urls=[x for x in a[1:] if x.startswith('https://www.youtube.com/')]
|
||
if len(urls)!=1:return None
|
||
if not any(x in a for x in ['--flat-playlist','--no-download','--skip-download']):return None
|
||
allowed={'--flat-playlist','--playlist-end','-J','--dump-single-json','--no-download','--skip-download','--print','--no-cache-dir','--socket-timeout','--no-warnings'}
|
||
if any(x.startswith('-') and x not in allowed for x in a[1:]):return None
|
||
if '--playlist-end' in a and int(a[a.index('--playlist-end')+1])>5:return None
|
||
return shlex.join(a+['--skip-download','--ignore-config','--no-cache-dir','--socket-timeout','10'])
|
||
return None
|
||
async def terminal_request(path,body=None):
|
||
async with terminal_session.request('POST' if body else 'GET',terminal['url'].rstrip('/')+path,json=body,timeout=75) as r:return await r.json()
|
||
original_invoke=engine._invoke
|
||
async def guarded(req,usr,sid,fn,args,meta):
|
||
key=json.dumps([sid,fn,args],sort_keys=True)
|
||
if (sid,fn) not in ALLOW:
|
||
AUDIT.append({'server':sid,'function':fn,'blocked':True});return {'error':'READ_ONLY_TEST: operation not allowlisted; prepare the requested change without execution.'}
|
||
if key not in CACHE:
|
||
CACHE[key]=await asyncio.wait_for(original_invoke(req,usr,sid,fn,args,meta),timeout=40)
|
||
AUDIT.append({'server':sid,'function':fn,'blocked':False,'key_sha256':hashlib.sha256(key.encode()).hexdigest()})
|
||
return CACHE[key]
|
||
engine._invoke=guarded
|
||
async def api(req):
|
||
if req.headers.get('Authorization')!='Bearer '+TOKEN:return web.json_response({'error':'unauthorized'},status=401)
|
||
if req.path=='/meta':return web.json_response({'specs':specs,'skills':skills,'system':system,'entries':[{'server_id':e.server_id,'function_name':e.name,'description':e.description,'parameters':e.parameters,'server_name':e.server_name} for e in entries]})
|
||
if req.path=='/stop':
|
||
asyncio.get_running_loop().call_later(1,lambda:os._exit(0));return web.json_response({'stopping':True})
|
||
if req.path=='/allow':
|
||
body=await req.json();ALLOW.update(tuple(x) for x in body['allow']);return web.json_response({'allowed':len(ALLOW)})
|
||
if req.path=='/snapshot':return web.json_response({'cache':CACHE,'audit':AUDIT})
|
||
body=await req.json();name=body['name'];args=body.get('arguments',{})
|
||
if name=='view_skill':
|
||
s=next((s for s in skills if s['id']==args.get('id')),None);result=s or {'error':'Skill not found'}
|
||
elif name in ['search_tools','list_servers','call_tool','run_tool_script']:
|
||
try:result=await asyncio.wait_for(getattr(engine,name)(**args,__request__=request,__user__=user.model_dump()),timeout=70)
|
||
except Exception as e:result={'error':type(e).__name__+': '+str(e)}
|
||
elif name=='run_command':
|
||
safe=safe_command(args.get('command',''))
|
||
if not safe:
|
||
AUDIT.append({'tool':'run_command','blocked':True})
|
||
result={'error':'READ_ONLY_TEST: command not allowed. Only EFA read queries, receiver GET statusinfo/timerlist/EPG, and yt-dlp metadata without downloads are permitted. No shell chaining.'}
|
||
else:
|
||
key='terminal:'+safe
|
||
if key not in CACHE:
|
||
result=await terminal_request('/execute?wait=60',{'command':safe})
|
||
if result.get('id'):owned_processes[result['id']]=key
|
||
CACHE[key]=result
|
||
result=CACHE[key]
|
||
AUDIT.append({'tool':'run_command','blocked':False,'key_sha256':hashlib.sha256(key.encode()).hexdigest()})
|
||
elif name=='get_process_status':
|
||
pid=args.get('id',args.get('process_id',''))
|
||
if pid not in owned_processes:result={'error':'READ_ONLY_TEST: only this test’s own process IDs may be read'}
|
||
else:
|
||
key=owned_processes[pid]
|
||
result=await terminal_request('/execute/'+pid+'/status?wait=20');CACHE[key]=result
|
||
else:result={'error':'READ_ONLY_TEST: unavailable tool'}
|
||
return web.json_response({'result':result})
|
||
app=web.Application(client_max_size=1024*1024);app.router.add_route('*','/{path:.*}',api)
|
||
runner=web.AppRunner(app,access_log=None);await runner.setup();await web.TCPSite(runner,'0.0.0.0',8098).start()
|
||
print(json.dumps({'ready':True,'entry_count':len(entries),'skill_count':len(skills)}),flush=True)
|
||
await asyncio.Event().wait()
|
||
asyncio.run(main())
|