| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import email.utils |
| 5 |
import http |
| 6 |
import http.cookies |
| 7 |
import pathlib |
| 8 |
import signal |
| 9 |
import urllib.parse |
| 10 |
import uuid |
| 11 |
|
| 12 |
from websockets.asyncio.server import basic_auth as websockets_basic_auth, serve |
| 13 |
from websockets.datastructures import Headers |
| 14 |
from websockets.frames import CloseCode |
| 15 |
from websockets.http11 import Response |
| 16 |
|
| 17 |
|
| 18 |
# User accounts database |
| 19 |
|
| 20 |
USERS = {} |
| 21 |
|
| 22 |
|
| 23 |
def create_token(user, lifetime=1): |
| 24 |
"""Create token for user and delete it once its lifetime is over.""" |
| 25 |
token = uuid.uuid4().hex |
| 26 |
USERS[token] = user |
| 27 |
asyncio.get_running_loop().call_later(lifetime, USERS.pop, token) |
| 28 |
return token |
| 29 |
|
| 30 |
|
| 31 |
def get_user(token): |
| 32 |
"""Find user authenticated by token or return None.""" |
| 33 |
return USERS.get(token) |
| 34 |
|
| 35 |
|
| 36 |
# Utilities |
| 37 |
|
| 38 |
|
| 39 |
def get_cookie(raw, key): |
| 40 |
cookie = http.cookies.SimpleCookie(raw) |
| 41 |
morsel = cookie.get(key) |
| 42 |
if morsel is not None: |
| 43 |
return morsel.value |
| 44 |
|
| 45 |
|
| 46 |
def get_query_param(path, key): |
| 47 |
query = urllib.parse.urlparse(path).query |
| 48 |
params = urllib.parse.parse_qs(query) |
| 49 |
values = params.get(key, []) |
| 50 |
if len(values) == 1: |
| 51 |
return values[0] |
| 52 |
|
| 53 |
|
| 54 |
# WebSocket handler |
| 55 |
|
| 56 |
|
| 57 |
async def handler(websocket): |
| 58 |
try: |
| 59 |
user = websocket.username |
| 60 |
except AttributeError: |
| 61 |
return |
| 62 |
|
| 63 |
await websocket.send(f"Hello {user}!") |
| 64 |
message = await websocket.recv() |
| 65 |
assert message == f"Goodbye {user}." |
| 66 |
|
| 67 |
|
| 68 |
CONTENT_TYPES = { |
| 69 |
".css": "text/css", |
| 70 |
".html": "text/html; charset=utf-8", |
| 71 |
".ico": "image/x-icon", |
| 72 |
".js": "text/javascript", |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
async def serve_html(connection, request): |
| 77 |
"""Basic HTTP server implemented as a process_request hook.""" |
| 78 |
user = get_query_param(request.path, "user") |
| 79 |
path = urllib.parse.urlparse(request.path).path |
| 80 |
if path == "/": |
| 81 |
if user is None: |
| 82 |
page = "index.html" |
| 83 |
else: |
| 84 |
page = "test.html" |
| 85 |
else: |
| 86 |
page = path[1:] |
| 87 |
|
| 88 |
try: |
| 89 |
template = pathlib.Path(__file__).with_name(page) |
| 90 |
except ValueError: |
| 91 |
pass |
| 92 |
else: |
| 93 |
if template.is_file(): |
| 94 |
body = template.read_bytes() |
| 95 |
if user is not None: |
| 96 |
token = create_token(user) |
| 97 |
body = body.replace(b"TOKEN", token.encode()) |
| 98 |
headers = Headers( |
| 99 |
{ |
| 100 |
"Date": email.utils.formatdate(usegmt=True), |
| 101 |
"Connection": "close", |
| 102 |
"Content-Length": str(len(body)), |
| 103 |
"Content-Type": CONTENT_TYPES[template.suffix], |
| 104 |
} |
| 105 |
) |
| 106 |
return Response(200, "OK", headers, body) |
| 107 |
|
| 108 |
return connection.respond(http.HTTPStatus.NOT_FOUND, "Not found\n") |
| 109 |
|
| 110 |
|
| 111 |
async def first_message_handler(websocket): |
| 112 |
"""Handler that sends credentials in the first WebSocket message.""" |
| 113 |
token = await websocket.recv() |
| 114 |
user = get_user(token) |
| 115 |
if user is None: |
| 116 |
await websocket.close(CloseCode.INTERNAL_ERROR, "authentication failed") |
| 117 |
return |
| 118 |
|
| 119 |
websocket.username = user |
| 120 |
await handler(websocket) |
| 121 |
|
| 122 |
|
| 123 |
async def query_param_auth(connection, request): |
| 124 |
"""Authenticate user from token in query parameter.""" |
| 125 |
token = get_query_param(request.path, "token") |
| 126 |
if token is None: |
| 127 |
return connection.respond(http.HTTPStatus.UNAUTHORIZED, "Missing token\n") |
| 128 |
|
| 129 |
user = get_user(token) |
| 130 |
if user is None: |
| 131 |
return connection.respond(http.HTTPStatus.UNAUTHORIZED, "Invalid token\n") |
| 132 |
|
| 133 |
connection.username = user |
| 134 |
|
| 135 |
|
| 136 |
async def cookie_auth(connection, request): |
| 137 |
"""Authenticate user from token in cookie.""" |
| 138 |
if "Upgrade" not in request.headers: |
| 139 |
template = pathlib.Path(__file__).with_name(request.path[1:]) |
| 140 |
body = template.read_bytes() |
| 141 |
headers = Headers( |
| 142 |
{ |
| 143 |
"Date": email.utils.formatdate(usegmt=True), |
| 144 |
"Connection": "close", |
| 145 |
"Content-Length": str(len(body)), |
| 146 |
"Content-Type": CONTENT_TYPES[template.suffix], |
| 147 |
} |
| 148 |
) |
| 149 |
return Response(200, "OK", headers, body) |
| 150 |
|
| 151 |
token = get_cookie(request.headers.get("Cookie", ""), "token") |
| 152 |
if token is None: |
| 153 |
return connection.respond(http.HTTPStatus.UNAUTHORIZED, "Missing token\n") |
| 154 |
|
| 155 |
user = get_user(token) |
| 156 |
if user is None: |
| 157 |
return connection.respond(http.HTTPStatus.UNAUTHORIZED, "Invalid token\n") |
| 158 |
|
| 159 |
connection.username = user |
| 160 |
|
| 161 |
|
| 162 |
def check_credentials(username, password): |
| 163 |
"""Authenticate user with HTTP Basic Auth.""" |
| 164 |
return username == get_user(password) |
| 165 |
|
| 166 |
|
| 167 |
basic_auth = websockets_basic_auth(check_credentials=check_credentials) |
| 168 |
|
| 169 |
|
| 170 |
async def main(): |
| 171 |
"""Start one HTTP server and four WebSocket servers.""" |
| 172 |
# Set the stop condition when receiving SIGINT or SIGTERM. |
| 173 |
loop = asyncio.get_running_loop() |
| 174 |
stop = asyncio.Event() |
| 175 |
loop.add_signal_handler(signal.SIGINT, stop.set) |
| 176 |
loop.add_signal_handler(signal.SIGTERM, stop.set) |
| 177 |
|
| 178 |
async with ( |
| 179 |
serve(handler, host="", port=8000, process_request=serve_html), |
| 180 |
serve(first_message_handler, host="", port=8001), |
| 181 |
serve(handler, host="", port=8002, process_request=query_param_auth), |
| 182 |
serve(handler, host="", port=8003, process_request=cookie_auth), |
| 183 |
serve(handler, host="", port=8004, process_request=basic_auth), |
| 184 |
): |
| 185 |
print("Running on http://localhost:8000/") |
| 186 |
await stop.wait() |
| 187 |
print("\rExiting") |
| 188 |
|
| 189 |
|
| 190 |
if __name__ == "__main__": |
| 191 |
asyncio.run(main()) |