mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-27 23:59:20 -05:00
152 lines
6.3 KiB
Python
152 lines
6.3 KiB
Python
"""Authenticated outbound connections from Tether."""
|
|
|
|
import asyncio
|
|
import json
|
|
from contextlib import suppress
|
|
from types import SimpleNamespace
|
|
from uuid import uuid4
|
|
|
|
from fastapi import APIRouter, WebSocket
|
|
from open_webui.models.auth_sessions import AuthSessions
|
|
from open_webui.utils.auth import decode_token, get_verified_user_by_token
|
|
from open_webui.utils.tether import hub, encode, decode
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.websocket('/connect')
|
|
async def connect(ws: WebSocket):
|
|
await ws.accept()
|
|
connection = None
|
|
watcher = None
|
|
try:
|
|
hello = json.loads(await asyncio.wait_for(ws.receive_text(), 10))
|
|
if hello.get('type') != 'hello' or hello.get('version') != 1:
|
|
raise ValueError('Unsupported Tether handshake')
|
|
token = hello.get('token', '')
|
|
user = await get_verified_user_by_token(token, getattr(ws.app.state, 'redis', None))
|
|
claims = decode_token(token)
|
|
if not user or not claims or not claims.get('sid') or claims.get('typ') != 'session':
|
|
raise ValueError('A renewable human session is required')
|
|
row = await AuthSessions.get(claims['sid'])
|
|
if not row or row.user_id != user.id or row.refresh_token_id is None:
|
|
raise ValueError('Invalid session')
|
|
connection_id = row.data.get('connection_id')
|
|
if not connection_id:
|
|
raise ValueError('A Tether connection ID is required')
|
|
await hub.start()
|
|
presence = {
|
|
'connection': str(uuid4()),
|
|
'worker': hub.worker,
|
|
'session': row.id,
|
|
'user': user.id,
|
|
'connection_id': connection_id,
|
|
}
|
|
connection = SimpleNamespace(ws=ws, presence=presence, routes={}, lock=asyncio.Lock())
|
|
|
|
async def send(header, data):
|
|
async with connection.lock:
|
|
await asyncio.wait_for(ws.send_bytes(encode(header, data)), 10)
|
|
|
|
connection.send = send
|
|
# A reconnect replaces the previous connection, including on another worker.
|
|
for old in list(hub.connections.values()):
|
|
if old.presence['user'] == user.id and old.presence['connection_id'] == connection_id:
|
|
await old.ws.close(code=1000)
|
|
hub.connections[presence['connection']] = connection
|
|
key = hub.key(user.id, connection_id)
|
|
record = json.dumps(presence)
|
|
if hub.redis:
|
|
await hub.redis.set(key, record, ex=60)
|
|
await ws.send_json({'type': 'ready'})
|
|
|
|
async def watch():
|
|
while True:
|
|
await asyncio.sleep(15)
|
|
current = await get_verified_user_by_token(token, getattr(ws.app.state, 'redis', None))
|
|
if not current or current.id != user.id:
|
|
await ws.close(code=4001)
|
|
return
|
|
if hub.redis:
|
|
refreshed = await hub.redis.eval(
|
|
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('expire', KEYS[1], 60) else return 0 end",
|
|
1,
|
|
key,
|
|
record,
|
|
)
|
|
if not refreshed:
|
|
await ws.close(code=1000)
|
|
return
|
|
|
|
async def guarded_watch():
|
|
try:
|
|
await watch()
|
|
except Exception:
|
|
with suppress(Exception):
|
|
await ws.close(code=4001)
|
|
|
|
watcher = asyncio.create_task(guarded_watch())
|
|
while True:
|
|
message = await ws.receive()
|
|
if message['type'] == 'websocket.disconnect':
|
|
break
|
|
if message.get('bytes') is not None:
|
|
header, data = decode(message['bytes'])
|
|
await hub.returned(connection, header, data)
|
|
elif message.get('text') is not None:
|
|
update = json.loads(message['text'])
|
|
updated = decode_token(update.get('token', ''))
|
|
current = await get_verified_user_by_token(
|
|
update.get('token', ''), getattr(ws.app.state, 'redis', None)
|
|
)
|
|
if (
|
|
update.get('type') != 'auth'
|
|
or not current
|
|
or current.id != user.id
|
|
or not updated
|
|
or updated.get('sid') != row.id
|
|
or updated.get('typ') != 'session'
|
|
):
|
|
raise ValueError('Cannot change relay identity')
|
|
token = update['token']
|
|
except Exception:
|
|
with suppress(Exception):
|
|
await ws.close(code=4001)
|
|
finally:
|
|
if watcher:
|
|
watcher.cancel()
|
|
await asyncio.gather(watcher, return_exceptions=True)
|
|
if connection:
|
|
hub.connections.pop(connection.presence['connection'], None)
|
|
if hub.redis:
|
|
with suppress(Exception):
|
|
await hub.redis.eval(
|
|
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",
|
|
1,
|
|
key,
|
|
record,
|
|
)
|
|
for stream_id in list(connection.routes):
|
|
stream = hub.streams.get(stream_id)
|
|
if stream:
|
|
stream.fail('Tether disconnected; operation completion may be unknown')
|
|
else:
|
|
worker = connection.routes[stream_id]
|
|
if hub.redis:
|
|
# An explicit failure is terminal even if a preceding frame was lost.
|
|
with suppress(Exception):
|
|
await hub.redis.publish(
|
|
hub.channel(worker),
|
|
encode(
|
|
{
|
|
'type': 'error',
|
|
'stream': stream_id,
|
|
'sequence': 0,
|
|
'route': 'stream',
|
|
'connection': connection.presence['connection'],
|
|
'message': 'Tether disconnected',
|
|
},
|
|
b'',
|
|
),
|
|
)
|