forked from mtusi2026/mtusi2026lab2
489 lines
20 KiB
Python
489 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import base64
|
|
import binascii
|
|
import json
|
|
import logging
|
|
import os
|
|
import re
|
|
import signal
|
|
import sys
|
|
import threading
|
|
import uuid
|
|
from datetime import datetime, timezone
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from urllib.parse import parse_qs, urlsplit
|
|
|
|
from auth import (
|
|
create_session,
|
|
hash_password,
|
|
now_iso,
|
|
parse_basic_auth,
|
|
parse_bearer_token,
|
|
validate_password,
|
|
verify_password,
|
|
)
|
|
from db import ApiError, Store
|
|
from sessions import SessionStore
|
|
|
|
MAX_BODY_BYTES = 1024 * 1024
|
|
USERNAME_PATTERN = re.compile(r'^[a-z0-9_]{3,32}$')
|
|
CURSOR_TIMESTAMP_PATTERN = re.compile(
|
|
r'^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?Z$'
|
|
)
|
|
LOG = logging.getLogger('messenger')
|
|
OPENAPI_PATH = Path(__file__).resolve().parent / 'contracts' / 'openapi.json'
|
|
SWAGGER_HTML = b'''<!doctype html>
|
|
<html lang="ru">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<title>MTUSI Messenger API</title>
|
|
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui.css">
|
|
</head>
|
|
<body>
|
|
<div id="swagger-ui"></div>
|
|
<script src="https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui-bundle.js"></script>
|
|
<script>
|
|
window.onload = () => SwaggerUIBundle({
|
|
url: "/openapi.json",
|
|
dom_id: "#swagger-ui",
|
|
deepLinking: true,
|
|
presets: [SwaggerUIBundle.presets.apis],
|
|
layout: "BaseLayout"
|
|
});
|
|
</script>
|
|
</body>
|
|
</html>
|
|
'''
|
|
|
|
|
|
def cursor_encode(resource, item):
|
|
value = json.dumps(
|
|
{'resource': resource, 'created_at': item['created_at'], 'id': item['id']},
|
|
separators=(',', ':'),
|
|
).encode('utf-8')
|
|
return base64.urlsafe_b64encode(value).rstrip(b'=').decode('ascii')
|
|
|
|
|
|
def cursor_decode(cursor, resource):
|
|
try:
|
|
padding = '=' * (-len(cursor) % 4)
|
|
decoded = base64.b64decode(cursor + padding, altchars=b'-_', validate=True)
|
|
value = json.loads(decoded.decode('utf-8'))
|
|
except (ValueError, UnicodeError, binascii.Error):
|
|
raise ApiError(400, 'invalid_request', 'Invalid cursor') from None
|
|
if (not isinstance(value, dict) or set(value) != {'resource', 'created_at', 'id'}
|
|
or value.get('resource') != resource
|
|
or not isinstance(value.get('created_at'), str)
|
|
or not CURSOR_TIMESTAMP_PATTERN.fullmatch(value['created_at'])
|
|
or not isinstance(value.get('id'), str)):
|
|
raise ApiError(400, 'invalid_request', 'Invalid cursor')
|
|
try:
|
|
created_at = datetime.fromisoformat(value['created_at'][:-1] + '+00:00')
|
|
item_id = str(uuid.UUID(value['id']))
|
|
except (ValueError, AttributeError):
|
|
raise ApiError(400, 'invalid_request', 'Invalid cursor') from None
|
|
if item_id != value['id']:
|
|
raise ApiError(400, 'invalid_request', 'Invalid cursor')
|
|
return created_at, item_id
|
|
|
|
|
|
def required_text(value, name, maximum):
|
|
if not isinstance(value, str) or not value.strip() or len(value) > maximum:
|
|
raise ApiError(400, 'invalid_request', 'Invalid ' + name)
|
|
try:
|
|
value.encode('utf-8')
|
|
except UnicodeEncodeError:
|
|
raise ApiError(400, 'invalid_request', 'Invalid ' + name) from None
|
|
return value
|
|
|
|
|
|
def parse_uuid(value):
|
|
if not isinstance(value, str):
|
|
raise ApiError(400, 'invalid_request', 'Invalid UUID')
|
|
try:
|
|
parsed = uuid.UUID(value)
|
|
except (ValueError, AttributeError):
|
|
raise ApiError(400, 'invalid_request', 'Invalid UUID') from None
|
|
if str(parsed) != value.lower():
|
|
raise ApiError(400, 'invalid_request', 'Invalid UUID')
|
|
return str(parsed)
|
|
|
|
|
|
class MessengerHandler(BaseHTTPRequestHandler):
|
|
server_version = 'MTUSI-Messenger'
|
|
protocol_version = 'HTTP/1.1'
|
|
|
|
def log_message(self, _format, *args):
|
|
LOG.info('request method=%s status=%s request_id=%s', self.command, self._status, self._request_id)
|
|
|
|
def _send_bytes(self, status, request_id, body, content_type, extra_headers=None):
|
|
self._status = status
|
|
self.send_response(status)
|
|
self.send_header('X-Request-Id', request_id)
|
|
self.send_header('Content-Length', str(len(body)))
|
|
if status != 204:
|
|
self.send_header('Content-Type', content_type)
|
|
for name, value in (extra_headers or {}).items():
|
|
self.send_header(name, value)
|
|
self.end_headers()
|
|
if body:
|
|
self.wfile.write(body)
|
|
|
|
def _send(self, status, request_id, payload=None, extra_headers=None):
|
|
body = b'' if status == 204 else json.dumps(
|
|
payload, ensure_ascii=False, separators=(',', ':')
|
|
).encode('utf-8')
|
|
self._send_bytes(
|
|
status, request_id, body, 'application/json; charset=utf-8', extra_headers
|
|
)
|
|
|
|
def _error(self, request_id, error, extra_headers=None):
|
|
self._send(error.status, request_id, {
|
|
'error': {
|
|
'code': error.code,
|
|
'message': error.message,
|
|
'request_id': request_id,
|
|
},
|
|
}, extra_headers=extra_headers)
|
|
|
|
def _read_json(self):
|
|
if self.headers.get_content_type() != 'application/json':
|
|
raise ApiError(415, 'unsupported_media_type', 'Expected application/json')
|
|
raw_length = self.headers.get('Content-Length')
|
|
try:
|
|
length = int(raw_length)
|
|
except (TypeError, ValueError):
|
|
raise ApiError(400, 'invalid_request', 'Invalid Content-Length') from None
|
|
if length < 0:
|
|
raise ApiError(400, 'invalid_request', 'Invalid Content-Length')
|
|
if length > MAX_BODY_BYTES:
|
|
raise ApiError(413, 'payload_too_large', 'Request body is too large')
|
|
try:
|
|
value = json.loads(self.rfile.read(length).decode('utf-8'))
|
|
except (ValueError, UnicodeError):
|
|
raise ApiError(400, 'invalid_request', 'Malformed JSON') from None
|
|
if not isinstance(value, dict):
|
|
raise ApiError(400, 'invalid_request', 'Expected a JSON object')
|
|
return value
|
|
|
|
def _dependencies_ok(self):
|
|
try:
|
|
self.server.store.ping()
|
|
self.server.sessions.ping()
|
|
return True
|
|
except Exception:
|
|
LOG.exception('dependency check failed')
|
|
return False
|
|
|
|
def _unauthorized_bearer(self, request_id):
|
|
self._error(
|
|
request_id,
|
|
ApiError(401, 'unauthorized', 'Authentication required'),
|
|
extra_headers={'WWW-Authenticate': 'Bearer realm="messenger"'},
|
|
)
|
|
|
|
def _unauthorized_basic(self, request_id):
|
|
self._error(
|
|
request_id,
|
|
ApiError(401, 'unauthorized', 'Authentication required'),
|
|
extra_headers={'WWW-Authenticate': 'Basic realm="messenger", charset="UTF-8"'},
|
|
)
|
|
|
|
def _authenticated_user(self, request_id):
|
|
auth = self.headers.get('Authorization', '')
|
|
if auth.startswith('Basic '):
|
|
self._unauthorized_bearer(request_id)
|
|
return None
|
|
token = parse_bearer_token(auth)
|
|
if not token:
|
|
self._unauthorized_bearer(request_id)
|
|
return None
|
|
try:
|
|
user_id = self.server.sessions.get_user_id(token)
|
|
except Exception:
|
|
LOG.exception('session lookup failed')
|
|
self._error(request_id, ApiError(503, 'unavailable', 'Service unavailable'))
|
|
return None
|
|
if not user_id:
|
|
self._unauthorized_bearer(request_id)
|
|
return None
|
|
try:
|
|
user = self.server.store.get_user(user_id)
|
|
except Exception:
|
|
LOG.exception('user lookup failed')
|
|
self._error(request_id, ApiError(503, 'unavailable', 'Service unavailable'))
|
|
return None
|
|
if user is None:
|
|
self._unauthorized_bearer(request_id)
|
|
return None
|
|
user['_token'] = token
|
|
return user
|
|
|
|
@staticmethod
|
|
def _query(query):
|
|
try:
|
|
values = parse_qs(query, keep_blank_values=True, strict_parsing=True)
|
|
except ValueError:
|
|
raise ApiError(400, 'invalid_request', 'Invalid query parameters') from None
|
|
if set(values) - {'limit', 'cursor'} or any(len(items) != 1 for items in values.values()):
|
|
raise ApiError(400, 'invalid_request', 'Invalid query parameters')
|
|
try:
|
|
limit = int(values.get('limit', ['50'])[0])
|
|
except ValueError:
|
|
raise ApiError(400, 'invalid_request', 'Invalid limit') from None
|
|
if not 1 <= limit <= 100:
|
|
raise ApiError(400, 'invalid_request', 'Invalid limit')
|
|
cursor = values.get('cursor', [''])[0]
|
|
if ('cursor' in values and not cursor) or len(cursor) > 2048:
|
|
raise ApiError(400, 'invalid_request', 'Invalid cursor')
|
|
return limit, cursor
|
|
|
|
def _create_session(self, request_id):
|
|
credentials = parse_basic_auth(self.headers.get('Authorization'))
|
|
if not credentials:
|
|
self._unauthorized_basic(request_id)
|
|
return
|
|
username, password = credentials
|
|
if not isinstance(username, str) or not USERNAME_PATTERN.fullmatch(username):
|
|
self._unauthorized_basic(request_id)
|
|
return
|
|
if not validate_password(password):
|
|
self._unauthorized_basic(request_id)
|
|
return
|
|
try:
|
|
row = self.server.store.get_user_with_password(username)
|
|
except Exception:
|
|
LOG.exception('login lookup failed')
|
|
self._error(request_id, ApiError(503, 'unavailable', 'Service unavailable'))
|
|
return
|
|
if row is None or not verify_password(row['password_hash'], password):
|
|
self._unauthorized_basic(request_id)
|
|
return
|
|
user = self.server.store.get_user(str(row['id']))
|
|
try:
|
|
token, expires_at = create_session(self.server.sessions, user['id'])
|
|
except Exception:
|
|
LOG.exception('session create failed')
|
|
self._error(request_id, ApiError(503, 'unavailable', 'Service unavailable'))
|
|
return
|
|
self._send(201, request_id, {
|
|
'token': token,
|
|
'token_type': 'Bearer',
|
|
'expires_at': expires_at,
|
|
'user': user,
|
|
})
|
|
|
|
def _logout(self, request_id, user):
|
|
try:
|
|
self.server.sessions.revoke(user['_token'])
|
|
except Exception:
|
|
LOG.exception('session revoke failed')
|
|
self._error(request_id, ApiError(503, 'unavailable', 'Service unavailable'))
|
|
return
|
|
self._send_bytes(204, request_id, b'', 'application/json; charset=utf-8')
|
|
|
|
def _register(self, request_id, body):
|
|
if set(body) != {'username', 'display_name', 'password'}:
|
|
raise ApiError(400, 'invalid_request', 'Invalid user fields')
|
|
username = body['username']
|
|
if not isinstance(username, str) or not USERNAME_PATTERN.fullmatch(username):
|
|
raise ApiError(400, 'invalid_request', 'Invalid username')
|
|
display_name = required_text(body['display_name'], 'display_name', 100)
|
|
password = body['password']
|
|
if not validate_password(password):
|
|
raise ApiError(400, 'invalid_request', 'Invalid password')
|
|
created_at = now_iso()
|
|
password_hash = hash_password(password)
|
|
user = self.server.store.register_user(username, display_name, password_hash, created_at)
|
|
self._send(201, request_id, user)
|
|
|
|
def _dispatch(self):
|
|
request_id = str(uuid.uuid4())
|
|
self._request_id = request_id
|
|
self._status = 500
|
|
try:
|
|
if self.server.stopping:
|
|
raise ApiError(503, 'unavailable', 'Server is shutting down')
|
|
route = urlsplit(self.path)
|
|
path = route.path
|
|
if self.command == 'GET' and path in ('/docs', '/docs/'):
|
|
self._send_bytes(200, request_id, SWAGGER_HTML, 'text/html; charset=utf-8')
|
|
return
|
|
if self.command == 'GET' and path == '/openapi.json':
|
|
self._send_bytes(
|
|
200, request_id, self.server.openapi_json, 'application/json; charset=utf-8'
|
|
)
|
|
return
|
|
if path == '/health/live' and self.command == 'GET':
|
|
self._send(200, request_id, {'status': 'ok'})
|
|
return
|
|
if path == '/health/ready' and self.command == 'GET':
|
|
if self._dependencies_ok():
|
|
self._send(200, request_id, {'status': 'ok'})
|
|
else:
|
|
self._error(request_id, ApiError(503, 'unavailable', 'Service unavailable'))
|
|
return
|
|
if path == '/api/v1/users' and self.command == 'POST':
|
|
self._register(request_id, self._read_json())
|
|
return
|
|
if path == '/api/v1/auth/sessions' and self.command == 'POST':
|
|
self._create_session(request_id)
|
|
return
|
|
if path.startswith('/api/v1/'):
|
|
user = self._authenticated_user(request_id)
|
|
if user is None:
|
|
return
|
|
user_id = user['id']
|
|
if path == '/api/v1/auth/sessions/current' and self.command == 'DELETE':
|
|
self._logout(request_id, user)
|
|
return
|
|
if path == '/api/v1/users/me' and self.command == 'GET':
|
|
self._send(200, request_id, {
|
|
k: user[k] for k in ('id', 'username', 'display_name', 'created_at')
|
|
})
|
|
return
|
|
if path == '/api/v1/chats' and self.command == 'POST':
|
|
body = self._read_json()
|
|
if set(body) != {'title', 'member_ids'}:
|
|
raise ApiError(400, 'invalid_request', 'Invalid chat fields')
|
|
title = required_text(body['title'], 'title', 100)
|
|
member_ids = body['member_ids']
|
|
if (not isinstance(member_ids, list) or not member_ids or len(member_ids) > 100
|
|
or any(not isinstance(value, str) for value in member_ids)):
|
|
raise ApiError(400, 'invalid_request', 'Invalid chat members')
|
|
normalized = [parse_uuid(value) for value in member_ids]
|
|
if len(set(normalized)) != len(normalized) or user_id not in normalized:
|
|
raise ApiError(400, 'invalid_request', 'Invalid chat members')
|
|
chat = self.server.store.create_chat(
|
|
user_id, title, normalized, now_iso()
|
|
)
|
|
self._send(201, request_id, chat)
|
|
return
|
|
if path == '/api/v1/chats' and self.command == 'GET':
|
|
limit, cursor = self._query(route.query)
|
|
key = cursor_decode(cursor, 'chats') if cursor else None
|
|
items, next_key = self.server.store.list_chats(user_id, limit, key)
|
|
next_cursor = cursor_encode('chats', items[-1]) if next_key else None
|
|
self._send(200, request_id, {'items': items, 'next_cursor': next_cursor})
|
|
return
|
|
match = re.fullmatch(r'/api/v1/chats/([^/]+)', path)
|
|
if match and self.command == 'GET':
|
|
chat_id = parse_uuid(match.group(1))
|
|
self._send(200, request_id, self.server.store.get_chat(user_id, chat_id))
|
|
return
|
|
match = re.fullmatch(r'/api/v1/chats/([^/]+)/messages', path)
|
|
if match:
|
|
chat_id = parse_uuid(match.group(1))
|
|
resource = 'messages:' + chat_id
|
|
if self.command == 'POST':
|
|
body = self._read_json()
|
|
if not isinstance(body, dict) or set(body) != {'text'}:
|
|
raise ApiError(400, 'invalid_request', 'Invalid message fields')
|
|
text = body['text']
|
|
if not isinstance(text, str) or len(text) > 4000 or not text.strip():
|
|
raise ApiError(400, 'invalid_request', 'Message text must not be empty')
|
|
try:
|
|
text.encode('utf-8')
|
|
except UnicodeEncodeError:
|
|
raise ApiError(400, 'invalid_request', 'Invalid message text') from None
|
|
message = self.server.store.create_message(
|
|
user_id, chat_id, text, now_iso()
|
|
)
|
|
self._send(201, request_id, message)
|
|
return
|
|
if self.command == 'GET':
|
|
limit, cursor = self._query(route.query)
|
|
key = cursor_decode(cursor, resource) if cursor else None
|
|
items, next_key = self.server.store.list_messages(user_id, chat_id, limit, key)
|
|
next_cursor = cursor_encode(resource, items[-1]) if next_key else None
|
|
self._send(200, request_id, {'items': items, 'next_cursor': next_cursor})
|
|
return
|
|
raise ApiError(404, 'not_found', 'Resource not found')
|
|
except ApiError as error:
|
|
self._error(request_id, error)
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
LOG.info('request disconnected request_id=%s', request_id)
|
|
except Exception:
|
|
LOG.exception('request failed request_id=%s', request_id)
|
|
self._error(request_id, ApiError(500, 'internal_error', 'Internal server error'))
|
|
|
|
def do_GET(self):
|
|
self._dispatch()
|
|
|
|
def do_POST(self):
|
|
self._dispatch()
|
|
|
|
def do_PUT(self):
|
|
self._dispatch()
|
|
|
|
def do_PATCH(self):
|
|
self._dispatch()
|
|
|
|
def do_DELETE(self):
|
|
self._dispatch()
|
|
|
|
def do_OPTIONS(self):
|
|
self._dispatch()
|
|
|
|
|
|
class MessengerServer(ThreadingHTTPServer):
|
|
daemon_threads = True
|
|
block_on_close = False
|
|
|
|
def __init__(self, address, store, sessions):
|
|
super().__init__(address, MessengerHandler)
|
|
self.store = store
|
|
self.sessions = sessions
|
|
self.stopping = False
|
|
try:
|
|
spec = json.loads(OPENAPI_PATH.read_text(encoding='utf-8'))
|
|
spec['servers'] = [{'url': '/', 'description': 'Текущий адрес API'}]
|
|
self.openapi_json = json.dumps(
|
|
spec, ensure_ascii=False, separators=(',', ':')
|
|
).encode('utf-8')
|
|
except (OSError, ValueError) as error:
|
|
self.server_close()
|
|
raise RuntimeError('Unable to load the OpenAPI contract') from error
|
|
|
|
|
|
def main():
|
|
host = os.environ.get('APP_HOST', '0.0.0.0')
|
|
try:
|
|
port = int(os.environ.get('APP_PORT', '8080'))
|
|
except ValueError:
|
|
raise SystemExit('APP_PORT must be an integer')
|
|
if not 1 <= port <= 65535:
|
|
raise SystemExit('APP_PORT must be between 1 and 65535')
|
|
if os.environ.get('SESSION_STORE', 'redis').lower() != 'redis':
|
|
raise SystemExit('SESSION_STORE must be redis for this implementation')
|
|
|
|
logging.basicConfig(
|
|
level=os.environ.get('LOG_LEVEL', 'INFO').upper(),
|
|
format='%(asctime)s %(levelname)s %(name)s %(message)s',
|
|
stream=sys.stdout,
|
|
)
|
|
store = Store.connect()
|
|
sessions = SessionStore.from_env()
|
|
server = MessengerServer((host, port), store, sessions)
|
|
|
|
def stop(_signum, _frame):
|
|
server.stopping = True
|
|
threading.Thread(target=server.shutdown, name='http-shutdown', daemon=True).start()
|
|
|
|
signal.signal(signal.SIGTERM, stop)
|
|
signal.signal(signal.SIGINT, stop)
|
|
LOG.info('server started host=%s port=%d', host, port)
|
|
try:
|
|
server.serve_forever(poll_interval=0.2)
|
|
finally:
|
|
server.server_close()
|
|
store.close()
|
|
LOG.info('server stopped')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|