Serve permissioned graph queries and atomic mutations across isolated sites
This commit is contained in:
@@ -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