Serve permissioned graph queries and atomic mutations across isolated sites

This commit is contained in:
2026-12-03 04:50:19 +08:00
parent 455e83551b
commit e90d551eea
9 changed files with 740 additions and 13 deletions
+15 -4
View File
@@ -1,19 +1,30 @@
from contextlib import closing
import json
import os
from wsgiref.simple_server import make_server
from .api import create_app
from .gateway import GraphApp
def main():
names = os.getenv("MICA_PLUGINS")
enabled = None if names is None else [name.strip() for name in names.split(",") if name.strip()]
app = create_app(os.getenv("MICA_DATABASE", "postgresql:///mica"),
os.getenv("MICA_WRITE_TOKEN"), enabled=enabled)
sites_file = os.getenv("MICA_SITES_FILE")
if sites_file:
with open(sites_file, encoding="utf-8") as config:
app = GraphApp(json.load(config))
else:
app = legacy_app()
with closing(app), make_server("127.0.0.1", int(os.getenv("MICA_PORT", "8000")), app) as server:
print(f"MICA listening on http://127.0.0.1:{server.server_port}", flush=True)
server.serve_forever()
def legacy_app():
names = os.getenv("MICA_PLUGINS")
enabled = None if names is None else [name.strip() for name in names.split(",") if name.strip()]
return create_app(os.getenv("MICA_DATABASE", "postgresql:///mica"),
os.getenv("MICA_WRITE_TOKEN"), enabled=enabled)
if __name__ == "__main__":
main()
+26 -6
View File
@@ -1,9 +1,11 @@
"""Load plugins, materialize their models and dispatch transactional calls."""
from contextlib import contextmanager
from dataclasses import dataclass
from sqlalchemy.orm import Session
from .database import connect, materialize
from .protocol import Principal, validate_arguments
from .plugins import Plugin, Registry, Snippet
# Keep the original content extension imports usable by installed plugins.
@@ -16,30 +18,48 @@ __all__ = ["Runtime", "Call", "Plugin", "Registry", "Snippet", "ContentType", "d
class Call:
registry: Registry
session: Session
principal: Principal | None = None
@property
def db(self):
self.session.flush()
return self.session.connection()
def call(self, operation, **parameters):
def call(self, operation, /, **parameters):
action = self.registry.actions.get(operation)
if action is not None:
if self.principal is None:
raise PermissionError("public actions require a caller")
self.principal.require(action.grant)
validate_arguments(action, parameters)
handler = self.registry.operations[operation]
return handler(self, **parameters)
class Runtime:
def __init__(self, database, plugins=(), *, enabled=None):
def __init__(self, database, plugins=(), *, enabled=None, site=None):
self.site = site
self.registry = Registry.load(plugins, enabled)
self.engine = connect(database)
try:
materialize(self.engine, self.registry)
materialize(self.engine, self.registry, site=site)
except BaseException:
self.engine.dispose()
raise
def call(self, operation, **parameters):
with Session(self.engine, expire_on_commit=False) as session, session.begin():
return Call(self.registry, session).call(operation, **parameters)
@contextmanager
def transaction(self, principal=None):
if self.site is not None and (principal is None or principal.site != self.site):
raise PermissionError("site mismatch")
# Own the outer transaction even when a handler flushes or commits its ORM session.
with self.engine.begin() as connection:
with Session(connection, expire_on_commit=False, join_transaction_mode="rollback_only") as session:
yield Call(self.registry, session, principal)
session.flush()
def call(self, operation, /, **parameters):
with self.transaction() as call:
return call.call(operation, **parameters)
def close(self):
self.engine.dispose()
+51 -2
View File
@@ -6,7 +6,7 @@ from os import PathLike
from alembic.autogenerate import compare_metadata
from alembic.migration import MigrationContext
from alembic.operations import Operations
from sqlalchemy import JSON, Column, MetaData, String, Table, create_engine, event, inspect, select, text
from sqlalchemy import JSON, Column, Integer, MetaData, String, Table, create_engine, event, inspect, select, text
from sqlalchemy.engine import URL, make_url
@@ -49,17 +49,65 @@ def startup_transaction(engine):
db.execute(text("SELECT RELEASE_LOCK('mica.core.startup')"))
def materialize(engine, registry):
system = MetaData()
site_binding = Table("mica_site", system, Column("slot", Integer, primary_key=True),
Column("site", String(63), nullable=False))
receipts = Table("mica_receipts", system, Column("subject", String(128), primary_key=True),
Column("key_hash", String(64), primary_key=True),
Column("digest", String(64), nullable=False), Column("result", JSON))
revisions = Table("mica_plugin_revisions", system, Column("plugin", String(63), primary_key=True),
Column("version", Integer, primary_key=True))
def bind_site(db, site):
if site is None and not inspect(db).has_table(site_binding.name):
return
site_binding.create(db, checkfirst=True)
bound = db.scalar(select(site_binding.c.site))
if bound is None and site is not None:
db.execute(site_binding.insert().values(slot=1, site=site))
elif bound != site:
raise ValueError("database is bound to another site")
def migrate_plugins(db, catalog, registry):
catalog.create(db, checkfirst=True)
revisions.create(db, checkfirst=True)
known = set(db.scalars(select(catalog.c.name)))
for plugin in registry.plugins.values():
applied = db.scalars(select(revisions.c.version).where(revisions.c.plugin == plugin.name)).all()
# Pre-versioned catalog rows correspond to revision 1. New installs use current models.
current = max(applied) if applied else (1 if plugin.name in known else plugin.version)
if current > plugin.version:
raise ValueError(f"plugin downgrade: {plugin.name} {current} -> {plugin.version}")
if not applied:
db.execute(revisions.insert().values(plugin=plugin.name, version=current))
for revision in range(current + 1, plugin.version + 1):
migrate = plugin.migrations.get(revision)
if not callable(migrate):
raise ValueError(f"{plugin.name} missing migration to {revision}")
migrate(db)
db.execute(revisions.insert().values(plugin=plugin.name, version=revision))
def materialize(engine, registry, *, site=None):
metadata = MetaData()
for table in registry.metadata.tables.values():
table.to_metadata(metadata)
catalog = Table("mica_plugins", metadata, Column("name", String(63), primary_key=True),
Column("description", JSON, nullable=False))
revisions.to_metadata(metadata)
if site is not None:
site_binding.to_metadata(metadata)
receipts.to_metadata(metadata)
def include_name(name, kind, parents):
return kind != "table" or name in metadata.tables
with startup_transaction(engine) as db:
bind_site(db, site)
migrate_plugins(db, catalog, registry)
context = MigrationContext.configure(db, opts={"include_name": include_name})
inspector = inspect(db)
for table in metadata.tables.values():
@@ -98,6 +146,7 @@ def materialize(engine, registry):
existing = set(db.scalars(select(catalog.c.name)))
for plugin in registry.plugins.values():
description = {
"version": plugin.version,
"requires": list(plugin.requires),
"snippets": {s.name: {"operations": sorted(s.operations),
"tables": [t.name for t in s.tables]} for s in plugin.snippets},
+181
View File
@@ -0,0 +1,181 @@
"""Single graph endpoint serving independently provisioned site databases."""
from hashlib import sha256
from hmac import compare_digest
from http import HTTPStatus
import json
import logging
import re
from sqlalchemy import select
from sqlalchemy.exc import DataError, IntegrityError
from .core import Runtime
from .database import receipts
from .graph import node_for, read, schema
from .plugins import check_name
from .protocol import Principal, ProtocolError, validate_arguments
def encode(obj):
return json.dumps(obj, allow_nan=False, ensure_ascii=True, sort_keys=True,
separators=(",", ":")).encode()
def callers(site, entries):
result = {}
for entry in entries:
subject, digest, grants = entry["subject"], entry["sha256"], entry["grants"]
check_name(subject)
if not re.fullmatch("[0-9a-f]{64}", digest) or digest in result:
raise ValueError("invalid or duplicate caller digest")
if not isinstance(grants, list) or any(not isinstance(g, str) or not g for g in grants):
raise ValueError("invalid caller grants")
result[digest] = Principal(site, subject, frozenset(grants))
return result
class Replay(Exception):
pass
def mutate(runtime, principal, body, key):
steps = body["mutate"]
if not isinstance(steps, list) or not 1 <= len(steps) <= 32:
raise ProtocolError(400, "invalid_batch")
if key is not None and not re.fullmatch(r"[!-~]{1,128}", key):
raise ProtocolError(400, "invalid_idempotency_key")
for step in steps:
if not isinstance(step, dict) or step.keys() != {"action", "args"} or not isinstance(step["action"], str):
raise ProtocolError(400, "invalid_action")
action = runtime.registry.actions.get(step["action"])
if action is None:
raise ProtocolError(404, "unknown_action")
principal.require(action.grant)
validate_arguments(action, step["args"])
if key is not None:
digest = sha256(encode(body)).hexdigest()
key_hash = sha256(key.encode()).hexdigest()
match = (receipts.c.subject == principal.subject) & (receipts.c.key_hash == key_hash)
try:
with runtime.transaction(principal) as call:
if key is not None:
try:
call.db.execute(receipts.insert().values(subject=principal.subject,
key_hash=key_hash, digest=digest))
except IntegrityError as exc:
raise Replay from exc
result = [call.call(step["action"], **step["args"]) for step in steps]
# Check that the result can be returned before committing any writes.
encode(result)
if key is not None:
call.db.execute(receipts.update().where(match).values(result=result))
return result
except Replay:
with runtime.transaction(principal) as call:
row = call.db.execute(select(receipts).where(match)).mappings().one()
if row["digest"] != digest:
raise ProtocolError(409, "idempotency_conflict")
return row["result"]
class GraphApp:
def __init__(self, sites, plugins=()):
self.sites = {}
self.origins = {}
names = set()
plugins = tuple(plugins)
try:
for site in sites:
name, key = site["name"], site["key"]
check_name(name)
if name in names or not re.fullmatch(r"[!-~]{1,128}", key) or key in self.sites:
raise ValueError("invalid or duplicate site")
names.add(name)
origins = site.get("origins", [])
if not isinstance(origins, list) or any(
not isinstance(origin, str) or not re.fullmatch(r"https?://[a-zA-Z0-9.:-]+", origin)
for origin in origins
):
raise ValueError("configure explicit HTTP(S) origins")
self.origins[key] = frozenset(origins)
identities = callers(name, site["callers"])
runtime = Runtime(site["database"], plugins, enabled=site.get("plugins"), site=name)
self.sites[key] = (runtime, identities)
if not names:
raise ValueError("configure at least one site")
except BaseException:
self.close()
raise
def close(self):
for runtime, _ in self.sites.values():
runtime.close()
def dispatch(self, env):
if env["PATH_INFO"] != "/v1/graph":
raise ProtocolError(404, "unknown_endpoint")
if env["REQUEST_METHOD"] != "POST":
raise ProtocolError(405, "post_required")
site = self.sites.get(env.get("HTTP_X_MICA_SITE_KEY"))
scheme, _, token = env.get("HTTP_AUTHORIZATION", "").partition(" ")
if not site or scheme.lower() != "bearer" or not token:
raise ProtocolError(401, "invalid_credentials")
origin = env.get("HTTP_ORIGIN")
if origin and origin not in self.origins[env["HTTP_X_MICA_SITE_KEY"]]:
raise ProtocolError(403, "origin_denied")
runtime, identities = site
digest = sha256(token.encode()).hexdigest()
principal = next((who for saved, who in identities.items() if compare_digest(saved, digest)), None)
if principal is None:
raise ProtocolError(401, "invalid_credentials")
if env.get("CONTENT_TYPE", "").split(";")[0].lower().strip() != "application/json":
raise ProtocolError(415, "json_required")
length = int(env.get("CONTENT_LENGTH") or 0)
if not 0 < length <= 1024 * 1024:
raise ProtocolError(413 if length > 0 else 400, "invalid_body_size")
body = json.loads(env["wsgi.input"].read(length).decode("utf-8"))
if not isinstance(body, dict) or len(body) != 1:
raise ProtocolError(400, "invalid_request")
if "mutate" in body:
return mutate(runtime, principal, body, env.get("HTTP_IDEMPOTENCY_KEY"))
with runtime.transaction(principal) as call:
if body == {"schema": True} and body["schema"] is True:
return schema(call)
spec = body.get("query")
if not isinstance(spec, dict) or "node" not in spec:
raise ProtocolError(400, "invalid_query")
return read(call, node_for(call, spec.pop("node")), spec)
def __call__(self, env, start_response):
headers = [("Content-Type", "application/json"), ("Cache-Control", "no-store")]
origin = env.get("HTTP_ORIGIN")
headers.append(("Vary", "Origin"))
try:
if env["REQUEST_METHOD"] == "OPTIONS" and env["PATH_INFO"] == "/v1/graph":
if not origin or not any(origin in origins for origins in self.origins.values()):
raise ProtocolError(403, "origin_denied")
headers.extend([("Access-Control-Allow-Origin", origin),
("Access-Control-Allow-Methods", "POST"),
("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Mica-Site-Key, Idempotency-Key")])
start_response("204 No Content", headers)
return [b""]
if origin and origin in self.origins.get(env.get("HTTP_X_MICA_SITE_KEY"), ()):
headers.append(("Access-Control-Allow-Origin", origin))
result = encode({"data": self.dispatch(env)})
status = 200
except ProtocolError as exc:
result, status = encode({"error": exc.code}), exc.status
if status == 401:
headers.append(("WWW-Authenticate", "Bearer"))
if status == 405:
headers.append(("Allow", "POST"))
except IntegrityError:
result, status = encode({"error": "constraint_conflict"}), 409
except (ValueError, DataError, RecursionError):
result, status = encode({"error": "invalid_request"}), 400
except Exception as exc:
logging.getLogger(__name__).error("Graph request failed (%s)", type(exc).__name__)
result, status = encode({"error": "internal_error"}), 500
start_response(f"{status} {HTTPStatus(status).phrase}", [*headers, ("Content-Length", str(len(result)))])
return [result]
+156
View File
@@ -0,0 +1,156 @@
"""Bounded relational graph reads and caller-specific v1 schema discovery."""
from datetime import date, datetime
from decimal import Decimal
from uuid import UUID
from sqlalchemy import and_, or_, select
from .protocol import FIELD_TYPES, ProtocolError, SCALARS
def invalid():
raise ProtocolError(400, "invalid_query")
def json_value(value):
if isinstance(value, (date, datetime)):
return value.isoformat()
if isinstance(value, (Decimal, UUID)):
return str(value)
return value
def schema(call):
grants = call.principal.grants
nodes = {}
for name, node in call.registry.nodes.items():
if node.grant in grants:
nodes[name] = {
"key": node.key, "fields": list(node.fields),
"types": {f: FIELD_TYPES[node.table.c[f].type.python_type] for f in node.fields},
"filters": node.filters,
"edges": {k: e.target for k, e in node.edges.items()
if call.registry.nodes[e.target].grant in grants},
}
return {"version": 1, "nodes": nodes, "actions": {
name: {k: SCALARS[t] for k, t in action.arguments.items()}
for name, action in call.registry.actions.items() if action.grant in grants
}}
def scalar(column, value):
# Convert JSON scalars before sending them to a driver. This also keeps
# numeric comparisons consistent across SQLite, MySQL and PostgreSQL.
t = column.type.python_type
if t is float and type(value) in (int, float):
return float(value)
if t in (date, datetime, UUID, Decimal) and isinstance(value, str):
try:
return t.fromisoformat(value) if t in (date, datetime) else t(value)
except (ValueError, ArithmeticError):
invalid()
if type(value) is not t or t not in (int, bool, str):
invalid()
if t is int and not -(2**63) <= value < 2**63:
invalid()
return value
def predicate(node, spec, depth=0):
if not isinstance(spec, dict) or depth > 2:
invalid()
if len(spec) == 1 and next(iter(spec)) in ("and", "or"):
key, terms = next(iter(spec.items()))
if not isinstance(terms, list) or not 1 <= len(terms) <= 8:
invalid()
combine = and_ if key == "and" else or_
return combine(*(predicate(node, term, depth + 1) for term in terms))
if spec.keys() != {"field", "op", "value"}:
invalid()
field, op, value = spec["field"], spec["op"], spec["value"]
if not isinstance(field, str) or op not in node.filters.get(field, ()):
invalid()
col = node.table.c[field]
if op == "in":
if not isinstance(value, list) or not 1 <= len(value) <= 32:
invalid()
return col.in_([scalar(col, item) for item in value])
if value is None:
if op == "eq":
return col.is_(None)
if op == "ne":
return col.is_not(None)
invalid()
value = scalar(col, value)
if op == "prefix":
if not isinstance(value, str):
invalid()
return col.startswith(value, autoescape=True)
methods = {"eq": col.__eq__, "ne": col.__ne__, "lt": col.__lt__, "lte": col.__le__,
"gt": col.__gt__, "gte": col.__ge__}
return methods[op](value)
def node_for(call, name):
if not isinstance(name, str) or name not in call.registry.nodes:
raise ProtocolError(404, "unknown_node")
node = call.registry.nodes[name]
call.principal.require(node.grant)
return node
def prepare(call, node, spec, *, nested=False):
allowed = {"fields", "where", "limit", "offset", "id"}
if not nested:
allowed.add("expand")
if not isinstance(spec, dict) or spec.keys() - allowed:
invalid()
fields = spec.get("fields", [])
if not isinstance(fields, list) or not fields or any(
not isinstance(f, str) or f not in node.fields for f in fields
):
invalid()
limit, offset = spec.get("limit", 20), spec.get("offset", 0)
if type(limit) is not int or not 1 <= limit <= 50 or type(offset) is not int or not 0 <= offset <= 2**31-1:
invalid()
expansions = spec.get("expand", {})
if not isinstance(expansions, dict) or len(expansions) > 3:
invalid()
joins = {}
needed = list(dict.fromkeys(fields))
for name, selection in expansions.items():
if name not in node.edges or name in fields:
invalid()
edge = node.edges[name]
target = node_for(call, edge.target)
joins[name] = (edge, target, prepare(call, target, selection, nested=True))
if edge.local not in needed:
needed.append(edge.local)
stmt = select(*(node.table.c[f] for f in needed))
if node.visibility is not None:
stmt = stmt.where(node.visibility(call))
if "id" in spec:
stmt = stmt.where(node.table.c[node.key] == scalar(node.table.c[node.key], spec["id"]))
if "where" in spec:
stmt = stmt.where(predicate(node, spec["where"]))
stmt = stmt.order_by(node.table.c[node.key]).limit(limit).offset(offset)
return stmt, fields, joins
def execute(call, plan, condition=None):
stmt, fields, joins = plan
if condition is not None:
stmt = stmt.where(condition)
result = []
for row in call.db.execute(stmt).mappings().all():
item = {f: json_value(row[f]) for f in fields}
for name, (edge, target, child) in joins.items():
value = row[edge.local]
item[name] = [] if value is None else execute(call, child, target.table.c[edge.remote] == value)
result.append(item)
return result
def read(call, node, spec):
return execute(call, prepare(call, node, spec))
+37 -1
View File
@@ -8,12 +8,15 @@ import re
from sqlalchemy import MetaData, Table, inspect
from sqlalchemy.orm import Mapper
from .protocol import Action, FIELD_TYPES, Node, OPERATORS, SCALARS
@dataclass(frozen=True)
class Snippet:
name: str
operations: Mapping[str, Callable] = field(default_factory=dict)
operations: Mapping[str, Callable | Action] = field(default_factory=dict)
models: tuple[Table | type, ...] = ()
node: Node | None = None
@property
def tables(self):
@@ -34,6 +37,8 @@ class Plugin:
name: str
snippets: tuple[Snippet, ...]
requires: tuple[str, ...] = ()
version: int = 1
migrations: Mapping[int, Callable] = field(default_factory=dict)
def check_name(name):
@@ -47,13 +52,23 @@ class Registry:
self.snippets = {}
self.operations = {}
self.metadata = MetaData()
self.nodes = {}
self.actions = {}
for plugin in plugins:
check_name(plugin.name)
if type(plugin.version) is not int or plugin.version < 1:
raise ValueError(f"invalid plugin version: {plugin.name}")
if plugin.name in self.plugins:
raise ValueError(f"duplicate plugin: {plugin.name}")
self.plugins[plugin.name] = plugin
for snippet in plugin.snippets:
self._register(snippet)
for name, node in self.nodes.items():
for relation, edge in node.edges.items():
check_name(relation)
target = self.nodes.get(edge.target)
if target is None or edge.local not in node.table.c or edge.remote not in target.table.c:
raise ValueError(f"invalid edge: {name}.{relation}")
for plugin in self.plugins.values():
missing = set(plugin.requires) - self.snippets.keys()
if missing:
@@ -64,8 +79,29 @@ class Registry:
if snippet.name in self.snippets:
raise ValueError(f"duplicate snippet: {snippet.name}")
self.snippets[snippet.name] = snippet
node = snippet.node
if node is not None:
if (node.table not in snippet.tables or not node.grant or node.key not in node.fields
or list(node.table.primary_key.columns.keys()) != [node.key]
or not set(node.fields) <= set(node.table.c.keys())
or not node.filters.keys() <= set(node.fields)
or any(set(ops) - OPERATORS for ops in node.filters.values())):
raise ValueError(f"invalid node declaration: {snippet.name}")
if set(node.fields) & node.edges.keys() or len(node.fields) != len(set(node.fields)):
raise ValueError(f"duplicate graph field: {snippet.name}")
for name in node.fields:
kind = node.table.c[name].type.python_type
ops = node.filters.get(name, ())
if kind not in FIELD_TYPES or (ops and kind in (dict, list)) or ("prefix" in ops and kind is not str):
raise ValueError(f"unsupported graph field type or filters: {snippet.name}.{name}")
self.nodes[snippet.name] = node
for name, handler in snippet.operations.items():
check_name(name)
if isinstance(handler, Action):
if not handler.grant or any(t not in SCALARS for t in handler.arguments.values()):
raise ValueError(f"invalid public action: {snippet.name}.{name}")
self.actions[f"{snippet.name}.{name}"] = handler
handler = handler.handler
if not callable(handler):
raise ValueError(f"invalid operation: {snippet.name}.{name}")
self.operations[f"{snippet.name}.{name}"] = handler
+66
View File
@@ -0,0 +1,66 @@
"""Public contracts for the MICA v1 graph interface."""
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from datetime import date, datetime
from decimal import Decimal
from uuid import UUID
from sqlalchemy import Table
class ProtocolError(Exception):
def __init__(self, status, code):
super().__init__(code)
self.status = status
self.code = code
@dataclass(frozen=True)
class Principal:
site: str
subject: str
grants: frozenset[str]
def require(self, grant):
if grant not in self.grants:
raise ProtocolError(403, "forbidden")
@dataclass(frozen=True)
class Edge:
target: str
local: str
remote: str
@dataclass(frozen=True)
class Node:
table: Table
key: str
fields: tuple[str, ...]
grant: str
filters: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
edges: Mapping[str, Edge] = field(default_factory=dict)
# Applied to every root and edge read; return a SQLAlchemy WHERE expression.
visibility: Callable | None = None
@dataclass(frozen=True)
class Action:
handler: Callable
grant: str
arguments: Mapping[str, type] = field(default_factory=dict)
SCALARS = {str: "string", int: "integer", float: "number", bool: "boolean"}
FIELD_TYPES = {**SCALARS, date: "date", datetime: "datetime", Decimal: "decimal", UUID: "uuid",
dict: "object", list: "array"}
OPERATORS = {"eq", "ne", "lt", "lte", "gt", "gte", "in", "prefix"}
def validate_arguments(action, args):
if not isinstance(args, dict) or args.keys() != action.arguments.keys():
raise ProtocolError(400, "invalid_arguments")
if any(type(args[key]) is not expected for key, expected in action.arguments.items()):
raise ProtocolError(400, "invalid_arguments")