181 lines
9.3 KiB
Python
181 lines
9.3 KiB
Python
"""Persistent implementation of lab1 operations and lab2 sessions."""
|
|
import base64
|
|
from datetime import datetime
|
|
import hashlib
|
|
import hmac
|
|
import os
|
|
import re
|
|
import secrets
|
|
from uuid import UUID, uuid4
|
|
|
|
import psycopg
|
|
|
|
from .common import APIError, fields, invalid, string_value, uuid_value
|
|
from .database import pool
|
|
from .pagination import Pagination
|
|
|
|
|
|
def record(row):
|
|
return {k: (str(v) if isinstance(v, UUID) else
|
|
v.isoformat(timespec="microseconds").replace("+00:00", "Z")
|
|
if isinstance(v, datetime) else v) for k, v in row.items()}
|
|
|
|
|
|
def password_hash(password, salt=None):
|
|
salt = salt or secrets.token_hex(16)
|
|
derived = hashlib.scrypt(password.encode("utf-8"), salt=bytes.fromhex(salt),
|
|
n=16384, r=8, p=1, dklen=32)
|
|
return "scrypt$16384$8$1$" + salt + "$" + derived.hex()
|
|
|
|
|
|
def unauthorized():
|
|
return APIError(401, "unauthorized", "Valid credentials required")
|
|
|
|
|
|
class Store(Pagination):
|
|
def __init__(self):
|
|
self.pool = pool()
|
|
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
|
if self.ttl <= 0:
|
|
raise ValueError("SESSION_TTL_SECONDS must be positive")
|
|
with self.pool.connection() as conn:
|
|
self.cursor_key = bytes.fromhex(conn.execute("SELECT value FROM settings WHERE key='cursor_key'").fetchone()["value"])
|
|
self.dummy_hash = password_hash("dummy-password-not-a-user")
|
|
|
|
def ready(self):
|
|
with self.pool.connection() as conn:
|
|
conn.execute("SELECT 1 FROM schema_migrations LIMIT 1").fetchone()
|
|
|
|
def authenticate(self, header):
|
|
if not isinstance(header, str) or not re.fullmatch(r"(?i:Bearer) [A-Za-z0-9_-]{43}", header):
|
|
raise unauthorized()
|
|
digest = hashlib.sha256(header.split(" ", 1)[1].encode()).hexdigest()
|
|
with self.pool.connection() as conn:
|
|
row = conn.execute("SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at>clock_timestamp()", (digest,)).fetchone()
|
|
if not row:
|
|
raise unauthorized()
|
|
return (str(row["user_id"]), digest)
|
|
|
|
def login(self, header):
|
|
try:
|
|
scheme, encoded = header.split(" ", 1)
|
|
if scheme.lower() != "basic":
|
|
raise ValueError()
|
|
username, password = base64.b64decode(encoded, validate=True).decode("utf-8").split(":", 1)
|
|
if not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128:
|
|
raise ValueError()
|
|
except (AttributeError, ValueError, UnicodeError):
|
|
raise unauthorized() from None
|
|
with self.pool.connection() as conn:
|
|
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
|
|
expected = row["password_hash"] if row else self.dummy_hash
|
|
actual = password_hash(password, expected.split("$")[4])
|
|
if not hmac.compare_digest(actual, expected) or row is None:
|
|
raise unauthorized()
|
|
del row["password_hash"]
|
|
token = secrets.token_urlsafe(32)
|
|
digest = hashlib.sha256(token.encode()).hexdigest()
|
|
with self.pool.connection() as conn:
|
|
expiry = conn.execute("INSERT INTO sessions VALUES (%s,%s,clock_timestamp()+%s*interval '1 second') RETURNING expires_at", (digest, row["id"], self.ttl)).fetchone()
|
|
return 201, {"token": token, "token_type": "Bearer", "expires_at": record(expiry)["expires_at"], "user": record(row)}
|
|
|
|
def chat(self, conn, value, actor, lock=False):
|
|
chat_id = uuid_value(value)
|
|
row = conn.execute("SELECT c.* FROM chats c WHERE c.id=%s AND EXISTS "
|
|
"(SELECT 1 FROM memberships m WHERE m.chat_id=c.id AND m.user_id=%s)" +
|
|
(" FOR UPDATE OF c" if lock else ""), (chat_id, actor[0])).fetchone()
|
|
if not row:
|
|
raise APIError(404, "not_found", "Object not found")
|
|
row = record(row)
|
|
row["member_ids"] = [str(m["user_id"]) for m in conn.execute("SELECT user_id FROM memberships WHERE chat_id=%s ORDER BY ordinal", (chat_id,))]
|
|
return row
|
|
|
|
def check_chat(self, value, actor):
|
|
with self.pool.connection() as conn:
|
|
self.chat(conn, value, actor)
|
|
|
|
def page(self, conn, query, scope, table, actor=None, chat_id=None):
|
|
limit, after = self.decode_page(query, scope)
|
|
# Table and predicate are selected internally, never supplied by a client.
|
|
if table == "messages":
|
|
sql = "SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s"
|
|
params = [chat_id]
|
|
else:
|
|
sql = "SELECT c.* FROM chats c WHERE EXISTS (SELECT 1 FROM memberships m WHERE m.chat_id=c.id AND m.user_id=%s)"
|
|
params = [actor[0]]
|
|
if after:
|
|
sql += " AND (created_at,id)>(%s::timestamptz,%s::uuid)"
|
|
params.extend(after)
|
|
sql += " ORDER BY created_at,id LIMIT %s"
|
|
params.append(limit + 1)
|
|
rows = [record(r) for r in conn.execute(sql, params)]
|
|
items = rows[:limit]
|
|
if table == "chats":
|
|
items = [self.chat(conn, r["id"], actor) for r in items]
|
|
return {"items": items, "next_cursor": self.cursor(scope, items[-1]) if len(rows) > limit else None}
|
|
|
|
def dispatch(self, method, path, query, actor, read_body):
|
|
if path == "/api/v1/users" and method == "POST":
|
|
body = read_body()
|
|
fields(body, ("username", "display_name", "password"))
|
|
username = body["username"]
|
|
if not isinstance(username, str) or not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
|
raise invalid()
|
|
display = string_value(body["display_name"], 100)
|
|
password = string_value(body["password"], 128)
|
|
if len(password) < 12:
|
|
raise invalid()
|
|
hashed = password_hash(password)
|
|
try:
|
|
with self.pool.connection() as conn:
|
|
row = conn.execute("INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at", (uuid4(), username, display, hashed)).fetchone()
|
|
return 201, record(row)
|
|
except psycopg.errors.UniqueViolation:
|
|
raise APIError(409, "conflict", "Username already exists") from None
|
|
with self.pool.connection() as conn:
|
|
if path == "/api/v1/auth/sessions/current" and method == "DELETE":
|
|
deleted = conn.execute("DELETE FROM sessions WHERE token_hash=%s RETURNING user_id", (actor[1],)).fetchone()
|
|
if not deleted:
|
|
raise unauthorized()
|
|
return 204, None
|
|
if path == "/api/v1/users/me" and method == "GET":
|
|
return 200, record(conn.execute("SELECT id,username,display_name,created_at FROM users WHERE id=%s", (actor[0],)).fetchone())
|
|
if path == "/api/v1/chats":
|
|
if method == "GET":
|
|
return 200, self.page(conn, query, "chats:" + actor[0], "chats", actor=actor)
|
|
if method == "POST":
|
|
body = read_body()
|
|
fields(body, ("title", "member_ids"))
|
|
title = string_value(body["title"], 100)
|
|
members = body["member_ids"]
|
|
if not isinstance(members, list) or not 1 <= len(members) <= 100:
|
|
raise invalid()
|
|
members = [uuid_value(m) for m in members]
|
|
if len(set(members)) != len(members) or actor[0] not in members:
|
|
raise invalid()
|
|
row = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *", (uuid4(), title)).fetchone()
|
|
existing = conn.execute("SELECT id FROM users WHERE id=ANY(%s::uuid[])", (members,)).fetchall()
|
|
if len(existing) != len(members):
|
|
raise invalid() # Rolls back the chat INSERT as well.
|
|
with conn.cursor() as cur:
|
|
cur.executemany("INSERT INTO memberships VALUES (%s,%s,%s)", [(row["id"], m, i) for i, m in enumerate(members)])
|
|
return 201, dict(record(row), member_ids=members)
|
|
match = re.fullmatch(r"/api/v1/chats/([^/]+)(/messages)?", path)
|
|
if match:
|
|
chat = self.chat(conn, match[1], actor, lock=method == "POST")
|
|
if match[2] is None and method == "GET":
|
|
return 200, chat
|
|
if match[2] == "/messages":
|
|
if method == "GET":
|
|
return 200, self.page(conn, query, "messages:" + chat["id"], "messages", chat_id=chat["id"])
|
|
if method == "POST":
|
|
body = read_body()
|
|
fields(body, ("text",))
|
|
text = string_value(body["text"], 4000)
|
|
row = conn.execute("INSERT INTO messages VALUES (%s,%s,%s,%s,GREATEST(clock_timestamp(), "
|
|
"COALESCE((SELECT created_at+interval '1 microsecond' FROM messages "
|
|
"WHERE chat_id=%s ORDER BY created_at DESC,id DESC LIMIT 1),clock_timestamp()))) RETURNING *",
|
|
(uuid4(), chat["id"], actor[0], text, chat["id"])).fetchone()
|
|
return 201, record(row)
|
|
raise APIError(404, "not_found", "Object not found")
|