diff options
Diffstat (limited to 'ttun_server')
| -rw-r--r-- | ttun_server/__init__.py | 23 | ||||
| -rw-r--r-- | ttun_server/endpoints.py | 57 | ||||
| -rw-r--r-- | ttun_server/types.py | 1 | ||||
| -rw-r--r-- | ttun_server/websockets.py | 217 |
4 files changed, 73 insertions, 225 deletions
diff --git a/ttun_server/__init__.py b/ttun_server/__init__.py index 6c77858..d54227a 100644 --- a/ttun_server/__init__.py +++ b/ttun_server/__init__.py | |||
| @@ -2,30 +2,23 @@ import logging | |||
| 2 | import os | 2 | import os |
| 3 | 3 | ||
| 4 | from fastapi import FastAPI | 4 | from fastapi import FastAPI |
| 5 | from starlette.routing import Host, Route, Router, WebSocketRoute | 5 | from starlette.routing import Host, Route, WebSocketRoute |
| 6 | 6 | ||
| 7 | from ttun_server.endpoints import health, proxy | 7 | from proxy import app as proxy_app |
| 8 | from .websockets import WebsocketProxy, Tunnel | 8 | from ttun_server.endpoints import health, base_endpoints |
| 9 | from ttun_server.websockets import tunnel | ||
| 9 | 10 | ||
| 10 | logging.basicConfig(level=getattr(logging, os.environ.get('LOG_LEVEL', 'INFO'))) | 11 | logging.basicConfig(level=getattr(logging, os.environ.get('LOG_LEVEL', 'INFO'))) |
| 11 | 12 | ||
| 12 | base_router = Router(routes=[ | 13 | app = FastAPI( |
| 13 | Route('/health/', health), | ||
| 14 | WebSocketRoute('/tunnel/', Tunnel) | ||
| 15 | ]) | ||
| 16 | |||
| 17 | server = FastAPI( | ||
| 18 | debug=True, | 14 | debug=True, |
| 19 | routes=[ | 15 | routes=[ |
| 20 | Host(os.environ['TUNNEL_DOMAIN'], base_router, 'base'), | 16 | WebSocketRoute('/tunnel/', endpoint=tunnel), |
| 21 | Route('/{path:path}', proxy), | 17 | Route('/health/', endpoint=health), |
| 22 | WebSocketRoute('/{path:path}', WebsocketProxy) | 18 | Host(f'{{subdomain}}.{os.environ['TUNNEL_DOMAIN']}', app=proxy_app) |
| 23 | ] | 19 | ] |
| 24 | ) | 20 | ) |
| 25 | 21 | ||
| 26 | server.post() | ||
| 27 | |||
| 28 | |||
| 29 | try: | 22 | try: |
| 30 | from ._version import version | 23 | from ._version import version |
| 31 | __version__ = version | 24 | __version__ = version |
diff --git a/ttun_server/endpoints.py b/ttun_server/endpoints.py index 22dcb6d..51c17aa 100644 --- a/ttun_server/endpoints.py +++ b/ttun_server/endpoints.py | |||
| @@ -1,54 +1,7 @@ | |||
| 1 | import logging | 1 | from fastapi import FastAPI |
| 2 | from base64 import b64decode, b64encode | ||
| 3 | from uuid import uuid4 | ||
| 4 | 2 | ||
| 5 | from starlette.background import BackgroundTask | 3 | base_endpoints = FastAPI() |
| 6 | from starlette.requests import Request | ||
| 7 | from starlette.responses import Response | ||
| 8 | 4 | ||
| 9 | from ttun_server.proxy_queue import ProxyQueue | 5 | @base_endpoints.get('/health/') |
| 10 | from ttun_server.types import HttpRequestData, HttpMessageType, HttpMessage | 6 | async def health(): |
| 11 | 7 | return 'OK' | |
| 12 | logger = logging.getLogger(__name__) | ||
| 13 | |||
| 14 | |||
| 15 | async def proxy(request: Request) -> Response: | ||
| 16 | [subdomain, *_] = request.headers['host'].split('.') | ||
| 17 | identifier = str(uuid4()) | ||
| 18 | response_queue = await ProxyQueue.create_for_identifier(identifier) | ||
| 19 | |||
| 20 | try: | ||
| 21 | request_queue = await ProxyQueue.get_for_identifier(subdomain) | ||
| 22 | |||
| 23 | logger.debug('PROXY %s%s ', subdomain, request.url) | ||
| 24 | await request_queue.enqueue( | ||
| 25 | HttpMessage( | ||
| 26 | type=HttpMessageType.request.value, | ||
| 27 | identifier=identifier, | ||
| 28 | payload=HttpRequestData( | ||
| 29 | method=request.method, | ||
| 30 | path=str(request.url).replace(str(request.base_url), '/'), | ||
| 31 | headers=list(request.headers.items()), | ||
| 32 | body=b64encode(await request.body()).decode() | ||
| 33 | ) | ||
| 34 | ) | ||
| 35 | ) | ||
| 36 | |||
| 37 | _response = await response_queue.dequeue() | ||
| 38 | payload = _response['payload'] | ||
| 39 | return Response( | ||
| 40 | status_code=payload['status'], | ||
| 41 | headers=dict(payload['headers']), | ||
| 42 | content=b64decode(payload['body'].encode()), | ||
| 43 | background=BackgroundTask(response_queue.delete) | ||
| 44 | ) | ||
| 45 | except AssertionError: | ||
| 46 | return Response( | ||
| 47 | content='Not Found', | ||
| 48 | status_code=404, | ||
| 49 | background=BackgroundTask(response_queue.delete) | ||
| 50 | ) | ||
| 51 | |||
| 52 | |||
| 53 | async def health(_: Request) -> Response: | ||
| 54 | return Response(content='OK', status_code=200) | ||
diff --git a/ttun_server/types.py b/ttun_server/types.py index 8591e7d..a0c22a3 100644 --- a/ttun_server/types.py +++ b/ttun_server/types.py | |||
| @@ -9,6 +9,7 @@ class HttpMessageType(Enum): | |||
| 9 | 9 | ||
| 10 | 10 | ||
| 11 | class Config(TypedDict): | 11 | class Config(TypedDict): |
| 12 | version: str | ||
| 12 | subdomain: str | 13 | subdomain: str |
| 13 | client_version: str | 14 | client_version: str |
| 14 | 15 | ||
diff --git a/ttun_server/websockets.py b/ttun_server/websockets.py index e828b8d..ea9ae94 100644 --- a/ttun_server/websockets.py +++ b/ttun_server/websockets.py | |||
| @@ -1,189 +1,90 @@ | |||
| 1 | import asyncio | 1 | import asyncio |
| 2 | import json | ||
| 3 | import logging | 2 | import logging |
| 4 | import os | 3 | import os |
| 5 | import typing | ||
| 6 | from asyncio import create_task | ||
| 7 | from base64 import b64encode, b64decode | ||
| 8 | from contextlib import asynccontextmanager | ||
| 9 | from typing import Optional | ||
| 10 | from uuid import uuid4 | 4 | from uuid import uuid4 |
| 11 | 5 | ||
| 12 | from starlette.endpoints import WebSocketEndpoint | 6 | from fastapi import WebSocket, WebSocketDisconnect |
| 13 | from starlette.types import Scope, Receive, Send | ||
| 14 | from starlette.websockets import WebSocket | ||
| 15 | 7 | ||
| 16 | import ttun_server | 8 | import ttun_server |
| 17 | from ttun_server.proxy_queue import ProxyQueue | 9 | from ttun_server.proxy_queue import ProxyQueue |
| 18 | from ttun_server.types import Config, Message, WebsocketMessageType, \ | 10 | from ttun_server.types import ( |
| 19 | WebsocketConnectData, WebsocketMessage, WebsocketMessageData, WebsocketDisconnectData, MessageType | 11 | Config, |
| 12 | Message, | ||
| 13 | MessageType, | ||
| 14 | ) | ||
| 20 | 15 | ||
| 21 | logger = logging.getLogger(__name__) | 16 | logger = logging.getLogger(__name__) |
| 22 | logger.setLevel('DEBUG') | 17 | logger.setLevel('DEBUG') |
| 23 | 18 | ||
| 24 | class WebsocketProxy(WebSocketEndpoint): | 19 | async def assert_compatible_version(websocket: WebSocket, config: Config) -> None: |
| 25 | encoding = 'json' | 20 | client_version = config.get('version', '1.0.0') |
| 26 | websocket_listen_task = None | 21 | logger.debug('client_version %s', client_version) |
| 27 | 22 | ||
| 28 | def __init__(self, *args, **kwargs): | 23 | if 'git' not in client_version and ttun_server.__version__ != 'development': |
| 29 | super().__init__(*args, **kwargs) | 24 | [client_major, *_] = [int(i) for i in client_version.split('.')[:3]] |
| 30 | self.id = str(uuid4()) | 25 | [server_major, *_] = [int(i) for i in ttun_server.__version__.split('.')] |
| 31 | 26 | ||
| 32 | @asynccontextmanager | 27 | if client_major < server_major: |
| 33 | async def proxy(self, websocket: WebSocket, message: WebsocketMessage): | 28 | await websocket.close(4000, 'Your client is too old') |
| 34 | [subdomain, *_] = websocket.url.hostname.split('.') | ||
| 35 | 29 | ||
| 36 | expect_ack = WebsocketMessageType(message['type']) == WebsocketMessageType.connect | 30 | if client_major > server_major: |
| 31 | await websocket.close(4001, 'Your client is too new') | ||
| 37 | 32 | ||
| 38 | try: | ||
| 39 | request_queue = await ProxyQueue.get_for_identifier(subdomain) | ||
| 40 | await request_queue.enqueue(message) | ||
| 41 | 33 | ||
| 42 | if expect_ack: | 34 | async def tunnel(websocket: WebSocket) -> None: |
| 43 | response_queue = await ProxyQueue.create_for_identifier(message["identifier"]) | 35 | request_tasks: dict[str, asyncio.Task] = {} |
| 44 | yield await response_queue.dequeue() | 36 | proxy_queues: dict[str, ProxyQueue] = {} |
| 45 | await response_queue.delete() | ||
| 46 | else: | ||
| 47 | yield | ||
| 48 | except AssertionError: | ||
| 49 | yield None | ||
| 50 | 37 | ||
| 51 | async def listen_for_messages(self, websocket: WebSocket): | 38 | await websocket.accept() |
| 52 | response_queue = await ProxyQueue.create_for_identifier(self.id) | 39 | config: Config = await websocket.receive_json() |
| 53 | 40 | ||
| 54 | while True: | 41 | await assert_compatible_version(websocket, config) |
| 55 | message: WebsocketMessage = await response_queue.dequeue() | ||
| 56 | logger.debug(message) | ||
| 57 | await websocket.send_text(b64decode(message['payload']['body'].encode()).decode()) | ||
| 58 | |||
| 59 | async def on_connect(self, websocket: WebSocket) -> None: | ||
| 60 | message = WebsocketMessage( | ||
| 61 | type=WebsocketMessageType.connect.value, | ||
| 62 | identifier=self.id, | ||
| 63 | payload=WebsocketConnectData( | ||
| 64 | path=websocket.path_params['path'], | ||
| 65 | headers=[ | ||
| 66 | (k.decode(), v.decode()) | ||
| 67 | for k, v | ||
| 68 | in websocket.scope['headers'] | ||
| 69 | ], | ||
| 70 | ) | ||
| 71 | ) | ||
| 72 | 42 | ||
| 73 | async with self.proxy(websocket, message) as m: | 43 | if 'subdomains' not in config: |
| 74 | if m is not None and WebsocketMessageType(m['type']) == WebsocketMessageType.ack: | 44 | config['subdomains'] = [config['subdomain']] |
| 75 | await super().on_connect(websocket) | 45 | elif config['subdomains'] is None: |
| 46 | config['subdomains'] = [None] | ||
