Files

226 lines
11 KiB
Python

import base64
import binascii
import hashlib
import hmac
import os
import secrets
import time
import uuid
from datetime import datetime, timezone
from .domain import USERNAME_RE, now, require_uuid, validate_object, validate_text
from .errors import ApiError
from .state import State
class MessengerService:
def __init__(self, state: State):
self.state = state
def actor(self, headers):
authorization = headers.get("Authorization", "")
if not authorization.startswith("Bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer-сессия")
token = authorization[7:].strip()
with self.state.lock:
session = self.state.sessions.get(token)
user = self.state.users.get(session["user_id"]) if session else None
if session and (session["revoked"] or session["expires_at"] <= time.time()):
user = None
if not user:
raise ApiError(401, "unauthorized", "Требуется действительная сессия")
return user
@staticmethod
def public_user(user):
return {key: value for key, value in user.items() if not key.startswith("_")}
@staticmethod
def _password_hash(password):
salt = secrets.token_bytes(16)
digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=16384, r=8, p=1)
return "scrypt$16384$8$1$%s$%s" % (salt.hex(), digest.hex())
@staticmethod
def _password_matches(password, encoded):
try:
_, n, r, p, salt, digest = encoded.split("$")
actual = hashlib.scrypt(password.encode("utf-8"), salt=bytes.fromhex(salt),
n=int(n), r=int(r), p=int(p))
return hmac.compare_digest(actual.hex(), digest)
except (ValueError, TypeError):
return False
def create_user(self, body):
validate_object(body, ("username", "display_name", "password"), ("username", "display_name", "password"))
username = body["username"]
display_name = body["display_name"]
password = body["password"]
if (
not isinstance(username, str)
or not isinstance(display_name, str)
or not USERNAME_RE.fullmatch(username)
or not validate_text(display_name, 100)
or not isinstance(password, str)
or not 12 <= len(password) <= 128
):
raise ApiError(400, "invalid_request", "Некорректные данные пользователя")
with self.state.lock:
if username in self.state.usernames:
raise ApiError(409, "conflict", "Username уже занят")
user = {"id": str(uuid.uuid4()), "username": username, "display_name": display_name,
"created_at": now(), "_password_hash": self._password_hash(password)}
self.state.users[user["id"]] = user
self.state.usernames[username] = user["id"]
self.state.execute(
"INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES (%s,%s,%s,%s,%s)",
(user["id"], username, display_name, user["_password_hash"], user["created_at"]))
return self.public_user(user)
def create_session(self, authorization):
if not authorization.startswith("Basic "):
raise ApiError(401, "unauthorized", "Неверные credentials")
try:
decoded = base64.b64decode(authorization[6:], validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
except (ValueError, UnicodeDecodeError, binascii.Error):
raise ApiError(401, "unauthorized", "Неверные credentials")
with self.state.lock:
user = self.state.users.get(self.state.usernames.get(username, ""))
if not user or not self._password_matches(password, user["_password_hash"]):
raise ApiError(401, "unauthorized", "Неверные credentials")
expires = time.time() + int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
token = secrets.token_urlsafe(32)
with self.state.lock:
self.state.sessions[token] = {"user_id": user["id"], "expires_at": expires, "revoked": False}
self.state.execute("INSERT INTO sessions (token,user_id,expires_at) VALUES (%s,%s,to_timestamp(%s))",
(token, user["id"], expires))
expires_at = datetime.fromtimestamp(expires, timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
return {"token": token, "token_type": "Bearer", "expires_at": expires_at,
"user": self.public_user(user)}
def revoke_session(self, headers):
authorization = headers.get("Authorization", "")
if not authorization.startswith("Bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer-сессия")
token = authorization[7:].strip()
self.actor(headers)
with self.state.lock:
self.state.sessions[token]["revoked"] = True
self.state.execute("UPDATE sessions SET revoked=TRUE WHERE token=%s", (token,))
def current_user(self, headers):
return self.public_user(self.actor(headers))
def create_chat(self, headers, body):
actor = self.actor(headers)
validate_object(body, ("title", "member_ids"), ("title", "member_ids"))
members = body["member_ids"]
if not validate_text(body["title"], 100) or not isinstance(members, list) or not 1 <= len(members) <= 100:
raise ApiError(400, "invalid_request", "Некорректные данные чата")
if not all(isinstance(item, str) and require_uuid(item) for item in members):
raise ApiError(400, "invalid_request", "Некорректный список участников")
if len(set(members)) != len(members):
raise ApiError(400, "invalid_request", "Некорректный список участников")
with self.state.lock:
if actor["id"] not in members:
raise ApiError(400, "invalid_request", "Вызывающий должен быть участником")
if any(member not in self.state.users for member in members):
raise ApiError(400, "invalid_request", "Неизвестный участник")
chat = {"id": str(uuid.uuid4()), "title": body["title"], "member_ids": members, "created_at": now()}
self.state.chats[chat["id"]] = chat
self.state.messages[chat["id"]] = []
self.state.transaction([
("INSERT INTO chats (id,title,created_at) VALUES (%s,%s,%s)",
(chat["id"], chat["title"], chat["created_at"])),
("INSERT INTO chat_members (chat_id,user_id) VALUES " + ",".join(["(%s,%s)"] * len(members)),
tuple(value for member in members for value in (chat["id"], member))),
])
return chat
def accessible_chat(self, chat_id, actor):
if not require_uuid(chat_id):
raise ApiError(400, "invalid_request", "Некорректный UUID чата")
with self.state.lock:
chat = self.state.chats.get(chat_id)
if not chat or actor["id"] not in chat["member_ids"]:
raise ApiError(404, "not_found", "Объект не найден")
return chat
def list_chats(self, headers, query):
actor = self.actor(headers)
limit = self.limit(query)
cursor = query.get("cursor", [None])[0]
with self.state.lock:
chats = [chat for chat in self.state.chats.values() if actor["id"] in chat["member_ids"]]
chats.sort(key=lambda item: (item["created_at"], item["id"]))
if cursor:
try:
padded_cursor = cursor + "=" * (-len(cursor) % 4)
cursor_time, cursor_id = base64.urlsafe_b64decode(padded_cursor.encode()).decode().split("|", 1)
except (ValueError, UnicodeDecodeError, binascii.Error):
raise ApiError(400, "invalid_request", "Некорректный cursor")
if not require_uuid(cursor_id) or not any(
item["id"] == cursor_id and item["created_at"] == cursor_time for item in chats
):
raise ApiError(400, "invalid_request", "Cursor не принадлежит этому списку")
chats = [item for item in chats if (item["created_at"], item["id"]) > (cursor_time, cursor_id)]
page = chats[:limit]
next_cursor = None
if len(chats) > limit:
last = page[-1]
next_cursor = base64.urlsafe_b64encode(
(last["created_at"] + "|" + last["id"]).encode()
).decode().rstrip("=")
return {"items": page, "next_cursor": next_cursor}
def get_chat(self, headers, chat_id):
return self.accessible_chat(chat_id, self.actor(headers))
def create_message(self, headers, chat_id, body):
actor = self.actor(headers)
chat = self.accessible_chat(chat_id, actor)
validate_object(body, ("text",), ("text",))
if not validate_text(body["text"], 4000):
raise ApiError(400, "invalid_request", "Сообщение не может быть пустым")
with self.state.lock:
message = {"id": str(uuid.uuid4()), "chat_id": chat["id"], "sender_id": actor["id"], "text": body["text"], "created_at": now()}
self.state.messages[chat_id].append(message)
self.state.execute(
"INSERT INTO messages (id,chat_id,sender_id,text,created_at) VALUES (%s,%s,%s,%s,%s)",
(message["id"], chat_id, actor["id"], message["text"], message["created_at"]))
return message
def limit(self, query):
raw = query.get("limit", ["50"])[0]
try:
value = int(raw)
except ValueError:
raise ApiError(400, "invalid_request", "Некорректный limit")
if not 1 <= value <= 100:
raise ApiError(400, "invalid_request", "limit должен быть от 1 до 100")
return value
def list_messages(self, headers, chat_id, query):
actor = self.actor(headers)
self.accessible_chat(chat_id, actor)
limit = self.limit(query)
cursor = query.get("cursor", [None])[0]
with self.state.lock:
messages = list(self.state.messages[chat_id])
messages.sort(key=lambda item: (item["created_at"], item["id"]))
if cursor:
try:
padded_cursor = cursor + "=" * (-len(cursor) % 4)
cursor_time, cursor_id = base64.urlsafe_b64decode(padded_cursor.encode()).decode().split("|", 1)
except (ValueError, UnicodeDecodeError, binascii.Error):
raise ApiError(400, "invalid_request", "Некорректный cursor")
if not require_uuid(cursor_id) or not any(item["id"] == cursor_id and item["created_at"] == cursor_time for item in messages):
raise ApiError(400, "invalid_request", "Cursor не принадлежит этому чату")
messages = [item for item in messages if (item["created_at"], item["id"]) > (cursor_time, cursor_id)]
page = messages[:limit]
next_cursor = None
if len(messages) > limit:
last = page[-1]
next_cursor = base64.urlsafe_b64encode((last["created_at"] + "|" + last["id"]).encode()).decode().rstrip("=")
return {"items": page, "next_cursor": next_cursor}