222 lines
8.0 KiB
Python
222 lines
8.0 KiB
Python
import json
|
|
import re
|
|
from urllib.parse import parse_qs
|
|
|
|
from app import domain, faults
|
|
from app.codec import REQUEST_ID, loads_object, media_type, require_text
|
|
from app.errors import AppError, bad_request, not_found, unauthorized
|
|
from app.settings import settings
|
|
|
|
_ROUTES = [
|
|
("GET", re.compile(r"^/health/live$"), "/health/live", "live"),
|
|
("GET", re.compile(r"^/health/ready$"), "/health/ready", "ready"),
|
|
("POST", re.compile(r"^/api/v1/users$"), "/api/v1/users", "register"),
|
|
("GET", re.compile(r"^/api/v1/users/me$"), "/api/v1/users/me", "me"),
|
|
("POST", re.compile(r"^/api/v1/auth/sessions$"), "/api/v1/auth/sessions", "login"),
|
|
("DELETE", re.compile(r"^/api/v1/auth/sessions/current$"), "/api/v1/auth/sessions/current", "logout"),
|
|
("POST", re.compile(r"^/api/v1/chats$"), "/api/v1/chats", "create_chat"),
|
|
("GET", re.compile(r"^/api/v1/chats$"), "/api/v1/chats", "list_chats"),
|
|
("GET", re.compile(r"^/api/v1/chats/([^/]+)$"), "/api/v1/chats/{chat_id}", "get_chat"),
|
|
("POST", re.compile(r"^/api/v1/chats/([^/]+)/messages$"), "/api/v1/chats/{chat_id}/messages", "create_message"),
|
|
("GET", re.compile(r"^/api/v1/chats/([^/]+)/messages$"), "/api/v1/chats/{chat_id}/messages", "list_messages"),
|
|
("POST", re.compile(r"^/api/v1/chats/([^/]+)/attachments$"), "/api/v1/chats/{chat_id}/attachments", "upload"),
|
|
("GET", re.compile(r"^/api/v1/attachments/([^/]+)$"), "/api/v1/attachments/{attachment_id}", "get_attachment"),
|
|
("GET", re.compile(r"^/api/v1/attachments/([^/]+)/content$"), "/api/v1/attachments/{attachment_id}/content", "download"),
|
|
]
|
|
|
|
|
|
def match(method, path):
|
|
for route_method, pattern, template, name in _ROUTES:
|
|
found = pattern.fullmatch(path)
|
|
if found and route_method == method:
|
|
return template, name, found.groups()
|
|
return "unmatched", "unmatched", ()
|
|
|
|
|
|
def _single(query, name):
|
|
values = query.get(name)
|
|
if not values:
|
|
return None
|
|
if len(values) != 1 or values[0] == "":
|
|
raise bad_request()
|
|
return values[0]
|
|
|
|
|
|
def _limit(query):
|
|
raw = _single(query, "limit")
|
|
if raw is None:
|
|
return 50
|
|
if re.fullmatch(r"[1-9][0-9]*", raw) is None:
|
|
raise bad_request()
|
|
value = int(raw)
|
|
if value > 100:
|
|
raise bad_request()
|
|
return value
|
|
|
|
|
|
def _json_body(headers, body):
|
|
if media_type(headers.get("content-type", "")) != "application/json":
|
|
raise bad_request()
|
|
if not body:
|
|
raise bad_request()
|
|
return loads_object(body)
|
|
|
|
|
|
def _bearer(headers):
|
|
value = headers.get("authorization", "")
|
|
if not value.lower().startswith("bearer "):
|
|
raise unauthorized(domain.BEARER)
|
|
token = value.split(" ", 1)[1].strip()
|
|
return token
|
|
|
|
|
|
def _basic(headers):
|
|
import base64
|
|
|
|
value = headers.get("authorization", "")
|
|
if not value.lower().startswith("basic "):
|
|
raise unauthorized(domain.BASIC)
|
|
try:
|
|
decoded = base64.b64decode(value.split(" ", 1)[1].strip(), validate=True).decode("utf-8")
|
|
except (ValueError, UnicodeError) as exc:
|
|
raise unauthorized(domain.BASIC) from exc
|
|
if ":" not in decoded:
|
|
raise unauthorized(domain.BASIC)
|
|
return decoded.split(":", 1)
|
|
|
|
|
|
def _filename(query):
|
|
raw = _single(query, "filename")
|
|
if raw is None:
|
|
raise bad_request()
|
|
if len(raw) < 1 or len(raw) > 255 or not raw.strip():
|
|
raise bad_request()
|
|
if any(ord(ch) < 32 or ord(ch) == 127 or ch in "/\\" for ch in raw):
|
|
raise bad_request()
|
|
return raw
|
|
|
|
|
|
def handle(method, path, query, headers, body):
|
|
template, name, groups = match(method, path)
|
|
if name == "unmatched":
|
|
raise not_found()
|
|
if name not in {"live", "ready"}:
|
|
delay = faults.handler_slow_seconds()
|
|
if delay:
|
|
import time
|
|
|
|
time.sleep(delay)
|
|
if name == "live":
|
|
return template, 200, {"Content-Type": "application/json; charset=utf-8"}, _dump({"status": "ok"})
|
|
if name == "ready":
|
|
domain.ready_check()
|
|
return template, 200, {"Content-Type": "application/json; charset=utf-8"}, _dump({"status": "ok"})
|
|
if name == "register":
|
|
status, payload = domain.register(_json_body(headers, body))
|
|
return template, status, _json_headers(), _dump(payload)
|
|
if name == "login":
|
|
if body:
|
|
raise bad_request()
|
|
username, password = _basic(headers)
|
|
status, payload = domain.login(username, password)
|
|
return template, status, _json_headers(), _dump(payload)
|
|
if name == "me":
|
|
user = domain.current_user(_bearer(headers))
|
|
return template, 200, _json_headers(), _dump(domain._user_json(user))
|
|
if name == "logout":
|
|
domain.revoke(_bearer(headers))
|
|
return template, 204, {}, b""
|
|
if name == "create_chat":
|
|
user = domain.current_user(_bearer(headers))
|
|
status, payload = domain.create_chat(user, _json_body(headers, body))
|
|
return template, status, _json_headers(), _dump(payload)
|
|
if name == "list_chats":
|
|
user = domain.current_user(_bearer(headers))
|
|
payload = domain.list_chats(user, _limit(query), _single(query, "cursor"))
|
|
return template, 200, _json_headers(), _dump(payload)
|
|
if name == "get_chat":
|
|
user = domain.current_user(_bearer(headers))
|
|
payload = domain.get_chat(user, _uuid_segment(groups[0]))
|
|
return template, 200, _json_headers(), _dump(payload)
|
|
if name == "create_message":
|
|
user = domain.current_user(_bearer(headers))
|
|
chat_id = _uuid_segment(groups[0])
|
|
status, payload = domain.create_message(
|
|
user,
|
|
chat_id,
|
|
headers.get("idempotency-key"),
|
|
_json_body(headers, body),
|
|
path,
|
|
)
|
|
return template, status, _json_headers(), _dump(payload)
|
|
if name == "list_messages":
|
|
user = domain.current_user(_bearer(headers))
|
|
payload = domain.list_messages(user, _uuid_segment(groups[0]), _limit(query), _single(query, "cursor"))
|
|
return template, 200, _json_headers(), _dump(payload)
|
|
if name == "upload":
|
|
user = domain.current_user(_bearer(headers))
|
|
content_type = media_type(headers.get("content-type", ""))
|
|
status, payload = domain.upload(user, _uuid_segment(groups[0]), _filename(query), content_type, body)
|
|
return template, status, _json_headers(), _dump(payload)
|
|
if name == "get_attachment":
|
|
user = domain.current_user(_bearer(headers))
|
|
payload = domain.get_attachment(user, _uuid_segment(groups[0]))
|
|
return template, 200, _json_headers(), _dump(payload)
|
|
if name == "download":
|
|
user = domain.current_user(_bearer(headers))
|
|
variant = _single(query, "variant") or "original"
|
|
data, content_type = domain.download(user, _uuid_segment(groups[0]), variant)
|
|
return template, 200, {"Content-Type": content_type}, data
|
|
raise not_found()
|
|
|
|
|
|
def _uuid_segment(value):
|
|
from app.codec import parse_uuid
|
|
|
|
return parse_uuid(value)
|
|
|
|
|
|
def _json_headers():
|
|
return {"Content-Type": "application/json; charset=utf-8"}
|
|
|
|
|
|
def _dump(payload):
|
|
return json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
|
|
|
|
def error_response(exc, request_id):
|
|
if isinstance(exc, AppError):
|
|
status = exc.status
|
|
code = exc.code
|
|
message = exc.message
|
|
headers = dict(exc.headers)
|
|
else:
|
|
status = 500
|
|
code = "internal_error"
|
|
message = "Внутренняя ошибка"
|
|
headers = {}
|
|
headers["Content-Type"] = "application/json; charset=utf-8"
|
|
body = _dump({"error": {"code": code, "message": message, "request_id": request_id}})
|
|
return status, headers, body
|
|
|
|
|
|
def request_id_from(headers):
|
|
incoming = headers.get("x-request-id", "")
|
|
if REQUEST_ID.fullmatch(incoming):
|
|
return incoming
|
|
import uuid
|
|
|
|
return uuid.uuid4().hex
|
|
|
|
|
|
def query_from(raw):
|
|
if not raw:
|
|
return {}
|
|
return parse_qs(raw, keep_blank_values=True, strict_parsing=False)
|
|
|
|
|
|
def body_limit(path):
|
|
if "/attachments" in path and path.rstrip("/").endswith("attachments"):
|
|
return settings.max_upload + 1
|
|
return 1_000_000
|