feat: add authenticated search frontend
This commit is contained in:
1 parent
93e5fc5837
commit
0a30adb85f
20 files changed
+885
-113
No files matched your search
+125
-10
@@ -4,12 +4,16 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import getpass
|
||||
import http.cookies
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import urllib.parse
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from search.auth import AuthError, AuthStore
|
||||
from search.minjust_opensearch import APP_VERSION, request_json
|
||||
from search.catalog import CATALOGS, labels
|
||||
from search.query import build_search_query
|
||||
@@ -60,11 +64,20 @@ def date(value: str | None, name: str) -> str | None:
|
||||
|
||||
|
||||
def openapi() -> dict:
|
||||
responses = {"200": {"description": "Successful response"}, "400": {"description": "Invalid request"}, "404": {"description": "Not found"}, "502": {"description": "Search backend unavailable"}}
|
||||
responses = {"200": {"description": "Successful response"}, "400": {"description": "Invalid request"}, "401": {"description": "Authentication required"}, "403": {"description": "Additional access required"}, "404": {"description": "Not found"}, "502": {"description": "Search backend unavailable"}}
|
||||
return {
|
||||
"openapi": "3.0.3",
|
||||
"info": {"title": "Akyldash Search API", "version": API_VERSION},
|
||||
"components": {"securitySchemes": {"SessionCookie": {"type": "apiKey", "in": "cookie", "name": "akyldash_session"}}},
|
||||
"security": [{"SessionCookie": []}],
|
||||
"paths": {
|
||||
"/auth/login": {"post": {"security": [], "responses": {"200": {"description": "Signed in and session cookie issued"}, "401": {"description": "Invalid login or password"}}}},
|
||||
"/auth/logout": {"post": {"responses": {"200": {"description": "Signed out"}}}},
|
||||
"/auth/me": {"get": {"responses": {"200": {"description": "Current account"}, "401": {"description": "Authentication required"}}}},
|
||||
"/auth/change-password": {"post": {"responses": {"200": {"description": "Password changed"}, "400": {"description": "Invalid password"}}}},
|
||||
"/admin/users": {"get": {"responses": {"200": {"description": "User list"}}}, "post": {"responses": {"201": {"description": "User created with a temporary password"}}}},
|
||||
"/admin/users/{username}": {"delete": {"responses": {"200": {"description": "User deleted"}}}},
|
||||
"/admin/users/{username}/reset-password": {"post": {"responses": {"200": {"description": "Temporary password set"}}}},
|
||||
"/search": {"get": {"responses": responses, "parameters": [
|
||||
{"name": "q", "in": "query", "required": True, "schema": {"type": "string"}},
|
||||
{"name": "language", "in": "query", "schema": {"type": "string", "enum": ["ru", "ky"]}},
|
||||
@@ -90,12 +103,14 @@ def openapi() -> dict:
|
||||
|
||||
|
||||
class Api:
|
||||
def __init__(self, base_url: str, index: str, data_root: Path, reviews_db: Path | str = ":memory:", review_secret: bytes | None = None):
|
||||
def __init__(self, base_url: str, index: str, data_root: Path, reviews_db: Path | str = ":memory:", review_secret: bytes | None = None, users_db: Path | str = ":memory:", cookie_secure: bool = False):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.index = index
|
||||
self.data_root = data_root
|
||||
self.review_store = ReviewStore(reviews_db)
|
||||
self.review_snapshots = ReviewSnapshots(review_secret)
|
||||
self.auth_store = AuthStore(users_db)
|
||||
self.cookie_secure = cookie_secure
|
||||
|
||||
def search_url(self, suffix: str) -> str:
|
||||
return f"{self.base_url}/{urllib.parse.quote(self.index, safe='')}/{suffix}"
|
||||
@@ -242,12 +257,12 @@ class Api:
|
||||
raise ApiError(404, "edition language not found")
|
||||
return {"api_version": API_VERSION, "edition": metadata, "content": content}
|
||||
|
||||
def save_review(self, body: dict) -> dict:
|
||||
def save_review(self, body: dict, username: str) -> dict:
|
||||
if not isinstance(body, dict):
|
||||
raise ApiError(400, "request body must be an object")
|
||||
try:
|
||||
snapshot = self.review_snapshots.verify(body["review_token"])
|
||||
reviewer = body["reviewer"].strip()
|
||||
reviewer = username
|
||||
overall_comment = body.get("overall_comment", "").strip()
|
||||
submitted = body["results"]
|
||||
except (KeyError, AttributeError, TypeError, ValueError) as error:
|
||||
@@ -288,12 +303,49 @@ class Api:
|
||||
except (OSError, UnicodeError) as error:
|
||||
raise ApiError(500, "review interface is unavailable") from error
|
||||
|
||||
def handle(self, method: str, path: str, body: dict | None = None) -> tuple[int, dict]:
|
||||
def handle(self, method: str, path: str, body: dict | None = None, user: dict | None = None) -> tuple[int, dict]:
|
||||
parsed = urllib.parse.urlsplit(path)
|
||||
query = urllib.parse.parse_qs(parsed.query, keep_blank_values=True)
|
||||
parts = [urllib.parse.unquote(part) for part in parsed.path.split("/") if part]
|
||||
if method == "POST" and parts == ["auth", "login"]:
|
||||
try:
|
||||
token, account = self.auth_store.login(body.get("username"), body.get("password"))
|
||||
return 200, {"account": account, "session_token": token}
|
||||
except AuthError as error:
|
||||
raise ApiError(401, str(error)) from error
|
||||
if method == "POST" and parts == ["auth", "logout"]:
|
||||
return 200, {"ok": True}
|
||||
if method == "GET" and parts == ["auth", "me"]:
|
||||
return 200, {"account": user}
|
||||
if method == "POST" and parts == ["auth", "change-password"]:
|
||||
try:
|
||||
self.auth_store.change_password(user["username"], body.get("current_password"), body.get("new_password"))
|
||||
token, account = self.auth_store.login(user["username"], body.get("new_password"))
|
||||
return 200, {"account": account, "session_token": token}
|
||||
except AuthError as error:
|
||||
raise ApiError(400, str(error)) from error
|
||||
if user and user["username"].casefold() == "admin" and method == "GET" and parts == ["admin", "users"]:
|
||||
return 200, {"users": self.auth_store.list_users()}
|
||||
if user and user["username"].casefold() == "admin" and method == "POST" and parts == ["admin", "users"]:
|
||||
try:
|
||||
self.auth_store.create_user(body.get("username"), body.get("password"))
|
||||
return 201, {"ok": True}
|
||||
except AuthError as error:
|
||||
raise ApiError(400, str(error)) from error
|
||||
if user and user["username"].casefold() == "admin" and method == "DELETE" and len(parts) == 3 and parts[:2] == ["admin", "users"]:
|
||||
try:
|
||||
self.auth_store.delete_user(parts[2])
|
||||
return 200, {"ok": True}
|
||||
except AuthError as error:
|
||||
raise ApiError(400, str(error)) from error
|
||||
if user and user["username"].casefold() == "admin" and method == "POST" and len(parts) == 4 and parts[:2] == ["admin", "users"] and parts[3] == "reset-password":
|
||||
try:
|
||||
self.auth_store.reset_password(parts[2], body.get("password"))
|
||||
return 200, {"ok": True}
|
||||
except AuthError as error:
|
||||
raise ApiError(400, str(error)) from error
|
||||
if method == "POST" and parts == ["search-reviews"]:
|
||||
return 201, self.save_review(body)
|
||||
return 201, self.save_review(body, user["username"] if user else body.get("reviewer", ""))
|
||||
if method == "GET" and parts == ["search-reviews", "export"]:
|
||||
return 200, {"api_version": API_VERSION, "reviews": self.review_store.export()}
|
||||
if method != "GET":
|
||||
@@ -317,28 +369,61 @@ def handler(api: Api):
|
||||
class RequestHandler(BaseHTTPRequestHandler):
|
||||
def respond(self, method: str):
|
||||
try:
|
||||
if method == "GET" and urllib.parse.urlsplit(self.path).path == "/review":
|
||||
route = urllib.parse.urlsplit(self.path).path
|
||||
cookies = http.cookies.SimpleCookie(self.headers.get("Cookie", ""))
|
||||
session = cookies.get("akyldash_session")
|
||||
token = session.value if session else None
|
||||
user = api.auth_store.user_for_token(token)
|
||||
if method == "GET" and route in {"/", "/review"}:
|
||||
body = api.review_page().encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("X-Frame-Options", "DENY")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if not (method == "POST" and route in {"/auth/login", "/auth/logout"}):
|
||||
if not user:
|
||||
raise ApiError(401, "authentication required")
|
||||
if user["must_change_password"] and not (method == "POST" and route == "/auth/change-password") and not (method == "GET" and route == "/auth/me"):
|
||||
raise ApiError(403, "change password before continuing")
|
||||
if route.startswith("/admin/users") and user["username"].casefold() != "admin":
|
||||
raise ApiError(403, "admin account required")
|
||||
body = None
|
||||
if method == "POST":
|
||||
if method in {"POST", "DELETE"}:
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
if length > 1_000_000:
|
||||
raise ApiError(413, "request body is too large")
|
||||
body = json.loads(self.rfile.read(length) or b"{}")
|
||||
status, payload = api.handle(method, self.path, body)
|
||||
if not isinstance(body, dict):
|
||||
raise ApiError(400, "request body must be a JSON object")
|
||||
if method == "POST" and route == "/auth/logout":
|
||||
api.auth_store.logout(token)
|
||||
status, payload = api.handle(method, self.path, body, user)
|
||||
except json.JSONDecodeError:
|
||||
status, payload = 400, {"api_version": API_VERSION, "error": "request body must be valid JSON"}
|
||||
except ApiError as error:
|
||||
status, payload = error.status, {"api_version": API_VERSION, "error": error.message}
|
||||
except (ValueError, http.cookies.CookieError):
|
||||
status, payload = 400, {"api_version": API_VERSION, "error": "invalid request"}
|
||||
session_token = payload.pop("session_token", None) if isinstance(payload, dict) else None
|
||||
body = json.dumps(payload, ensure_ascii=False).encode()
|
||||
self.send_response(status)
|
||||
if session_token:
|
||||
secure = "; Secure" if api.cookie_secure else ""
|
||||
self.send_header("Set-Cookie", f"akyldash_session={session_token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=43200{secure}")
|
||||
elif method == "POST" and urllib.parse.urlsplit(self.path).path == "/auth/logout":
|
||||
secure = "; Secure" if api.cookie_secure else ""
|
||||
self.send_header("Set-Cookie", f"akyldash_session=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0{secure}")
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("X-Frame-Options", "DENY")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
@@ -349,6 +434,9 @@ def handler(api: Api):
|
||||
def do_POST(self):
|
||||
self.respond("POST")
|
||||
|
||||
def do_DELETE(self):
|
||||
self.respond("DELETE")
|
||||
|
||||
def log_message(self, format: str, *args):
|
||||
return
|
||||
|
||||
@@ -361,13 +449,40 @@ def main() -> int:
|
||||
parser.add_argument("--index", default="akyldash-fragments-current")
|
||||
parser.add_argument("--data", type=Path, default=Path("data/minjust-normalized"))
|
||||
parser.add_argument("--reviews-db", type=Path, default=Path("data/search-reviews.sqlite3"))
|
||||
parser.add_argument("--users-db", type=Path, default=Path("data/search-users.sqlite3"))
|
||||
parser.add_argument("--review-secret", default=None)
|
||||
parser.add_argument("--cookie-secure", action=argparse.BooleanOptionalAction, default=os.environ.get("COOKIE_SECURE", "false").lower() == "true")
|
||||
parser.add_argument("--create-admin", action="store_true", help="create the initial admin account and exit")
|
||||
parser.add_argument("--reset-admin-password", action="store_true", help="set a temporary password for admin and exit")
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=8080)
|
||||
parser.add_argument("--version", action="version", version=APP_VERSION)
|
||||
arguments = parser.parse_args()
|
||||
secret = arguments.review_secret.encode() if arguments.review_secret else None
|
||||
ThreadingHTTPServer((arguments.host, arguments.port), handler(Api(arguments.url, arguments.index, arguments.data, arguments.reviews_db, secret))).serve_forever()
|
||||
api = Api(arguments.url, arguments.index, arguments.data, arguments.reviews_db, secret, arguments.users_db, arguments.cookie_secure)
|
||||
if arguments.create_admin or arguments.reset_admin_password:
|
||||
users = api.auth_store.list_users()
|
||||
admin_exists = any(user["username"].casefold() == "admin" for user in users)
|
||||
if arguments.create_admin and users:
|
||||
parser.error("accounts already exist")
|
||||
if arguments.reset_admin_password and not admin_exists:
|
||||
parser.error("admin account does not exist")
|
||||
if arguments.create_admin and arguments.reset_admin_password:
|
||||
parser.error("choose either --create-admin or --reset-admin-password")
|
||||
password = getpass.getpass("Password for admin (12+ characters): ")
|
||||
confirm = getpass.getpass("Confirm password: ")
|
||||
if password != confirm:
|
||||
parser.error("passwords do not match")
|
||||
try:
|
||||
if arguments.create_admin:
|
||||
api.auth_store.create_admin(password)
|
||||
else:
|
||||
api.auth_store.reset_password("admin", password)
|
||||
except AuthError as error:
|
||||
parser.error(str(error))
|
||||
print("Initial admin account created." if arguments.create_admin else "Admin password reset. Change it at next sign-in.")
|
||||
return 0
|
||||
ThreadingHTTPServer((arguments.host, arguments.port), handler(api)).serve_forever()
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user