Files

103 lines
4.5 KiB
Python

"""Serve built assets and stream the authenticated API on one LAN port."""
from __future__ import annotations
import functools
import http.client
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit
HOP_HEADERS = {'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
'te', 'trailer', 'transfer-encoding', 'upgrade'}
class Gateway(SimpleHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
backend_port = 5281
extensions_map = {**SimpleHTTPRequestHandler.extensions_map, '.js': 'text/javascript',
'.mjs': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml',
'.wasm': 'application/wasm'}
def log_message(self, *_):
# Do not record query strings, authentication data or business values.
pass
def _proxy(self):
upstream = http.client.HTTPConnection('127.0.0.1', self.backend_port, timeout=1800)
try:
if self.headers.get('Transfer-Encoding'):
self.send_error(400, 'Content-Length is required')
return
length = int(self.headers.get('Content-Length', '0'))
if length < 0 or length > 273 * 1024 * 1024:
self.send_error(413)
return
upstream.putrequest(self.command, self.path, skip_host=True, skip_accept_encoding=True)
connection_headers = {s.strip().lower() for s in self.headers.get('Connection', '').split(',')}
for name, value in self.headers.items():
if name.lower() not in HOP_HEADERS | connection_headers:
upstream.putheader(name, value)
upstream.putheader('Connection', 'close')
upstream.endheaders()
remaining = length
while remaining:
chunk = self.rfile.read(min(remaining, 1024 * 1024))
if not chunk:
raise ConnectionError('Incomplete upload')
upstream.send(chunk)
remaining -= len(chunk)
response = upstream.getresponse()
self.send_response(response.status)
response_connection = {s.strip().lower() for s in response.getheader('Connection', '').split(',')}
for name, value in response.getheaders():
if name.lower() not in HOP_HEADERS | response_connection:
self.send_header(name, value)
self.send_header('Connection', 'close')
self.send_header('X-Content-Type-Options', 'nosniff')
self.end_headers()
self.close_connection = True
if self.command != 'HEAD':
while chunk := response.read1(64 * 1024):
self.wfile.write(chunk)
self.wfile.flush() # SSE events must arrive without buffering.
except (BrokenPipeError, ConnectionResetError):
self.close_connection = True
except (OSError, http.client.HTTPException, ValueError):
self.close_connection = True
# Never expose upstream exception text or an internal file path.
if not self.wfile.closed:
try:
self.send_error(502, 'Backend unavailable')
except OSError:
pass
finally:
upstream.close()
def _dispatch(self):
path = urlsplit(self.path).path
if path == '/api' or path.startswith('/api/') or path == '/actuator/health':
return self._proxy()
if self.command not in ('GET', 'HEAD'):
self.send_error(405)
return
candidate = Path(self.translate_path(self.path)).resolve()
root = Path(self.directory).resolve()
if not candidate.is_relative_to(root):
self.send_error(403)
return
if candidate.is_dir() and not (candidate / 'index.html').is_file():
self.send_error(404)
return
if not candidate.exists() and not Path(path).suffix:
self.path = '/index.html'
return super().do_HEAD() if self.command == 'HEAD' else super().do_GET()
do_GET = do_HEAD = do_POST = do_PUT = do_PATCH = do_DELETE = do_OPTIONS = _dispatch
def make_server(root, address, port, backend_port=5281):
handler = type('ConfiguredGateway', (Gateway,), {'backend_port': backend_port})
server = ThreadingHTTPServer((address, port), functools.partial(handler, directory=str(root)))
server.daemon_threads = True
return server