|
| 1 | +"""Reverse proxy for admin-configured terminal servers. |
| 2 | +
|
| 3 | +Routes: |
| 4 | + GET / — list terminals the user has access to |
| 5 | + * /{server_id}/{path:path} — proxy request to terminal server |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | + |
| 10 | +import aiohttp |
| 11 | +from fastapi import APIRouter, Depends, Request, Response |
| 12 | +from fastapi.responses import JSONResponse, StreamingResponse |
| 13 | +from starlette.background import BackgroundTask |
| 14 | + |
| 15 | +from open_webui.utils.auth import get_verified_user |
| 16 | +from open_webui.utils.access_control import has_connection_access |
| 17 | +from open_webui.models.groups import Groups |
| 18 | + |
| 19 | +log = logging.getLogger(__name__) |
| 20 | + |
| 21 | +router = APIRouter() |
| 22 | + |
| 23 | +STREAMING_CONTENT_TYPES = ("application/octet-stream", "image/", "application/pdf") |
| 24 | +STRIPPED_RESPONSE_HEADERS = frozenset( |
| 25 | + ("transfer-encoding", "connection", "content-encoding", "content-length") |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +@router.get("/") |
| 30 | +async def list_terminal_servers(request: Request, user=Depends(get_verified_user)): |
| 31 | + """Return terminal servers the authenticated user has access to.""" |
| 32 | + connections = request.app.state.config.TERMINAL_SERVER_CONNECTIONS or [] |
| 33 | + user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user.id)} |
| 34 | + |
| 35 | + return [ |
| 36 | + {"id": connection.get("id", ""), "url": connection.get("url", ""), "name": connection.get("name", "")} |
| 37 | + for connection in connections |
| 38 | + if has_connection_access(user, connection, user_group_ids) |
| 39 | + ] |
| 40 | + |
| 41 | + |
| 42 | +PROXY_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"] |
| 43 | + |
| 44 | + |
| 45 | +@router.api_route("/{server_id}/{path:path}", methods=PROXY_METHODS) |
| 46 | +async def proxy_terminal( |
| 47 | + server_id: str, |
| 48 | + path: str, |
| 49 | + request: Request, |
| 50 | + user=Depends(get_verified_user), |
| 51 | +): |
| 52 | + """Proxy a request to the admin terminal server identified by *server_id*.""" |
| 53 | + connections = request.app.state.config.TERMINAL_SERVER_CONNECTIONS or [] |
| 54 | + connection = next((c for c in connections if c.get("id") == server_id), None) |
| 55 | + |
| 56 | + if connection is None: |
| 57 | + return JSONResponse({"error": f"Terminal server '{server_id}' not found"}, status_code=404) |
| 58 | + |
| 59 | + user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user.id)} |
| 60 | + if not has_connection_access(user, connection, user_group_ids): |
| 61 | + return JSONResponse({"error": "Access denied"}, status_code=403) |
| 62 | + |
| 63 | + base_url = (connection.get("url") or "").rstrip("/") |
| 64 | + if not base_url: |
| 65 | + return JSONResponse({"error": "Terminal server URL not configured"}, status_code=503) |
| 66 | + |
| 67 | + target_url = f"{base_url}/{path}" |
| 68 | + if request.query_params: |
| 69 | + target_url += f"?{request.query_params}" |
| 70 | + |
| 71 | + headers = {"X-User-Id": user.id} |
| 72 | + cookies = {} |
| 73 | + auth_type = connection.get("auth_type", "bearer") |
| 74 | + |
| 75 | + if auth_type == "bearer": |
| 76 | + headers["Authorization"] = f"Bearer {connection.get('key', '')}" |
| 77 | + elif auth_type == "session": |
| 78 | + cookies = request.cookies |
| 79 | + headers["Authorization"] = f"Bearer {request.state.token.credentials}" |
| 80 | + elif auth_type == "system_oauth": |
| 81 | + cookies = request.cookies |
| 82 | + oauth_token = request.headers.get("x-oauth-access-token", "") |
| 83 | + if oauth_token: |
| 84 | + headers["Authorization"] = f"Bearer {oauth_token}" |
| 85 | + # auth_type == "none": no Authorization header |
| 86 | + |
| 87 | + content_type = request.headers.get("content-type") |
| 88 | + if content_type: |
| 89 | + headers["Content-Type"] = content_type |
| 90 | + |
| 91 | + body = await request.body() |
| 92 | + session = aiohttp.ClientSession( |
| 93 | + timeout=aiohttp.ClientTimeout(total=300, connect=10), |
| 94 | + trust_env=True, |
| 95 | + ) |
| 96 | + |
| 97 | + try: |
| 98 | + upstream_response = await session.request( |
| 99 | + method=request.method, |
| 100 | + url=target_url, |
| 101 | + headers=headers, |
| 102 | + cookies=cookies, |
| 103 | + data=body or None, |
| 104 | + ) |
| 105 | + |
| 106 | + upstream_content_type = upstream_response.headers.get("content-type", "") |
| 107 | + filtered_headers = { |
| 108 | + key: value |
| 109 | + for key, value in upstream_response.headers.items() |
| 110 | + if key.lower() not in STRIPPED_RESPONSE_HEADERS |
| 111 | + } |
| 112 | + |
| 113 | + # Stream binary responses directly |
| 114 | + if any(t in upstream_content_type for t in STREAMING_CONTENT_TYPES): |
| 115 | + async def cleanup(): |
| 116 | + await upstream_response.release() |
| 117 | + await session.close() |
| 118 | + |
| 119 | + return StreamingResponse( |
| 120 | + content=upstream_response.content.iter_any(), |
| 121 | + status_code=upstream_response.status, |
| 122 | + headers=filtered_headers, |
| 123 | + background=BackgroundTask(cleanup), |
| 124 | + ) |
| 125 | + |
| 126 | + # Buffer text/JSON responses |
| 127 | + response_body = await upstream_response.read() |
| 128 | + status_code = upstream_response.status |
| 129 | + await upstream_response.release() |
| 130 | + await session.close() |
| 131 | + |
| 132 | + return Response(content=response_body, status_code=status_code, headers=filtered_headers) |
| 133 | + |
| 134 | + except Exception as error: |
| 135 | + await session.close() |
| 136 | + log.exception("Terminal proxy error: %s", error) |
| 137 | + return JSONResponse({"error": f"Terminal proxy error: {error}"}, status_code=502) |
0 commit comments