Serve permissioned graph queries and atomic mutations across isolated sites
This commit is contained in:
@@ -98,3 +98,57 @@ python3 -B -m unittest discover -s tests -v
|
|||||||
```
|
```
|
||||||
|
|
||||||
数据库契约测试可使用 `MICA_TEST_POSTGRESQL` 和 `MICA_TEST_MYSQL` 指定两个专用、可丢弃的测试库。测试会创建表、写入数据并核对再次启动、跨插件事务、并发初始化和兼容性;未设置的服务端用例显示为 skipped。
|
数据库契约测试可使用 `MICA_TEST_POSTGRESQL` 和 `MICA_TEST_MYSQL` 指定两个专用、可丢弃的测试库。测试会创建表、写入数据并核对再次启动、跨插件事务、并发初始化和兼容性;未设置的服务端用例显示为 skipped。
|
||||||
|
|
||||||
|
## 多站点 Graph 协议 v1
|
||||||
|
|
||||||
|
同一个进程、监听端口和 `POST /v1/graph` 路径服务多个站点。Graph 模式通过 `MICA_SITES_FILE` 选择,启动后只提供这个协议。上面的 `/content` 仍可通过原来的单站模式运行。Graph 模式使用 `mica.plugins` 入口点加载插件;新的业务插件由站点自行安装并启用。
|
||||||
|
|
||||||
|
站点配置是一个 JSON 数组。为每个站点预建独立数据库,配置稳定的名称、公开站点 key、调用者和已启用插件。下面的空插件列表可用于启动空宿主并查询 schema。将占位摘要替换成高熵随机 Bearer 凭据的 SHA-256 小写十六进制摘要。`origins` 填写允许直接调用 API 的浏览器来源;服务间调用可省略此项。
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{"name":"news","key":"news-web","database":"postgresql:///mica_news",
|
||||||
|
"plugins":[],"origins":["https://news.example"],
|
||||||
|
"callers":[{"subject":"editor","sha256":"<64位摘要>","grants":["story.read","story.edit"]}]},
|
||||||
|
{"name":"community","key":"community-web","database":"postgresql:///mica_community",
|
||||||
|
"plugins":[],"callers":[]}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export MICA_SITES_FILE=/path/to/sites.json
|
||||||
|
python3 -m mica
|
||||||
|
```
|
||||||
|
|
||||||
|
把前端请求发往部署的 HTTPS 入口。当前实现认证站点配置中的 Bearer 凭据;凭据可按用户或后端服务签发。站点 key 只选择项目,调用方还须提供该站点登记的凭据。服务端长期凭据应由网站后端保管。每个数据库在首次图服务启动时绑定站点名,重复使用同一库配置另一个站点会导致启动失败。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -sS https://api.example/v1/graph \
|
||||||
|
-H 'Content-Type: application/json' -H 'X-Mica-Site-Key: news-web' \
|
||||||
|
-H "Authorization: Bearer $MICA_CALLER_TOKEN" -d '{"schema":true}'
|
||||||
|
```
|
||||||
|
|
||||||
|
每个请求选择 schema、query 或 mutate 中的一种。成功响应为 `{"data":...}`,错误为 `{"error":"错误码"}`。schema 返回调用者可以读取的节点、主键、字段类型、筛选运算、关系和可调用操作。以下为协议示例,需要站点插件先声明相应能力。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"query":{"node":"stories","fields":["id","title"],"limit":20,"offset":0,
|
||||||
|
"where":{"and":[{"field":"score","op":"gte","value":8},
|
||||||
|
{"field":"title","op":"prefix","value":"本周"}]},
|
||||||
|
"expand":{"comments":{"fields":["id","body"],"limit":3}}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
查询返回数组。用 `id` 定位单节点,用 `fields` 选择投影。每个节点按主键排序;分页默认 20,上限 50。允许展开一层、最多三个关系,每个父节点独立分页。筛选支持插件显式开放的 `eq/ne/lt/lte/gt/gte/in/prefix`,以及嵌套 `and/or`,最多两层组合,每组最多 8 项,`in` 最多 32 项。前缀按字面值匹配。根节点与关系目标都应用权限和插件的行级可见性条件。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"mutate":[{"action":"stories.rename","args":{"id":"42","title":"新标题"}},
|
||||||
|
{"action":"stories.publish","args":{"id":"42"}}]}
|
||||||
|
```
|
||||||
|
|
||||||
|
同站点一次 mutate 可顺序执行 1 至 32 个操作,返回顺序一致的结果数组。Core 校验调用资格和参数,在同一个数据库事务中执行全部操作。任一操作抛错或数据库约束冲突,整批回滚。指定 `Idempotency-Key` 后,站点、调用者和 key 相同的成功请求重放已提交结果;同 key 不同请求返回 409。失败批次可以重试。回执目前保存在站点库中,无自动过期策略。事务保证覆盖使用 Core 会话的数据库写入,插件须将邮件、HTTP 等外部副作用安排在成功提交之后。
|
||||||
|
|
||||||
|
### 插件声明与升级
|
||||||
|
|
||||||
|
- `Snippet.node` 可选,取值为 `mica.protocol.Node`。声明单列主键、可读字段、读权限、每字段允许的筛选符、可选的 `visibility(call)` SQL 条件。用 `Edge(target, local, remote)` 声明等值关联;`target` 指向已注册的 snippet。
|
||||||
|
- 通过 `Action(handler, grant, arguments)` 将操作显式暴露给图端点。参数类型支持必填的 str、int、float、bool,返回 JSON 可表示的数据。已有普通 Python 操作仍可供插件内部调用。`call.principal` 包含站点、主体和授权;对象级写入权限由处理函数校验,可抛出 `ProtocolError(403, "forbidden")`。插件间调用公共操作同样检查权限。
|
||||||
|
- `Plugin.version` 为从 1 开始的整型修订号。`Plugin.migrations={2: upgrade_to_2}` 声明 1 到 2 的回调,接收同一站点的 SQLAlchemy Connection。每个站点独立登记基线和逐次升级记录。新库直接创建当前模型,旧版目录按 v1 接续。升级在启动锁内执行,缺少中间步骤或尝试降级会拒绝启动。迁移应明确处理重命名、回填及其跨版本依赖。MySQL 的 DDL 隐式提交,涉及 DDL 的升级回调须可安全重试。
|
||||||
|
- 测试夹具 `tests/test_graph.py` 展示了插件声明、组合筛选、关系、调用者权限和批量更新。环境变量 `MICA_GRAPH_TEST_ONE`、`MICA_GRAPH_TEST_TWO` 可以指向两个独立的可丢弃服务端数据库;缺省用临时 SQLite 文件。
|
||||||
|
|||||||
+15
-4
@@ -1,19 +1,30 @@
|
|||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
|
import json
|
||||||
import os
|
import os
|
||||||
from wsgiref.simple_server import make_server
|
from wsgiref.simple_server import make_server
|
||||||
|
|
||||||
from .api import create_app
|
from .api import create_app
|
||||||
|
from .gateway import GraphApp
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
names = os.getenv("MICA_PLUGINS")
|
sites_file = os.getenv("MICA_SITES_FILE")
|
||||||
enabled = None if names is None else [name.strip() for name in names.split(",") if name.strip()]
|
if sites_file:
|
||||||
app = create_app(os.getenv("MICA_DATABASE", "postgresql:///mica"),
|
with open(sites_file, encoding="utf-8") as config:
|
||||||
os.getenv("MICA_WRITE_TOKEN"), enabled=enabled)
|
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:
|
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)
|
print(f"MICA listening on http://127.0.0.1:{server.server_port}", flush=True)
|
||||||
server.serve_forever()
|
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__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|||||||
+26
-6
@@ -1,9 +1,11 @@
|
|||||||
"""Load plugins, materialize their models and dispatch transactional calls."""
|
"""Load plugins, materialize their models and dispatch transactional calls."""
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from .database import connect, materialize
|
from .database import connect, materialize
|
||||||
|
from .protocol import Principal, validate_arguments
|
||||||
from .plugins import Plugin, Registry, Snippet
|
from .plugins import Plugin, Registry, Snippet
|
||||||
|
|
||||||
# Keep the original content extension imports usable by installed plugins.
|
# Keep the original content extension imports usable by installed plugins.
|
||||||
@@ -16,30 +18,48 @@ __all__ = ["Runtime", "Call", "Plugin", "Registry", "Snippet", "ContentType", "d
|
|||||||
class Call:
|
class Call:
|
||||||
registry: Registry
|
registry: Registry
|
||||||
session: Session
|
session: Session
|
||||||
|
principal: Principal | None = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def db(self):
|
def db(self):
|
||||||
self.session.flush()
|
self.session.flush()
|
||||||
return self.session.connection()
|
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]
|
handler = self.registry.operations[operation]
|
||||||
return handler(self, **parameters)
|
return handler(self, **parameters)
|
||||||
|
|
||||||
|
|
||||||
class Runtime:
|
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.registry = Registry.load(plugins, enabled)
|
||||||
self.engine = connect(database)
|
self.engine = connect(database)
|
||||||
try:
|
try:
|
||||||
materialize(self.engine, self.registry)
|
materialize(self.engine, self.registry, site=site)
|
||||||
except BaseException:
|
except BaseException:
|
||||||
self.engine.dispose()
|
self.engine.dispose()
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def call(self, operation, **parameters):
|
@contextmanager
|
||||||
with Session(self.engine, expire_on_commit=False) as session, session.begin():
|
def transaction(self, principal=None):
|
||||||
return Call(self.registry, session).call(operation, **parameters)
|
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):
|
def close(self):
|
||||||
self.engine.dispose()
|
self.engine.dispose()
|
||||||
|
|||||||
+51
-2
@@ -6,7 +6,7 @@ from os import PathLike
|
|||||||
from alembic.autogenerate import compare_metadata
|
from alembic.autogenerate import compare_metadata
|
||||||
from alembic.migration import MigrationContext
|
from alembic.migration import MigrationContext
|
||||||
from alembic.operations import Operations
|
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
|
from sqlalchemy.engine import URL, make_url
|
||||||
|
|
||||||
|
|
||||||
@@ -49,17 +49,65 @@ def startup_transaction(engine):
|
|||||||
db.execute(text("SELECT RELEASE_LOCK('mica.core.startup')"))
|
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()
|
metadata = MetaData()
|
||||||
for table in registry.metadata.tables.values():
|
for table in registry.metadata.tables.values():
|
||||||
table.to_metadata(metadata)
|
table.to_metadata(metadata)
|
||||||
catalog = Table("mica_plugins", metadata, Column("name", String(63), primary_key=True),
|
catalog = Table("mica_plugins", metadata, Column("name", String(63), primary_key=True),
|
||||||
Column("description", JSON, nullable=False))
|
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):
|
def include_name(name, kind, parents):
|
||||||
return kind != "table" or name in metadata.tables
|
return kind != "table" or name in metadata.tables
|
||||||
|
|
||||||
with startup_transaction(engine) as db:
|
with startup_transaction(engine) as db:
|
||||||
|
bind_site(db, site)
|
||||||
|
migrate_plugins(db, catalog, registry)
|
||||||
context = MigrationContext.configure(db, opts={"include_name": include_name})
|
context = MigrationContext.configure(db, opts={"include_name": include_name})
|
||||||
inspector = inspect(db)
|
inspector = inspect(db)
|
||||||
for table in metadata.tables.values():
|
for table in metadata.tables.values():
|
||||||
@@ -98,6 +146,7 @@ def materialize(engine, registry):
|
|||||||
existing = set(db.scalars(select(catalog.c.name)))
|
existing = set(db.scalars(select(catalog.c.name)))
|
||||||
for plugin in registry.plugins.values():
|
for plugin in registry.plugins.values():
|
||||||
description = {
|
description = {
|
||||||
|
"version": plugin.version,
|
||||||
"requires": list(plugin.requires),
|
"requires": list(plugin.requires),
|
||||||
"snippets": {s.name: {"operations": sorted(s.operations),
|
"snippets": {s.name: {"operations": sorted(s.operations),
|
||||||
"tables": [t.name for t in s.tables]} for s in plugin.snippets},
|
"tables": [t.name for t in s.tables]} for s in plugin.snippets},
|
||||||
|
|||||||
+181
@@ -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
@@ -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
@@ -8,12 +8,15 @@ import re
|
|||||||
from sqlalchemy import MetaData, Table, inspect
|
from sqlalchemy import MetaData, Table, inspect
|
||||||
from sqlalchemy.orm import Mapper
|
from sqlalchemy.orm import Mapper
|
||||||
|
|
||||||
|
from .protocol import Action, FIELD_TYPES, Node, OPERATORS, SCALARS
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class Snippet:
|
class Snippet:
|
||||||
name: str
|
name: str
|
||||||
operations: Mapping[str, Callable] = field(default_factory=dict)
|
operations: Mapping[str, Callable | Action] = field(default_factory=dict)
|
||||||
models: tuple[Table | type, ...] = ()
|
models: tuple[Table | type, ...] = ()
|
||||||
|
node: Node | None = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def tables(self):
|
def tables(self):
|
||||||
@@ -34,6 +37,8 @@ class Plugin:
|
|||||||
name: str
|
name: str
|
||||||
snippets: tuple[Snippet, ...]
|
snippets: tuple[Snippet, ...]
|
||||||
requires: tuple[str, ...] = ()
|
requires: tuple[str, ...] = ()
|
||||||
|
version: int = 1
|
||||||
|
migrations: Mapping[int, Callable] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
def check_name(name):
|
def check_name(name):
|
||||||
@@ -47,13 +52,23 @@ class Registry:
|
|||||||
self.snippets = {}
|
self.snippets = {}
|
||||||
self.operations = {}
|
self.operations = {}
|
||||||
self.metadata = MetaData()
|
self.metadata = MetaData()
|
||||||
|
self.nodes = {}
|
||||||
|
self.actions = {}
|
||||||
for plugin in plugins:
|
for plugin in plugins:
|
||||||
check_name(plugin.name)
|
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:
|
if plugin.name in self.plugins:
|
||||||
raise ValueError(f"duplicate plugin: {plugin.name}")
|
raise ValueError(f"duplicate plugin: {plugin.name}")
|
||||||
self.plugins[plugin.name] = plugin
|
self.plugins[plugin.name] = plugin
|
||||||
for snippet in plugin.snippets:
|
for snippet in plugin.snippets:
|
||||||
self._register(snippet)
|
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():
|
for plugin in self.plugins.values():
|
||||||
missing = set(plugin.requires) - self.snippets.keys()
|
missing = set(plugin.requires) - self.snippets.keys()
|
||||||
if missing:
|
if missing:
|
||||||
@@ -64,8 +79,29 @@ class Registry:
|
|||||||
if snippet.name in self.snippets:
|
if snippet.name in self.snippets:
|
||||||
raise ValueError(f"duplicate snippet: {snippet.name}")
|
raise ValueError(f"duplicate snippet: {snippet.name}")
|
||||||
self.snippets[snippet.name] = snippet
|
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():
|
for name, handler in snippet.operations.items():
|
||||||
check_name(name)
|
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):
|
if not callable(handler):
|
||||||
raise ValueError(f"invalid operation: {snippet.name}.{name}")
|
raise ValueError(f"invalid operation: {snippet.name}.{name}")
|
||||||
self.operations[f"{snippet.name}.{name}"] = handler
|
self.operations[f"{snippet.name}.{name}"] = handler
|
||||||
|
|||||||
@@ -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")
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
"""Graph protocol contract. The fixture plugin is installed only inside these tests."""
|
||||||
|
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from dataclasses import replace
|
||||||
|
from hashlib import sha256
|
||||||
|
from io import BytesIO
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest import TestCase
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from sqlalchemy import Column, Integer, MetaData, String, Table, select
|
||||||
|
|
||||||
|
from mica.core import Plugin, Runtime, Snippet
|
||||||
|
from mica.gateway import GraphApp
|
||||||
|
from mica.protocol import Action, Edge, Node, ProtocolError
|
||||||
|
|
||||||
|
|
||||||
|
metadata = MetaData()
|
||||||
|
notes = Table("fixture_notes", metadata, Column("id", String(64), primary_key=True),
|
||||||
|
Column("parent", String(64)), Column("subject", String(63)), Column("score", Integer))
|
||||||
|
audit = Table("fixture_audit", metadata, Column("id", String(64), primary_key=True))
|
||||||
|
|
||||||
|
|
||||||
|
def write(call, id, parent, score):
|
||||||
|
call.db.execute(notes.insert().values(id=id, parent=parent, score=score, subject=call.principal.subject))
|
||||||
|
return id
|
||||||
|
|
||||||
|
|
||||||
|
def fail(call):
|
||||||
|
raise ProtocolError(409, "fixture_failure")
|
||||||
|
|
||||||
|
|
||||||
|
def nested(call):
|
||||||
|
return call.call("notes.fail")
|
||||||
|
|
||||||
|
|
||||||
|
node = Node(notes, "id", ("id", "score"), "view", {"score": ("gte", "in"), "id": ("prefix",)},
|
||||||
|
{"children": Edge("notes", "id", "parent")},
|
||||||
|
visibility=lambda call: notes.c.subject == call.principal.subject)
|
||||||
|
plugin = Plugin("fixture", (Snippet("notes", {
|
||||||
|
"write": Action(write, "write", {"id": str, "parent": str, "score": int}),
|
||||||
|
"fail": Action(fail, "admin"), "nested": Action(nested, "write"), "internal": fail,
|
||||||
|
}, (notes,), node),))
|
||||||
|
|
||||||
|
|
||||||
|
def credential(subject, token, grants):
|
||||||
|
return {"subject": subject, "sha256": sha256(token.encode()).hexdigest(), "grants": grants}
|
||||||
|
|
||||||
|
|
||||||
|
def mutation(id, parent="", score=3):
|
||||||
|
return {"action": "notes.write", "args": {"id": id, "parent": parent, "score": score}}
|
||||||
|
|
||||||
|
|
||||||
|
class GraphContract(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
temp = TemporaryDirectory()
|
||||||
|
self.addCleanup(temp.cleanup)
|
||||||
|
self.sites = []
|
||||||
|
for name in ("one", "two"):
|
||||||
|
database = os.environ.get("MICA_GRAPH_TEST_" + name.upper(), str(Path(temp.name) / name))
|
||||||
|
self.sites.append({"name": name, "key": name, "database": database, "plugins": ["fixture"], "origins": [f"https://{name}.example"],
|
||||||
|
"callers": [credential("alice", name+"-alice", ["view", "write", "admin"]),
|
||||||
|
credential("bob", name+"-bob", ["view", "write"]),
|
||||||
|
credential("visitor", name+"-visitor", [])]})
|
||||||
|
self.app = GraphApp(self.sites, [plugin])
|
||||||
|
self.addCleanup(self.app.close)
|
||||||
|
self.id = uuid4().hex
|
||||||
|
|
||||||
|
def request(self, body, *, site="one", token=None, key=None, path="/v1/graph", origin=None, method="POST"):
|
||||||
|
raw = json.dumps(body).encode()
|
||||||
|
status = []
|
||||||
|
env = {"REQUEST_METHOD": method, "PATH_INFO": path, "CONTENT_TYPE": "application/json",
|
||||||
|
"CONTENT_LENGTH": str(len(raw)), "wsgi.input": BytesIO(raw), "HTTP_X_MICA_SITE_KEY": site,
|
||||||
|
"HTTP_AUTHORIZATION": "Bearer " + (token or site+"-alice")}
|
||||||
|
if origin:
|
||||||
|
env["HTTP_ORIGIN"] = origin
|
||||||
|
if key is not None:
|
||||||
|
env["HTTP_IDEMPOTENCY_KEY"] = key
|
||||||
|
response = self.app(env, lambda line, headers: status.append(int(line[:3])))
|
||||||
|
return status[0], json.loads(b"".join(response) or b"null")
|
||||||
|
|
||||||
|
def test_projection_filter_edge_and_isolation(self):
|
||||||
|
child = self.id + "_child"
|
||||||
|
self.assertEqual(self.request({"mutate": [mutation(self.id), mutation(child, self.id, 5)]})[0], 200)
|
||||||
|
self.assertEqual(self.request({"mutate": [mutation(self.id+"_hidden", self.id)]}, token="one-bob")[0], 200)
|
||||||
|
spec = {"node": "notes", "id": self.id, "fields": ["id"],
|
||||||
|
"expand": {"children": {"fields": ["score"], "where": {"and": [
|
||||||
|
{"field": "score", "op": "gte", "value": 3},
|
||||||
|
{"or": [{"field": "score", "op": "in", "value": [5]}]}]}}}}
|
||||||
|
self.assertEqual(self.request({"query": spec}), (200, {"data": [{"id": self.id, "children": [{"score": 5}]}]}))
|
||||||
|
self.assertEqual(self.request({"query": spec}, site="two"), (200, {"data": []}))
|
||||||
|
self.assertEqual(self.request({"query": spec}, token="one-bob"), (200, {"data": []}))
|
||||||
|
self.assertEqual(self.request({"query": spec}, site="two", token="one-alice")[0], 401)
|
||||||
|
self.assertEqual(self.request({"query": spec}, token="one-visitor")[0], 403)
|
||||||
|
self.assertEqual(self.request({}, path="/content")[0], 404)
|
||||||
|
bad = {**spec, "id": "absent", "expand": {"children": {"fields": ["subject"]}}}
|
||||||
|
self.assertEqual(self.request({"query": bad})[0], 400)
|
||||||
|
self.assertEqual(self.request({"query": {**spec, "where": {"field": "subject", "op": "eq", "value": "alice"}}})[0], 400)
|
||||||
|
|
||||||
|
def test_browser_origins(self):
|
||||||
|
self.assertEqual(self.request({}, origin="https://one.example", method="OPTIONS")[0], 204)
|
||||||
|
self.assertEqual(self.request({"schema": True}, origin="https://one.example")[0], 200)
|
||||||
|
self.assertEqual(self.request({"schema": True}, site="two", origin="https://one.example")[0], 403)
|
||||||
|
|
||||||
|
def test_contract_and_nested_authorization(self):
|
||||||
|
status, result = self.request({"schema": True}, token="one-bob")
|
||||||
|
self.assertEqual(status, 200)
|
||||||
|
self.assertEqual(set(result["data"]["actions"]), {"notes.write", "notes.nested"})
|
||||||
|
self.assertEqual(result["data"]["nodes"]["notes"]["edges"], {"children": "notes"})
|
||||||
|
nested_action = {"action": "notes.nested", "args": {}}
|
||||||
|
self.assertEqual(self.request({"mutate": [mutation(self.id), nested_action]}, token="one-bob")[0], 403)
|
||||||
|
self.assertEqual(self.request({"query": {"node": "notes", "id": self.id, "fields": ["id"]}},
|
||||||
|
token="one-bob")[1]["data"], [])
|
||||||
|
self.assertEqual(self.request({"mutate": [{"action": "notes.internal", "args": {}}]})[0], 404)
|
||||||
|
|
||||||
|
def test_atomic_failure_then_retry_and_concurrent_replay(self):
|
||||||
|
body = {"mutate": [mutation(self.id)]}
|
||||||
|
bad = {"mutate": [mutation(self.id), {"action": "notes.fail", "args": {}}]}
|
||||||
|
self.assertEqual(self.request(bad, key=self.id)[0], 409)
|
||||||
|
with ThreadPoolExecutor(2) as workers:
|
||||||
|
results = list(workers.map(lambda _: self.request(body, key=self.id), range(2)))
|
||||||
|
self.assertEqual(results, [(200, {"data": [self.id]})]*2)
|
||||||
|
self.assertEqual(self.request({"mutate": [mutation("changed")]}, key=self.id)[0], 409)
|
||||||
|
self.assertEqual(self.request(body, key=self.id, site="two")[0], 200)
|
||||||
|
|
||||||
|
def test_database_binding(self):
|
||||||
|
config = {**self.sites[0], "name": "wrong"}
|
||||||
|
with self.assertRaisesRegex(ValueError, "bound to another site"):
|
||||||
|
GraphApp([config], [plugin])
|
||||||
|
with self.assertRaisesRegex(ValueError, "bound to another site"):
|
||||||
|
Runtime(self.sites[0]["database"], [plugin])
|
||||||
|
|
||||||
|
def test_migration_history_and_downgrade(self):
|
||||||
|
name = "upgrade_" + self.id
|
||||||
|
v1 = Plugin(name, (Snippet(name, {}, (audit,)),))
|
||||||
|
db = self.sites[0]["database"]
|
||||||
|
def start(p):
|
||||||
|
return Runtime(db, [p], enabled=[name], site="one")
|
||||||
|
start(v1).close()
|
||||||
|
def migrate(conn):
|
||||||
|
conn.execute(audit.insert().values(id=self.id))
|
||||||
|
v2 = replace(v1, version=2, migrations={2: migrate})
|
||||||
|
start(v2).close()
|
||||||
|
rt = start(v2)
|
||||||
|
with rt.engine.connect() as conn:
|
||||||
|
self.assertEqual(conn.scalar(select(audit.c.id).where(audit.c.id == self.id)), self.id)
|
||||||
|
rt.close()
|
||||||
|
with self.assertRaisesRegex(ValueError, "downgrade"):
|
||||||
|
start(v1)
|
||||||
|
with self.assertRaisesRegex(ValueError, "missing migration"):
|
||||||
|
start(replace(v2, version=3))
|
||||||
Reference in New Issue
Block a user