90 lines
3.6 KiB
Python
90 lines
3.6 KiB
Python
"""JSON HTTP API, exposed as a WSGI application."""
|
|
|
|
from contextlib import closing
|
|
import hmac
|
|
from http import HTTPStatus
|
|
import json
|
|
import re
|
|
from urllib.parse import parse_qs
|
|
|
|
from . import store
|
|
from .core import discover
|
|
|
|
|
|
class RequestError(Exception):
|
|
def __init__(self, status, message):
|
|
self.status = status
|
|
super().__init__(message)
|
|
|
|
|
|
def read_draft(env, types):
|
|
if env.get("CONTENT_TYPE", "").split(";")[0].strip().lower() != "application/json":
|
|
raise RequestError(415, "expected application/json")
|
|
length = int(env.get("CONTENT_LENGTH") or 0)
|
|
if length > 1024 * 1024:
|
|
raise RequestError(413, "body exceeds 1 MiB")
|
|
if length <= 0:
|
|
raise ValueError("expected a JSON body with a positive Content-Length")
|
|
payload = json.loads(env["wsgi.input"].read(length).decode("utf-8"))
|
|
if not isinstance(payload, dict) or payload.keys() != {"type", "fields"}:
|
|
raise ValueError("expected type and fields")
|
|
kind = payload["type"]
|
|
if not isinstance(kind, str) or kind not in types:
|
|
raise ValueError("unknown content type")
|
|
types[kind].validate(payload["fields"])
|
|
return kind, payload["fields"]
|
|
|
|
|
|
def create_app(database, write_token):
|
|
if not write_token or not write_token.isascii() or any(c.isspace() for c in write_token):
|
|
raise ValueError("MICA_WRITE_TOKEN must be a non-empty ASCII token without spaces")
|
|
types = discover()
|
|
store.initialize(database)
|
|
|
|
def dispatch(env, db):
|
|
method = env["REQUEST_METHOD"]
|
|
path = env["PATH_INFO"]
|
|
item = re.fullmatch(r"/content/([0-9a-f]{32})(/publish)?", path)
|
|
if path != "/content" and item is None:
|
|
raise RequestError(404, "not found")
|
|
allowed = ("GET", "POST") if item is None else (("POST",) if item[2] else ("GET",))
|
|
if method not in allowed:
|
|
return 405, {"error": "method not allowed"}, [("Allow", ", ".join(allowed))]
|
|
if method == "POST":
|
|
actual = env.get("HTTP_AUTHORIZATION", "").encode("latin-1")
|
|
if not hmac.compare_digest(actual, ("Bearer " + write_token).encode("ascii")):
|
|
return 401, {"error": "writer token required"}, [("WWW-Authenticate", "Bearer")]
|
|
if item is None:
|
|
kind, fields = read_draft(env, types)
|
|
return 201, store.draft(db, kind, fields), []
|
|
result = store.publish(db, item[1])
|
|
elif item is None:
|
|
query = parse_qs(env.get("QUERY_STRING", ""))
|
|
kind = query.get("type", [None])[0]
|
|
limit = int(query.get("limit", ["20"])[0])
|
|
offset = int(query.get("offset", ["0"])[0])
|
|
if not (1 <= limit <= 100 and 0 <= offset <= 2**63 - 1):
|
|
raise ValueError("invalid pagination")
|
|
return 200, store.list_public(db, kind, limit, offset), []
|
|
else:
|
|
result = store.get_public(db, item[1])
|
|
if result is None:
|
|
raise RequestError(404, "not found")
|
|
return 200, result, []
|
|
|
|
def application(env, start_response):
|
|
try:
|
|
with closing(store.connect(database)) as db, db:
|
|
status, payload, headers = dispatch(env, db)
|
|
except RequestError as error:
|
|
status, payload, headers = error.status, {"error": str(error)}, []
|
|
except (ValueError, RecursionError):
|
|
status, payload, headers = 400, {"error": "invalid request"}, []
|
|
body = json.dumps(payload).encode("utf-8")
|
|
start_response(f"{status} {HTTPStatus(status).phrase}", headers + [
|
|
("Content-Type", "application/json"), ("Content-Length", str(len(body))),
|
|
])
|
|
return [body]
|
|
|
|
return application
|