86 lines
3.7 KiB
Python
86 lines
3.7 KiB
Python
"""JSON HTTP API, exposed as a WSGI application."""
|
|
|
|
import hmac
|
|
from http import HTTPStatus
|
|
import json
|
|
import re
|
|
from urllib.parse import parse_qs
|
|
|
|
from .core import Runtime
|
|
from .publishing import bundled_plugins
|
|
|
|
|
|
class RequestError(Exception):
|
|
def __init__(self, status, message):
|
|
self.status = status
|
|
super().__init__(message)
|
|
|
|
|
|
def read_draft(env):
|
|
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")
|
|
return payload["type"], payload["fields"]
|
|
|
|
|
|
def create_app(database, write_token, *, enabled=None):
|
|
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")
|
|
runtime = Runtime(database, bundled_plugins(), enabled=enabled)
|
|
|
|
def dispatch(env):
|
|
if "content" not in runtime.registry.snippets:
|
|
raise RequestError(404, "not found")
|
|
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)
|
|
return 201, runtime.call("content.draft", kind=kind, fields=fields), []
|
|
result = runtime.call("content.publish", identifier=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, runtime.call("content.list", kind=kind, limit=limit, offset=offset), []
|
|
else:
|
|
result = runtime.call("content.get", identifier=item[1])
|
|
if result is None:
|
|
raise RequestError(404, "not found")
|
|
return 200, result, []
|
|
|
|
def application(env, start_response):
|
|
try:
|
|
status, payload, headers = dispatch(env)
|
|
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]
|
|
|
|
application.close = runtime.close
|
|
return application
|