Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_dron_schema.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_dron_schema.py · 115.8 KB · 1798 lines
1"""DRON's JSON Schema and the loaders that read the same files must not drift.
2
3DRON (Data Rules Object Notation) is the name for the declarations a package
4makes: collection schemas, the manifest and permission rules. dron/*.schema.json
5is its machine-readable definition (docs/dron.md). Two failures are possible:
6
7 - a shipped file the schema refuses (the schema is wrong, or the file is), and
8 - the schema and the loaders disagreeing about a declaration, so that an
9 editor says "fine" to something the server refuses, or the reverse.
10
11Both are caught here. Part 1 is a small validator for the subset of JSON
12Schema 2020-12 the DRON files use, written with the standard library only (no
13jsonschema package is installed or needed); it refuses a keyword it does not
14implement, so a schema can never lean on something this file silently ignores.
15Part 2 validates every shipped file. Part 3 feeds the same declarations to the
16loader and to the schema and compares the answers. Every disagreement is
17LISTED, with the reason one side is right, so a new disagreement fails the
18test and a fixed one has to be taken off the list.
19"""
20
21from __future__ import annotations
22
23import copy
24import json
25import re
26import urllib.parse
27from pathlib import Path
28
29import pytest
30
31import object_exchange
32import object_packages
33import object_permission_store
34import object_permissions
35import object_schemas
36
37ROOT = Path(__file__).resolve().parents[1]
38DRON_DIR = ROOT / "dron"
39PACKAGES = ROOT / "packages"
40
41COLLECTION_SCHEMA = "dron-collection.schema.json"
42PACKAGE_SCHEMA = "dron-package.schema.json"
43PERMISSIONS_SCHEMA = "dron-permissions.schema.json"
44VIEW_SCHEMA = "dron-view.schema.json"
45POLICY_SCHEMA = "dron-policy.schema.json"
46DOCUMENT_SCHEMA = "dron-document.schema.json"
47SCHEMA_FILES = (
48 "dron-common.schema.json",
49 COLLECTION_SCHEMA,
50 PACKAGE_SCHEMA,
51 PERMISSIONS_SCHEMA,
52 VIEW_SCHEMA,
53 POLICY_SCHEMA,
54 DOCUMENT_SCHEMA,
55)
56
57
58# --------------------------------------------------------------------------
59# Part 1: a small JSON Schema (2020-12 subset) validator
60# --------------------------------------------------------------------------
61
62ANNOTATIONS = frozenset({"$schema", "$comment", "title", "description", "examples", "default"})
63# keyword -> how its value holds subschemas
64SCHEMA_VALUED = frozenset({"additionalProperties", "propertyNames", "items", "not", "if", "then", "else"})
65SCHEMA_MAP = frozenset({"properties", "$defs"})
66SCHEMA_LIST = frozenset({"allOf", "anyOf", "oneOf"})
67PLAIN = frozenset({
68 "$ref", "type", "enum", "const", "required", "minProperties", "minItems",
69 "uniqueItems", "minLength", "maxLength", "pattern", "minimum", "maximum", "format",
70})
71SUPPORTED = ANNOTATIONS | SCHEMA_VALUED | SCHEMA_MAP | SCHEMA_LIST | PLAIN
72
73
74def _search(pattern: str, instance: str) -> bool:
75 """JSON Schema's `pattern`: a search, read as ECMAScript reads it. Every
76 pattern in the files is in the DRON dialect (a test below holds that), so
77 it is given the dialect's meaning: `$` is the end of the text, not also
78 the place before a final newline as in Python's `re`."""
79 source = object_schemas.portable_pattern_source(pattern)
80 return re.compile(source, re.ASCII).search(instance) is not None
81
82
83class SchemaError(Exception):
84 """The schema itself uses something this validator does not implement."""
85
86
87class Validator:
88 """Validate JSON data against the DRON schema files in one directory."""
89
90 def __init__(self, directory: Path = DRON_DIR) -> None:
91 self.directory = directory
92 self._documents: dict[str, dict] = {}
93
94 def document(self, name: str) -> dict:
95 if name not in self._documents:
96 self._documents[name] = json.loads((self.directory / name).read_text(encoding="utf-8"))
97 return self._documents[name]
98
99 def errors(self, instance, schema_file: str) -> list[str]:
100 root = self.document(schema_file)
101 return self._errors(instance, root, (schema_file, root), "$")
102
103 # -- references --------------------------------------------------------
104
105 def _resolve(self, ref: str, context: tuple[str, dict]):
106 file_part, _, pointer = ref.partition("#")
107 name, root = context
108 if file_part:
109 name = urllib.parse.unquote(file_part)
110 root = self.document(name)
111 node = root
112 for token in [part for part in pointer.split("/") if part]:
113 token = urllib.parse.unquote(token).replace("~1", "/").replace("~0", "~")
114 if not isinstance(node, dict) or token not in node:
115 raise SchemaError(f"unresolvable $ref {ref!r} in {context[0]}")
116 node = node[token]
117 return node, (name, root)
118
119 # -- evaluation --------------------------------------------------------
120
121 def _errors(self, instance, schema, context, path: str) -> list[str]:
122 if schema is True:
123 return []
124 if schema is False:
125 return [f"{path}: nothing is allowed here"]
126 if not isinstance(schema, dict):
127 raise SchemaError(f"a schema must be an object or boolean, got {schema!r}")
128 unknown = set(schema) - SUPPORTED
129 if unknown:
130 raise SchemaError(f"unsupported keyword(s) {sorted(unknown)} in {context[0]}")
131
132 errors: list[str] = []
133
134 if "$ref" in schema:
135 target, target_context = self._resolve(schema["$ref"], context)
136 errors += self._errors(instance, target, target_context, path)
137
138 if "type" in schema:
139 wanted = schema["type"] if isinstance(schema["type"], list) else [schema["type"]]
140 if not any(_is_type(instance, name) for name in wanted):
141 errors.append(f"{path}: expected {' or '.join(wanted)}, got {_type_name(instance)}")
142 return errors # the keywords below assume the type
143
144 if "enum" in schema and not any(_equal(instance, option) for option in schema["enum"]):
145 errors.append(f"{path}: {instance!r} is not one of {schema['enum']}")
146 if "const" in schema and not _equal(instance, schema["const"]):
147 errors.append(f"{path}: must be {schema['const']!r}")
148
149 if isinstance(instance, str):
150 if "minLength" in schema and len(instance) < schema["minLength"]:
151 errors.append(f"{path}: shorter than {schema['minLength']} characters")
152 if "maxLength" in schema and len(instance) > schema["maxLength"]:
153 errors.append(f"{path}: longer than {schema['maxLength']} characters")
154 if "pattern" in schema and not _search(schema["pattern"], instance):
155 errors.append(f"{path}: {instance!r} does not match {schema['pattern']}")
156 if schema.get("format") == "regex":
157 # The schema names the dialect in words: DRON's (docs/dron.md).
158 problem = object_schemas.pattern_problem(instance)
159 if problem:
160 errors.append(f"{path}: not a DRON regular expression: {problem}")
161 elif "format" in schema:
162 raise SchemaError(f"unsupported format {schema['format']!r}")
163
164 if _is_number(instance):
165 if "minimum" in schema and instance < schema["minimum"]:
166 errors.append(f"{path}: below the minimum {schema['minimum']}")
167 if "maximum" in schema and instance > schema["maximum"]:
168 errors.append(f"{path}: above the maximum {schema['maximum']}")
169
170 if isinstance(instance, list):
171 if "minItems" in schema and len(instance) < schema["minItems"]:
172 errors.append(f"{path}: fewer than {schema['minItems']} items")
173 if schema.get("uniqueItems"):
174 for index, item in enumerate(instance):
175 if any(_equal(item, earlier) for earlier in instance[:index]):
176 errors.append(f"{path}: item {index} repeats an earlier item")
177 break
178 if "items" in schema:
179 for index, item in enumerate(instance):
180 errors += self._errors(item, schema["items"], context, f"{path}[{index}]")
181
182 if isinstance(instance, dict):
183 if "minProperties" in schema and len(instance) < schema["minProperties"]:
184 errors.append(f"{path}: fewer than {schema['minProperties']} properties")
185 for name in schema.get("required", []):
186 if name not in instance:
187 errors.append(f"{path}: missing required property {name!r}")
188 properties = schema.get("properties", {})
189 for name, value in instance.items():
190 if "propertyNames" in schema:
191 errors += self._errors(name, schema["propertyNames"], context, f"{path}.<{name}>")
192 if name in properties:
193 errors += self._errors(value, properties[name], context, f"{path}.{name}")
194 elif "additionalProperties" in schema:
195 extra = schema["additionalProperties"]
196 if extra is False:
197 errors.append(f"{path}: unknown property {name!r}")
198 else:
199 errors += self._errors(value, extra, context, f"{path}.{name}")
200
201 for sub in schema.get("allOf", []):
202 errors += self._errors(instance, sub, context, path)
203 if "anyOf" in schema:
204 if not any(not self._errors(instance, sub, context, path) for sub in schema["anyOf"]):
205 errors.append(f"{path}: matches none of the allowed shapes")
206 if "oneOf" in schema:
207 matching = sum(1 for sub in schema["oneOf"] if not self._errors(instance, sub, context, path))
208 if matching != 1:
209 errors.append(f"{path}: must match exactly one allowed shape, matches {matching}")
210 if "not" in schema and not self._errors(instance, schema["not"], context, path):
211 errors.append(f"{path}: this value is not allowed")
212 if "if" in schema:
213 if not self._errors(instance, schema["if"], context, path):
214 if "then" in schema:
215 errors += self._errors(instance, schema["then"], context, path)
216 elif "else" in schema:
217 errors += self._errors(instance, schema["else"], context, path)
218 return errors
219
220
221def _is_number(value) -> bool:
222 return isinstance(value, (int, float)) and not isinstance(value, bool)
223
224
225def _is_type(value, name: str) -> bool:
226 if name == "string":
227 return isinstance(value, str)
228 if name == "number":
229 return _is_number(value)
230 if name == "integer":
231 return isinstance(value, int) and not isinstance(value, bool) or (
232 isinstance(value, float) and value.is_integer())
233 if name == "boolean":
234 return isinstance(value, bool)
235 if name == "null":
236 return value is None
237 if name == "array":
238 return isinstance(value, list)
239 if name == "object":
240 return isinstance(value, dict)
241 raise SchemaError(f"unknown type {name!r}")
242
243
244def _type_name(value) -> str:
245 for name in ("null", "boolean", "string", "integer", "number", "array", "object"):
246 if _is_type(value, name):
247 return name
248 return type(value).__name__
249
250
251def _equal(left, right) -> bool:
252 """JSON equality: true is not 1, 1 is 1.0."""
253 if isinstance(left, bool) or isinstance(right, bool):
254 return isinstance(left, bool) and isinstance(right, bool) and left == right
255 if isinstance(left, list) and isinstance(right, list):
256 return len(left) == len(right) and all(_equal(a, b) for a, b in zip(left, right))
257 if isinstance(left, dict) and isinstance(right, dict):
258 return left.keys() == right.keys() and all(_equal(left[k], right[k]) for k in left)
259 return left == right
260
261
262VALIDATOR = Validator()
263
264
265def schema_errors(instance, schema_file: str) -> list[str]:
266 return VALIDATOR.errors(instance, schema_file)
267
268
269# --- the validator must itself be trustworthy -----------------------------
270
271def _scratch(schema: dict, instance) -> list[str]:
272 validator = Validator()
273 validator._documents["scratch.json"] = schema
274 return validator.errors(instance, "scratch.json")
275
276
277@pytest.mark.parametrize("schema,instance,valid", [
278 ({"type": "string"}, "a", True),
279 ({"type": "string"}, 1, False),
280 ({"type": "integer"}, True, False),
281 ({"type": "integer"}, 3.0, True),
282 ({"type": "number"}, True, False),
283 ({"type": ["string", "null"]}, None, True),
284 ({"enum": [1, "a"]}, True, False),
285 ({"enum": [1, "a"]}, "a", True),
286 ({"const": True}, 1, False),
287 ({"required": ["a"]}, {}, False),
288 ({"additionalProperties": False, "properties": {"a": {}}}, {"a": 1, "b": 2}, False),
289 ({"additionalProperties": {"type": "integer"}}, {"a": "x"}, False),
290 ({"propertyNames": {"pattern": "^[a-z]+$"}}, {"A": 1}, False),
291 ({"items": {"type": "integer"}}, [1, "x"], False),
292 ({"uniqueItems": True}, [1, True], True),
293 ({"uniqueItems": True}, [1, 1.0], False),
294 ({"minItems": 1}, [], False),
295 ({"minProperties": 1}, {}, False),
296 ({"pattern": "^a"}, "ba", False),
297 ({"pattern": "a"}, "ba", True),
298 ({"pattern": "^a$"}, "a\n", False),
299 ({"pattern": "^[0-9]+$"}, "١٢", False),
300 ({"minLength": 2}, "a", False),
301 ({"minimum": 1}, 0, False),
302 ({"anyOf": [{"type": "string"}, {"type": "integer"}]}, [], False),
303 ({"oneOf": [{"type": "integer"}, {"type": "number"}]}, 1, False),
304 ({"not": {"const": "x"}}, "x", False),
305 ({"if": {"required": ["a"]}, "then": {"required": ["b"]}}, {"a": 1}, False),
306 ({"if": {"required": ["a"]}, "then": {"required": ["b"]}}, {}, True),
307 ({"if": {"required": ["a"]}, "else": {"required": ["b"]}}, {}, False),
308 ({"allOf": [{"type": "object"}, {"required": ["a"]}]}, {}, False),
309 ({"$ref": "#/$defs/n", "$defs": {"n": {"type": "integer"}}}, "x", False),
310 ({"format": "regex"}, "(", False),
311])
312def test_the_mini_validator_decides_like_json_schema(schema, instance, valid):
313 assert (not _scratch(schema, instance)) is valid
314
315
316def test_the_mini_validator_refuses_a_keyword_it_does_not_implement():
317 with pytest.raises(SchemaError):
318 _scratch({"patternProperties": {"^a": {}}}, {"a": 1})
319
320
321CONSTRAINT_ONLY = frozenset({"if", "then", "else", "not", "allOf"})
322
323
324def _walk_schemas(node, trail="#", *, definitions_only=False):
325 """Yield (location, schema) for every subschema reachable in a schema file.
326 definitions_only skips the branches that only constrain (if/then/else, not,
327 allOf): the keys inside them are not keys an author writes."""
328 if not isinstance(node, dict):
329 return
330 yield trail, node
331 for keyword in SCHEMA_VALUED:
332 if definitions_only and keyword in CONSTRAINT_ONLY:
333 continue
334 if isinstance(node.get(keyword), dict):
335 yield from _walk_schemas(node[keyword], f"{trail}/{keyword}", definitions_only=definitions_only)
336 for keyword in SCHEMA_MAP:
337 for name, sub in (node.get(keyword) or {}).items():
338 yield from _walk_schemas(sub, f"{trail}/{keyword}/{name}", definitions_only=definitions_only)
339 for keyword in SCHEMA_LIST:
340 if definitions_only and keyword in CONSTRAINT_ONLY:
341 continue
342 for index, sub in enumerate(node.get(keyword) or []):
343 yield from _walk_schemas(sub, f"{trail}/{keyword}/{index}", definitions_only=definitions_only)
344
345
346@pytest.mark.parametrize("name", SCHEMA_FILES)
347def test_each_dron_schema_uses_only_what_the_validator_implements_and_resolves(name):
348 document = VALIDATOR.document(name)
349 assert document["$schema"] == "https://json-schema.org/draft/2020-12/schema"
350 for location, node in _walk_schemas(document):
351 unknown = set(node) - SUPPORTED
352 assert not unknown, f"{name} {location} uses unsupported keyword(s) {sorted(unknown)}"
353 if "$ref" in node:
354 VALIDATOR._resolve(node["$ref"], (name, document))
355 if "pattern" in node:
356 assert object_schemas.pattern_problem(node["pattern"]) is None, f"{name} {location}"
357
358
359@pytest.mark.parametrize("name", SCHEMA_FILES)
360def test_each_dron_schema_is_titled_and_says_what_dron_is(name):
361 document = VALIDATOR.document(name)
362 assert document["title"].startswith("DRON")
363 assert "Data Rules Object Notation" in document["description"]
364 assert f"Notation) {object_packages.DRON_VERSION}." in document["description"] \
365 or f"DRON {object_packages.DRON_VERSION}." in document["description"]
366
367
368def _described(node, document_name):
369 if "description" in node:
370 return True
371 if "$ref" in node:
372 target, _ = VALIDATOR._resolve(node["$ref"], (document_name, VALIDATOR.document(document_name)))
373 return _described(target, document_name) if "$ref" in target else "description" in target
374 return False
375
376
377@pytest.mark.parametrize("name", SCHEMA_FILES)
378def test_every_key_a_dron_schema_defines_has_a_description_to_act_on(name):
379 """A key with no description is a key an author has to guess at."""
380 document = VALIDATOR.document(name)
381 missing = []
382 for location, node in _walk_schemas(document, definitions_only=True):
383 for key, sub in (node.get("properties") or {}).items():
384 if isinstance(sub, dict) and not _described(sub, name):
385 missing.append(f"{location}/properties/{key}")
386 assert not missing, f"keys with no description: {missing}"
387
388
389# --------------------------------------------------------------------------
390# Part 2: every shipped declaration validates
391# --------------------------------------------------------------------------
392
393def _shipped(pattern: str):
394 return sorted(PACKAGES.glob(pattern))
395
396
397def _ids(paths):
398 return [str(path.relative_to(PACKAGES)) for path in paths]
399
400
401# Shipped declarations the schema refuses TODAY, each with what is wrong. The
402# test pins this list exactly: a new violation fails, and so does a fixed one
403# still listed. It is empty, and should stay so: the package loader is being
404# held to DRON, so a shipped file listed here would fail to install, and every
405# deployed box reinstalls these packages on upgrade. The last two
406# entries were dead keys the loader used to drop: denominations.json's
407# `maxlength` (removed, not converted to validation.max_length, which would have
408# started enforcing a length) and unit_prices.json's root `label`.
409KNOWN_SHIPPED_DRIFT: dict[str, str] = {}
410
411
412def _drift_for(relative: str, errors: list[str]) -> bool:
413 expected = KNOWN_SHIPPED_DRIFT.get(relative)
414 return bool(expected) and all(expected in error for error in errors)
415
416
417def _check_shipped(path: Path, schema_file: str):
418 relative = str(path.relative_to(PACKAGES))
419 errors = schema_errors(json.loads(path.read_text(encoding="utf-8")), schema_file)
420 if relative in KNOWN_SHIPPED_DRIFT:
421 assert errors, f"{relative} now validates: take it off KNOWN_SHIPPED_DRIFT"
422 assert _drift_for(relative, errors), f"{relative}: {errors}"
423 else:
424 assert not errors, f"{relative} is not valid DRON:\n " + "\n ".join(errors)
425
426
427@pytest.mark.parametrize("path", _shipped("*/schemas/*.json"), ids=_ids(_shipped("*/schemas/*.json")))
428def test_every_shipped_collection_schema_is_valid_dron(path):
429 _check_shipped(path, COLLECTION_SCHEMA)
430
431
432@pytest.mark.parametrize("path", _shipped("*/dbbasic-package.json"), ids=_ids(_shipped("*/dbbasic-package.json")))
433def test_every_shipped_manifest_is_valid_dron(path):
434 _check_shipped(path, PACKAGE_SCHEMA)
435
436
437@pytest.mark.parametrize("path", _shipped("*/permissions/*.json"), ids=_ids(_shipped("*/permissions/*.json")))
438def test_every_shipped_permission_file_is_valid_dron(path):
439 _check_shipped(path, PERMISSIONS_SCHEMA)
440
441
442# --- seeded view records and site routes (seed/views.tsv, seed/site_routes.tsv) ---
443#
444# Seed files are rows, not rules, so they have no schema of their own; what DRON
445# describes is the JSON in a view's `blocks` column (dron/dron-view.schema.json)
446# and the columns around it. The row checks live here, in Python, because a TSV
447# row is a flat set of strings.
448
449VIEW_COLUMNS = {"id", "title", "route", "layout", "blocks", "owner_id", "is_public", "pinned", "created_at"}
450ROUTE_COLUMNS = {"id", "pattern", "object_id", "priority", "host"}
451
452
453def _tsv_rows(path: Path) -> list[dict[str, str]]:
454 import csv
455 import io
456 return list(csv.DictReader(io.StringIO(path.read_text(encoding="utf-8")), delimiter="\t"))
457
458
459def _view_rows():
460 return [(path, row) for path in _shipped("*/seed/views.tsv") for row in _tsv_rows(path)]
461
462
463def _view_row_problems(row: dict[str, str]) -> list[str]:
464 """Everything wrong with one seeded views row, as the schema and the loaders see it."""
465 import object_site_routes
466
467 problems = []
468 unknown = set(row) - VIEW_COLUMNS
469 if unknown:
470 problems.append(f"unknown column(s) {sorted(unknown)} (a column the views schema lacks is dropped)")
471 if not (row.get("id") or "").strip():
472 problems.append("no id")
473 if not (row.get("title") or "").strip():
474 problems.append("no title (the views schema requires one)")
475 if (row.get("layout") or "single") not in ("single", "two_column", "grid"):
476 problems.append(f"layout {row.get('layout')!r}")
477 route = row.get("route") or ""
478 if route and (not route.startswith("/") or not object_site_routes._parse_pattern(route)):
479 problems.append(f"route {route!r} is not a site-route pattern")
480 for column in ("is_public", "pinned"):
481 if (row.get(column) or "false") not in ("true", "false"):
482 problems.append(f"{column} {row.get(column)!r} is not true or false")
483 try:
484 blocks = json.loads(row.get("blocks") or "[]")
485 except ValueError as exc:
486 return problems + [f"blocks is not JSON: {exc}"]
487 return problems + schema_errors(blocks, VIEW_SCHEMA)
488
489
490@pytest.mark.parametrize("path,row", _view_rows(), ids=[f"{p.parent.parent.name}/{r['id']}" for p, r in _view_rows()])
491def test_every_shipped_view_record_is_valid_dron(path, row):
492 assert not _view_row_problems(row), f"{path.relative_to(PACKAGES)}: {row['id']}: {_view_row_problems(row)}"
493
494
495def test_the_view_block_schema_refuses_what_the_renderer_would_only_draw_as_a_placeholder():
496 ok = {"kind": "list", "collection": "notes", "search": True, "sort": "oldest", "where": {"direction": "inbound"}}
497 assert not schema_errors([ok], VIEW_SCHEMA)
498 for bad in (
499 {"kind": "table", "collection": "notes"}, # no such kind
500 {"kind": "list"}, # no collection
501 {"kind": "list", "collection": "notes", "serach": True}, # a misspelt option
502 {"kind": "list", "collection": "notes", "row_limit": "ten"},
503 {"kind": "list", "collection": "notes", "sort_dir": "up"},
504 {"kind": "related", "collection": "notes", "fk_field": "project_id"}, # no match
505 {"kind": "aggregate", "collection": "lines", "sums": []},
506 {"kind": "detail", "collection": "notes"}, # no record_id
507 ):
508 assert schema_errors([bad], VIEW_SCHEMA), bad
509 assert schema_errors({"kind": "list", "collection": "notes"}, VIEW_SCHEMA), "blocks is a list"
510
511
512@pytest.mark.parametrize("path", _shipped("*/seed/site_routes.tsv"), ids=_ids(_shipped("*/seed/site_routes.tsv")))
513def test_every_shipped_site_route_row_is_well_formed(path):
514 import object_site_routes
515
516 for row in _tsv_rows(path):
517 assert not set(row) - ROUTE_COLUMNS, f"{row['id']}: unknown column(s) {sorted(set(row) - ROUTE_COLUMNS)}"
518 assert (row.get("id") or "").strip(), row
519 assert object_site_routes._parse_pattern(row["pattern"]), f"{row['id']}: pattern {row['pattern']!r}"
520 assert (row.get("object_id") or "").strip(), f"{row['id']}: no object_id"
521 assert (row.get("priority") or "0").lstrip("-").isdigit(), f"{row['id']}: priority {row.get('priority')!r}"
522
523
524def test_shipped_drift_is_listed_only_for_files_that_exist():
525 for relative in KNOWN_SHIPPED_DRIFT:
526 assert (PACKAGES / relative).is_file(), relative
527
528
529def test_the_manifests_name_the_files_the_package_really_ships():
530 """The schema checks a path's shape; this checks it points at something."""
531 problems = []
532 for manifest in _shipped("*/dbbasic-package.json"):
533 payload = json.loads(manifest.read_text(encoding="utf-8"))
534 for section in ("objects", "schemas", "permissions", "seed"):
535 for entry in payload.get(section, []):
536 if not (manifest.parent / entry["path"]).is_file():
537 problems.append(f"{manifest.parent.name}: {section} {entry['path']}")
538 assert not problems, problems
539
540
541# --------------------------------------------------------------------------
542# Part 3: the loader and the schema, side by side
543# --------------------------------------------------------------------------
544
545def collection_loader_refuses(payload) -> str | None:
546 """What the package installer does with a schema file (object_packages):
547 hold it to DRON, then normalize it."""
548 try:
549 object_schemas.normalize_declaration("widgets", payload)
550 except ValueError as exc:
551 return str(exc)
552 return None
553
554
555def package_loader_refuses(payload, package_id: str = "widgets") -> str | None:
556 try:
557 object_packages._normalize_manifest(package_id, payload)
558 except ValueError as exc:
559 return str(exc)
560 return None
561
562
563def permissions_loader_refuses(payload) -> str | None:
564 import tempfile
565
566 with tempfile.TemporaryDirectory() as directory:
567 folder = Path(directory)
568 (folder / "rules.json").write_text(json.dumps(payload), encoding="utf-8")
569 try:
570 object_packages._load_permission_fragment(folder, {"path": "rules.json"}, package_id="widgets")
571 except (ValueError, RuntimeError) as exc:
572 return str(exc)
573 return None
574
575
576KINDS = {
577 "collection": (collection_loader_refuses, COLLECTION_SCHEMA),
578 "package": (package_loader_refuses, PACKAGE_SCHEMA),
579 "permissions": (permissions_loader_refuses, PERMISSIONS_SCHEMA),
580}
581
582# What both accept, from which the cases below are edited.
583COLLECTION = {
584 "name": "widgets",
585 "title": "Widgets",
586 "version": 1,
587 "fields": [
588 {"name": "id"},
589 {"name": "status", "type": "enum", "enum": ["draft", "posted"]},
590 {"name": "qty", "type": "integer"},
591 {"name": "note", "type": "text"},
592 ],
593}
594PACKAGE = {
595 "id": "widgets",
596 "name": "Widgets",
597 "version": "0.1.0",
598 "compatibility": {"dbbasic_object_server": ">=0.1.0"},
599 "objects": [{"id": "site_widgets", "path": "objects/site/widgets.py"}],
600 "schemas": [{"collection": "widgets", "path": "schemas/widgets.json"}],
601 "permissions": [{"path": "permissions/rules.json"}],
602 "seed": [{"collection": "widgets", "path": "seed/widgets.tsv"}],
603}
604PERMISSIONS = {
605 "rules": [
606 {"effect": "allow", "principal": "registered", "actions": ["read"],
607 "collection": "widgets", "row_filter": {"owner_id": "$user_id"}, "reason": "own rows"},
608 ],
609}
610BASE = {"collection": COLLECTION, "package": PACKAGE, "permissions": PERMISSIONS}
611
612
613def edit(kind: str, change):
614 """The base declaration of a kind with `change(payload)` applied."""
615 payload = copy.deepcopy(BASE[kind])
616 result = change(payload)
617 return payload if result is None else result
618
619
620def set_field(index: int, **keys):
621 def apply(payload):
622 payload["fields"][index].update(keys)
623 return apply
624
625
626def add_field(**field):
627 def apply(payload):
628 payload["fields"].append(field)
629 return apply
630
631
632def put(path: str, value):
633 """Set payload[a][b]... = value; a numeric part indexes a list."""
634 def apply(payload):
635 node = payload
636 parts = path.split(".")
637 for part in parts[:-1]:
638 node = node[int(part)] if isinstance(node, list) else node[part]
639 last = parts[-1]
640 if isinstance(node, list):
641 node[int(last)] = value
642 else:
643 node[last] = value
644 return apply
645
646
647def drop(path: str):
648 def apply(payload):
649 node = payload
650 parts = path.split(".")
651 for part in parts[:-1]:
652 node = node[int(part)] if isinstance(node, list) else node[part]
653 del node[parts[-1]]
654 return apply
655
656
657def several(*changes):
658 def apply(payload):
659 for change in changes:
660 change(payload)
661 return apply
662
663
664# (id, kind, change, loader_accepts, schema_accepts)
665# Cases where both sides give the same answer.
666AGREE = [
667 # --- accepted by both -------------------------------------------------
668 ("collection: the base", "collection", lambda p: None, True, True),
669 ("collection: a $schema pointer is tolerated", "collection", put("$schema", "../../dron/dron-collection.schema.json"), True, True),
670 ("collection: the `collection` spelling of name", "collection", lambda p: {**{k: v for k, v in p.items() if k != "name"}, "collection": "widgets"}, True, True),
671 ("collection: append storage", "collection", put("storage", "append"), True, True),
672 ("collection: unique with scope, case and message", "collection",
673 put("unique", [{"fields": ["note"], "scope": ["status"], "ignore_case": True, "message": "Already used."}]), True, True),
674 ("collection: locked_when with an except list", "collection",
675 put("locked_when", [{"when": {"status": ["posted"]}, "except": ["status", "note"], "allow_delete": True,
676 "message": "Posted entries are settled."}]), True, True),
677 ("collection: locked_when with a fields list", "collection",
678 put("locked_when", [{"when": {"status": "posted"}, "fields": ["note", "qty"], "message": "Posted notes are settled."}]), True, True),
679 ("collection: locked_checks with every key", "collection",
680 put("locked_checks", [{"name": "ceiling", "object": "hook_widgets", "function": "LOCKED_CHECK",
681 "reads": ["gadgets"], "lock": "ledger",
682 "on": {"create": True, "update": ["qty"], "delete": False}}]), True, True),
683 ("collection: guarded transitions", "collection",
684 set_field(1, transitions={"draft": ["posted", {"to": "draft", "when": {"owner_id": "$user_id"}}], "posted": []}), True, True),
685 ("collection: strict bound on a number", "collection", set_field(2, validation={"exclusive_min": 0, "max": 100}), True, True),
686 ("collection: required_when naming another field", "collection",
687 set_field(3, validation={"required_when": {"status": ["posted"]}}), True, True),
688 ("collection: a rollup", "collection",
689 add_field(name="total", type="computed",
690 rollup={"collection": "gadgets", "fk_field": "widget_id", "op": "sum", "field": "cents", "where": {"status": "ok"}}), True, True),
691 ("collection: a count rollup needs no field", "collection",
692 add_field(name="n", type="computed", rollup={"collection": "gadgets", "fk_field": "widget_id", "op": "count"}), True, True),
693 ("collection: a formula", "collection", add_field(name="both", type="computed", formula="note + \" \" + note"), True, True),
694 ("collection: field permissions", "collection",
695 set_field(3, permissions={"owner": "read", "role:moderator": "edit", "default": "hidden"}), True, True),
696 ("collection: views, forms, search, capabilities", "collection",
697 lambda p: p.update(views={"list_mode": "board", "list_fields": ["status"], "board": {"group_field": "status"},
698 "related": [{"collection": "gadgets", "fk_field": "widget_id"}]},
699 forms={"default": {"fields": ["note"]}}, search={"fields": ["note"]},
700 capabilities={"comments": True}, hooks={"before_write": "hook_widgets"}), True, True),
701 ("package: the base", "package", lambda p: None, True, True),
702 ("package: a $schema pointer is tolerated", "package", put("$schema", "../../dron/dron-package.schema.json"), True, True),
703 ("package: dependencies as ids and objects", "package", put("dependencies", ["app-nav", {"id": "app-views", "version": ">=1"}]), True, True),
704 ("package: a schedule", "package",
705 put("schedules", [{"id": "nightly", "object_id": "system_widgets", "schedule": "10 6 * * *", "method": "POST", "payload": {"a": 1}}]), True, True),
706 ("package: a one-time schedule", "package",
707 put("schedules", [{"id": "once", "object_id": "system_widgets", "type": "onetime", "schedule": "2030-01-01T00:00:00Z"}]), True, True),
708 ("package: a nav entry", "package",
709 put("nav", [{"id": "widgets", "label": "Widgets", "path": "/widgets", "blurb": "Widgets.", "surface": "public", "group": "Work", "order": 5}]), True, True),
710 ("package: a declared attention count with detail", "package",
711 put("attention", [{"id": "to_post", "collection": "widgets", "where": {"status": "draft", "created_at": {"op": "older_than_days", "value": {"setting": "a.b", "default": 3}}},
712 "detail": [{"op": "count", "text": "{value} old"}, {"op": "sum", "field": "qty", "format": "cents", "text": "{value} owed", "show_zero": True}],
713 "label": "Widgets to post", "path": "/widgets", "nav_id": "widgets", "group": "Work", "severity": "warning"}]), True, True),
714 ("package: a code provider attention count", "package",
715 put("attention", [{"id": "to_pick", "object_id": "system_pick", "reads": ["orders"], "label": "To pick", "path": "/orders"}]), True, True),
716 ("package: nav_optional", "package", put("nav_optional", True), True, True),
717 ("package: a connector", "package", put("connectors", [{"collection": "widgets", "module": "objects/x.py", "entry": "reconcile"}]), True, True),
718 ("permissions: the base", "permissions", lambda p: None, True, True),
719 ("permissions: a deny with a range filter and a retracted rule", "permissions",
720 lambda p: p.update(retracted=[{"effect": "allow", "principal": "public", "actions": ["read"], "collection": "widgets", "reason": "withdrawn"}],
721 rules=[{"effect": "deny", "principal": "role:x", "actions": ["delete", "update"], "collection": "widgets",
722 "row_filter": {"status": {"op": "in", "value": ["posted"]},
723 "created_at": [{"op": "gte", "value": "2026-01-01"}, {"op": "lt", "value": "2027-01-01"}]},
724 "fields": ["id"], "denied_fields": ["note"], "valid_from": "2026-01-01T00:00:00Z", "expires_at": "2027-01-01", "reason": "x"}]), True, True),
725 ("permissions: owner_fallback deny", "permissions",
726 put("rules", [{"effect": "deny", "principal": "owner_fallback", "actions": ["update", "delete"], "collection": "widgets", "reason": "ledger"}]), True, True),
727 ("permissions: an object rule with a wildcard", "permissions",
728 put("rules", [{"effect": "allow", "principal": "user:42", "actions": ["*"], "object_id": "site_widgets", "reason": "x"}]), True, True),
729 ("permissions: set-valued variables", "permissions",
730 put("rules.0.row_filter", {"project_id": "$accessible_projects", "id": {"op": "in", "value": "$shared_records"}}), True, True),
731 # --- refused by both -------------------------------------------------
732 ("collection: not an object", "collection", lambda p: [], False, False),
733 ("collection: name does not match... a bad name", "collection", put("name", "bad name"), False, False),
734 ("collection: fields not a list", "collection", put("fields", {}), False, False),
735 ("collection: title not a string", "collection", put("title", 5), False, False),
736 ("collection: version 0", "collection", put("version", 0), False, False),
737 ("collection: version true", "collection", put("version", True), False, False),
738 ("collection: unknown storage", "collection", put("storage", "wal"), False, False),
739 ("collection: a field with a bad name", "collection", add_field(name="1abc"), False, False),
740 ("collection: the reserved field _op", "collection", add_field(name="_op"), False, False),
741 ("collection: a field with no name", "collection", add_field(type="text"), False, False),
742 ("collection: unique as bare names", "collection", put("unique", ["note"]), False, False),
743 ("collection: unique with a misspelt key", "collection", put("unique", [{"fields": ["note"], "ignore_cas": True}]), False, False),
744 ("collection: unique naming no field", "collection", put("unique", [{"fields": []}]), False, False),
745 ("collection: unique on id", "collection", put("unique", [{"fields": ["id"]}]), False, False),
746 ("collection: unique ignore_case not a bool", "collection", put("unique", [{"fields": ["note"], "ignore_case": "yes"}]), False, False),
747 ("collection: unique with a blank message", "collection", put("unique", [{"fields": ["note"], "message": " "}]), False, False),
748 ("collection: locked_when with an unknown key", "collection", put("locked_when", [{"when": {"status": "posted"}, "unless": []}]), False, False),
749 ("collection: locked_when with an empty when", "collection", put("locked_when", [{"when": {}}]), False, False),
750 ("collection: locked_when with a number in when", "collection", put("locked_when", [{"when": {"status": 3}}]), False, False),
751 ("collection: locked_when with an empty list in when", "collection", put("locked_when", [{"when": {"status": []}}]), False, False),
752 ("collection: locked_when with both except and fields", "collection",
753 put("locked_when", [{"when": {"status": "posted"}, "except": ["status"], "fields": ["note"]}]), False, False),
754 ("collection: locked_when with an empty fields list", "collection", put("locked_when", [{"when": {"status": "posted"}, "fields": []}]), False, False),
755 ("collection: locked_when with fields not a list", "collection", put("locked_when", [{"when": {"status": "posted"}, "fields": "note"}]), False, False),
756 ("collection: locked_when allow_delete a string", "collection", put("locked_when", [{"when": {"status": "x"}, "allow_delete": "yes"}]), False, False),
757 ("collection: locked_checks with no object", "collection", put("locked_checks", [{"reads": ["gadgets"]}]), False, False),
758 ("collection: locked_checks calling POST", "collection", put("locked_checks", [{"object": "hook_x", "function": "post"}]), False, False),
759 ("collection: locked_checks with an unknown key", "collection", put("locked_checks", [{"object": "hook_x", "when": 1}]), False, False),
760 ("collection: locked_checks with an unknown on key", "collection", put("locked_checks", [{"object": "hook_x", "on": {"read": True}}]), False, False),
761 ("collection: locked_checks selecting no write", "collection",
762 put("locked_checks", [{"object": "hook_x", "on": {"create": False, "update": False, "delete": False}}]), False, False),
763 ("collection: locked_checks with an empty update list", "collection", put("locked_checks", [{"object": "hook_x", "on": {"update": []}}]), False, False),
764 ("collection: locked_checks with an upper-case lock", "collection", put("locked_checks", [{"object": "hook_x", "lock": "Ledger"}]), False, False),
765 ("collection: a transition entry with no to", "collection", set_field(1, transitions={"draft": [{"when": {"a": "b"}}]}), False, False),
766 ("collection: a transition entry with an extra key", "collection", set_field(1, transitions={"draft": [{"to": "posted", "also": 1}]}), False, False),
767 ("collection: a transition guard with a number", "collection", set_field(1, transitions={"draft": [{"to": "posted", "when": {"a": 1}}]}), False, False),
768 ("collection: an empty transition guard", "collection", set_field(1, transitions={"draft": [{"to": "posted", "when": {}}]}), False, False),
769 ("collection: transitions not a map", "collection", set_field(1, transitions=["a"]), False, False),
770 ("collection: an exclusive bound on a text field", "collection", set_field(3, validation={"exclusive_min": 0}), False, False),
771 ("collection: an exclusive bound that is not a number", "collection", set_field(2, validation={"exclusive_min": "abc"}), False, False),
772 ("collection: required_when empty", "collection", set_field(3, validation={"required_when": {}}), False, False),
773 ("collection: required_when with a number", "collection", set_field(3, validation={"required_when": {"status": 1}}), False, False),
774 ("collection: required_when on a read-only field", "collection",
775 set_field(3, read_only=True, validation={"required_when": {"status": "posted"}}), False, False),
776 ("collection: required_when on a computed field", "collection",
777 add_field(name="c", type="computed", validation={"required_when": {"status": "posted"}}), False, False),
778 # Once SCHEMA_STRICTER: the package loader now runs
779 # object_schemas.check_declaration before normalizing, so a key DRON does
780 # not define (a typo, a dead key, an engine-only synonym) refuses the install.
781 ("collection: a key the loader drops", "collection", put("colour", "red"), False, False),
782 ("collection: a field key the loader drops", "collection", set_field(3, maxlength=10), False, False),
783 ("collection: the regex alias", "collection", set_field(3, validation={"regex": "a+"}), False, False),
784 ("collection: the required alias in validation", "collection", set_field(3, validation={"required": True}), False, False),
785 ("collection: the readonly alias", "collection", set_field(3, readonly=True), False, False),
786 ("collection: the computed flag", "collection", set_field(3, computed=True), False, False),
787 ("collection: a views key that does nothing", "collection", put("views", {"columns": ["note"]}), False, False),
788 # Once SCHEMA_STRICTER: a value of the wrong type is refused, not coerced.
789 ("collection: required given as a string", "collection", set_field(3, required="no"), False, False),
790 ("collection: a version given as a string", "collection", put("version", "3"), False, False),
791 # Once SCHEMA_STRICTER: DRON spells each type, enum and choice one way; the
792 # package loader refuses another spelling (with DRON's) and an unknown type.
793 ("collection: an unknown field type", "collection", set_field(3, type="money"), False, False),
794 ("collection: a field type in capitals", "collection", set_field(3, type="INTEGER"), False, False),
795 ("collection: enum as {values: [...]}", "collection", set_field(1, enum={"values": ["a"]}), False, False),
796 # Once SCHEMA_STRICTER: a guard's $-variable is held to the closed set, as a
797 # rule's is, and a capability to true or false.
798 ("collection: a guard variable that is not one", "collection",
799 set_field(1, transitions={"draft": [{"to": "posted", "when": {"owner_id": "$userid"}}]}), False, False),
800 ("collection: a capability that is not a bool", "collection", put("capabilities", {"comments": "yes"}), False, False),
801 # Once SCHEMA_STRICTER: a bound is a number, or text that reads as one.
802 ("collection: a min that is not a number", "collection", set_field(2, validation={"min": "abc"}), False, False),
803 ("collection: a max that is not a number", "collection", set_field(2, validation={"max": "ten"}), False, False),
804 ("collection: a min that is a boolean", "collection", set_field(2, validation={"min": True}), False, False),
805 ("collection: a min that is empty text", "collection", set_field(2, validation={"min": ""}), False, False),
806 ("collection: a min written as text", "collection", set_field(2, validation={"min": " 5 ", "max": "1e3"}), True, True),
807 # Once SCHEMA_STRICTER: a field's access level is one of the three DRON defines.
808 ("collection: an unknown permission level", "collection", set_field(3, permissions={"default": "maybe"}), False, False),
809 ("collection: a permission level the engine reads as a synonym", "collection", set_field(3, permissions={"owner": "readonly"}), False, False),
810 ("collection: a role's level that is not one", "collection", set_field(3, permissions={"roles": {"sales": "none"}}), False, False),
811 ("collection: a bare permission level that is not one", "collection", set_field(3, permissions="maybe"), False, False),
812 ("collection: a permission level as an object", "collection", set_field(3, permissions={"owner": {"access": "edit"}}), False, False),
813 ("collection: permissions as a list", "collection", set_field(3, permissions=["edit"]), False, False),
814 ("collection: a bare permission level", "collection", set_field(3, permissions="hidden"), True, True),
815 ("collection: a level mapped to its principals", "collection",
816 set_field(3, permissions={"edit": ["role:admin"], "hidden": ["public"]}), True, True),
817 # Once SCHEMA_STRICTER: a relation names the collection its ids must exist in.
818 ("collection: a relation object with no collection", "collection", set_field(1, relation={"display_field": "name"}), False, False),
819 ("collection: a relation to a name that is not one", "collection", set_field(1, relation="bad name!"), False, False),
820 ("collection: a relation as a list", "collection", set_field(1, relation=["gadgets"]), False, False),
821 ("collection: a relation as a bare name", "collection", set_field(1, relation="gadgets"), True, True),
822 # Once SCHEMA_STRICTER: a formula (or rollup) belongs to a computed field.
823 ("collection: a formula on a field that is not computed", "collection", set_field(3, formula="qty + 1"), False, False),
824 ("collection: a rollup on a field that is not computed", "collection",
825 set_field(3, rollup={"collection": "gadgets", "fk_field": "w", "op": "count"}), False, False),
826 # Once SCHEMA_STRICTER: a rollup the engine could never compute.
827 ("collection: a sum rollup with no field", "collection",
828 add_field(name="t", type="computed", rollup={"collection": "gadgets", "fk_field": "w", "op": "sum"}), False, False),
829 ("collection: a rollup op that is not one", "collection",
830 add_field(name="t", type="computed", rollup={"collection": "gadgets", "fk_field": "w", "op": "median", "field": "c"}), False, False),
831 ("collection: a rollup op in capitals", "collection",
832 add_field(name="t", type="computed", rollup={"collection": "gadgets", "fk_field": "w", "op": "SUM", "field": "c"}), False, False),
833 ("collection: a rollup with no op", "collection",
834 add_field(name="t", type="computed", rollup={"collection": "gadgets", "fk_field": "w", "field": "c"}), False, False),
835 ("collection: a rollup with no collection", "collection",
836 add_field(name="t", type="computed", rollup={"fk_field": "w", "op": "count"}), False, False),
837 ("collection: a rollup with no fk_field", "collection",
838 add_field(name="t", type="computed", rollup={"collection": "gadgets", "op": "count"}), False, False),
839 ("collection: a rollup that is not an object", "collection", add_field(name="t", type="computed", rollup="gadgets"), False, False),
840 # Once SCHEMA_STRICTER: a hook is named by an object id.
841 ("collection: a hook name that is not an object id", "collection", put("hooks", {"before_write": "bad name!"}), False, False),
842 ("collection: a hook name with a path in it", "collection", put("hooks", {"before_write": "hooks/widgets.py"}), False, False),
843 ("collection: a hook name that is not text", "collection", put("hooks", {"before_write": ["hook_widgets"]}), False, False),
844 ("collection: an empty hook name", "collection", put("hooks", {"before_write": ""}), False, False),
845 # Once SCHEMA_STRICTER: a list mode is one of the six DRON defines.
846 ("collection: a list_mode that is not one", "collection", put("views", {"list_mode": "grid"}), False, False),
847 ("collection: a list_mode in capitals", "collection", put("views", {"list_mode": "Table"}), False, False),
848 ("collection: a list_mode that is not text", "collection", put("views", {"list_mode": ["table"]}), False, False),
849 ("collection: a list_mode that is defined", "collection", put("views", {"list_mode": "feed"}), True, True),
850 # Once SCHEMA_STRICTER: every section is the shape DRON gives it (an object, a list of field names, a field name).
851 ("collection: hooks as text", "collection", put("hooks", "hook_widgets"), False, False),
852 ("collection: hooks as a list", "collection", put("hooks", ["hook_widgets"]), False, False),
853 ("collection: views as text", "collection", put("views", "table"), False, False),
854 ("collection: views as a list", "collection", put("views", []), False, False),
855 ("collection: search as text", "collection", put("search", "title"), False, False),
856 ("collection: search as a list", "collection", put("search", ["note"]), False, False),
857 ("collection: capabilities as a list", "collection", put("capabilities", ["comments"]), False, False),
858 ("collection: capabilities as text", "collection", put("capabilities", "comments"), False, False),
859 ("collection: ui as text", "collection", put("ui", "compact"), False, False),
860 ("collection: ui as a list", "collection", put("ui", []), False, False),
861 ("collection: blocks as text", "collection", put("blocks", "feed"), False, False),
862 ("collection: forms as text", "collection", put("forms", "default"), False, False),
863 ("collection: flow as a list", "collection", put("flow", []), False, False),
864 ("collection: layout as text", "collection", put("layout", "wide"), False, False),
865 ("collection: table as a list", "collection", put("table", []), False, False),
866 ("collection: diagram as text", "collection", put("diagram", "er"), False, False),
867 ("collection: validation as a list", "collection", put("validation", []), False, False),
868 ("collection: permissions as a list", "collection", put("permissions", []), False, False),
869 ("collection: description as a list", "collection", put("description", ["a"]), False, False),
870 ("collection: title as null", "collection", put("title", None), False, False),
871 ("collection: ui as an object", "collection", put("ui", {"icon": "box"}), True, True),
872 ("collection: search.fields as text", "collection", put("search", {"fields": "note"}), False, False),
873 ("collection: search.fields empty", "collection", put("search", {"fields": []}), False, False),
874 ("collection: search.fields with a bad name", "collection", put("search", {"fields": ["a b"]}), False, False),
875 ("collection: search.fields with a number", "collection", put("search", {"fields": [3]}), False, False),
876 ("collection: search.result_fields as text", "collection", put("search", {"fields": ["note"], "result_fields": "id"}), False, False),
877 ("collection: search with names", "collection", put("search", {"fields": ["note"], "result_fields": ["id", "status"]}), True, True),
878 ("collection: views.list_fields as text", "collection", put("views", {"list_fields": "note"}), False, False),
879 ("collection: views.list_fields as an object", "collection", put("views", {"list_fields": {"a": 1}}), False, False),
880 ("collection: views.list_fields with a bad name", "collection", put("views", {"list_fields": ["a b"]}), False, False),
881 ("collection: views.detail_fields as text", "collection", put("views", {"detail_fields": "note"}), False, False),
882 ("collection: views.filter_fields as text", "collection", put("views", {"filter_fields": "status"}), False, False),
883 ("collection: views.board as text", "collection", put("views", {"board": "status"}), False, False),
884 ("collection: views.board group_field not a name", "collection", put("views", {"board": {"group_field": "a b"}}), False, False),
885 ("collection: views.tree as a list", "collection", put("views", {"tree": []}), False, False),
886 ("collection: views.tree parent_field not text", "collection", put("views", {"tree": {"parent_field": 5}}), False, False),
887 ("collection: views.calendar as text", "collection", put("views", {"calendar": "when"}), False, False),
888 ("collection: views.calendar date_field empty", "collection", put("views", {"calendar": {"date_field": ""}}), False, False),
889 ("collection: views.related as text", "collection", put("views", {"related": "gadgets"}), False, False),
890 ("collection: views.related entry as text", "collection", put("views", {"related": ["gadgets"]}), False, False),
891 ("collection: views.related with no fk_field", "collection", put("views", {"related": [{"collection": "gadgets"}]}), False, False),
892 ("collection: views.related with no collection", "collection", put("views", {"related": [{"fk_field": "w"}]}), False, False),
893 ("collection: views.related collection not a name", "collection", put("views", {"related": [{"collection": "bad name", "fk_field": "w"}]}), False, False),
894 ("collection: views.related fk_field not a name", "collection", put("views", {"related": [{"collection": "gadgets", "fk_field": "a b"}]}), False, False),
895 ("collection: views with every list and object", "collection", put("views", {"list_mode": "board", "list_fields": ["note"], "detail_fields": ["note"], "filter_fields": ["status"], "board": {"group_field": "status"}, "tree": {"parent_field": "note"}, "calendar": {"date_field": "note"}, "related": [{"collection": "gadgets", "fk_field": "w"}]}), True, True),
896 ("collection: blocks.feed as text", "collection", put("blocks", {"feed": "x"}), False, False),
897 ("collection: blocks.feed with no time_field", "collection", put("blocks", {"feed": {"owner_field": "note"}}), False, False),
898 ("collection: blocks.feed with no owner_field", "collection", put("blocks", {"feed": {"time_field": "note"}}), False, False),
899 ("collection: blocks.feed owner_field not a name", "collection", put("blocks", {"feed": {"owner_field": "a b", "time_field": "note"}}), False, False),
900 ("collection: blocks.feed summary_fields as text", "collection", put("blocks", {"feed": {"owner_field": "note", "time_field": "note", "summary_fields": "note"}}), False, False),
901 ("collection: blocks.feed visibility_true_value a number", "collection", put("blocks", {"feed": {"owner_field": "note", "time_field": "note", "visibility_true_value": 1}}), False, False),
902 ("collection: blocks.feed link_field not a name", "collection", put("blocks", {"feed": {"owner_field": "note", "time_field": "note", "link_field": ""}}), False, False),
903 ("collection: blocks.feed complete", "collection", put("blocks", {"feed": {"owner_field": "note", "time_field": "note", "visibility_field": "status", "visibility_true_value": "posted", "summary_fields": ["note"], "link_field": "note"}}), True, True),
904 ("collection: a form as text", "collection", put("forms", {"default": "x"}), False, False),
905 ("collection: a form with fields as text", "collection", put("forms", {"default": {"fields": "note"}}), False, False),
906 ("collection: a form with a bad field name", "collection", put("forms", {"default": {"fields": ["a b"]}}), False, False),
907 ("collection: a form with fields", "collection", put("forms", {"default": {"fields": ["note", "qty"]}}), True, True),
908 # Once SCHEMA_STRICTER: the plain values of a field are the kind DRON gives them.
909 ("collection: a label that is a number", "collection", set_field(3, label=5), False, False),
910 ("collection: a label that is a list", "collection", set_field(3, label=["Note"]), False, False),
911 ("collection: a label that is null", "collection", set_field(3, label=None), False, False),
912 ("collection: a help that is a number", "collection", set_field(3, help=1), False, False),
913 ("collection: a placeholder that is a list", "collection", set_field(3, placeholder=["x"]), False, False),
914 ("collection: a field description that is an object", "collection", set_field(3, description={"a": 1}), False, False),
915 ("collection: a text label, help, placeholder and description", "collection", set_field(3, label="Note", help="h", placeholder="p", description="d"), True, True),
916 ("collection: a default that is a list", "collection", set_field(3, default=["a"]), False, False),
917 ("collection: a default that is an object", "collection", set_field(3, default={"a": 1}), False, False),
918 ("collection: a default of each scalar kind", "collection", set_field(3, default="x"), True, True),
919 ("collection: a null default", "collection", set_field(3, default=None), True, True),
920 ("collection: a numeric default", "collection", set_field(2, default=3), True, True),
921 ("collection: a field ui that is text", "collection", set_field(3, ui="wide"), False, False),
922 ("collection: a field layout that is a list", "collection", set_field(3, layout=[]), False, False),
923 ("collection: a field ui object", "collection", set_field(3, ui={"rows": 4}, layout={"width": "half"}), True, True),
924 ("collection: a field validation that is text", "collection", set_field(3, validation="required"), False, False),
925 ("collection: a field validation that is a list", "collection", set_field(3, validation=[]), False, False),
926 ("collection: a field validation that is null", "collection", set_field(3, validation=None), False, False),
927 ("collection: a visible_when with no field", "collection", set_field(3, visible_when={"equals": "x"}), False, False),
928 ("collection: a visible_when that is text", "collection", set_field(3, visible_when="status"), False, False),
929 ("collection: a visible_when field that is not a name", "collection", set_field(3, visible_when={"field": "a b", "equals": "x"}), False, False),
930 ("collection: a visible_when equals that is a number", "collection", set_field(3, visible_when={"field": "status", "equals": 1}), False, False),
931 ("collection: a visible_when in that is text", "collection", set_field(3, visible_when={"field": "status", "in": "draft"}), False, False),
932 ("collection: a visible_when in with a number", "collection", set_field(3, visible_when={"field": "status", "in": ["draft", 2]}), False, False),
933 ("collection: a visible_when equals", "collection", set_field(3, visible_when={"field": "status", "equals": "posted"}), True, True),
934 ("collection: a visible_when in", "collection", set_field(3, visible_when={"field": "status", "in": ["draft", "posted"]}), True, True),
935 ("collection: an empty enum", "collection", set_field(1, enum=[]), False, False),
936 ("collection: an enum with a list in it", "collection", set_field(1, enum=["draft", ["posted"]]), False, False),
937 ("collection: an enum with null in it", "collection", set_field(1, enum=["draft", None]), False, False),
938 ("collection: an enum with an object in it", "collection", set_field(1, enum=["draft", {"a": 1}]), False, False),
939 ("collection: an enum with a repeated value", "collection", set_field(1, enum=["draft", "draft"]), False, False),
940 ("collection: an enum of numbers and booleans", "collection", set_field(1, enum=["draft", 2, True]), True, True),
941 ("collection: a subject that is not email or relation", "collection", set_field(3, subject="phone"), False, False),
942 ("collection: a subject of email", "collection", set_field(3, subject="email"), True, True),
943 ("collection: a store that is not extra", "collection", set_field(3, store="main"), False, False),
944 ("collection: a store of extra", "collection", set_field(3, store="extra"), True, True),
945 # Once SCHEMA_STRICTER: a name is a name, a message is text, a list of principals sits under edit, read or hidden.
946 ("collection: an empty name", "collection", put("name", ""), False, False),
947 ("collection: a null name", "collection", put("name", None), False, False),
948 ("collection: an empty collection key", "collection", lambda p: {**{k: v for k, v in p.items() if k != "name"}, "collection": ""}, False, False),
949 ("collection: a unique message that is null", "collection", put("unique", [{"fields": ["note"], "message": None}]), False, False),
950 ("collection: a locked_when message that is null", "collection",
951 put("locked_when", [{"when": {"status": "posted"}, "message": None}]), False, False),
952 ("collection: a principal mapped to a list of principals", "collection", set_field(3, permissions={"owner": ["role:a"]}), False, False),
953 ("collection: a role mapped to a list of principals", "collection", set_field(3, permissions={"role:admin": ["role:a"]}), False, False),
954 ("collection: the engine's synonym of an access level as a list key", "collection", set_field(3, permissions={"write": ["role:a"]}), False, False),
955 ("collection: an access level in capitals as a list key", "collection", set_field(3, permissions={"Edit": ["role:a"]}), False, False),
956 ("collection: default mapped to a list", "collection", set_field(3, permissions={"default": ["edit"]}), False, False),
957 ("collection: a roles entry mapped to a list", "collection", set_field(3, permissions={"roles": {"sales": ["role:a"]}}), False, False),
958 ("collection: edit, read and hidden each mapped to principals", "collection",
959 set_field(3, permissions={"edit": ["role:a"], "read": ["registered"], "hidden": ["public"], "default": "read"}), True, True),
960 ("collection: a list of principals with an empty one", "collection", set_field(3, permissions={"edit": [""]}), False, False),
961 ("collection: edit mapped to a level, as a principal's name", "collection", set_field(3, permissions={"edit": "read"}), True, True),
962 # Once SCHEMA_STRICTER: a length is a whole number of at least 0, a pattern a regular expression.
963 ("collection: a min_length below zero", "collection", set_field(3, validation={"min_length": -1}), False, False),
964 ("collection: a min_length with a fraction", "collection", set_field(3, validation={"min_length": 2.5}), False, False),
965 ("collection: a min_length written as text", "collection", set_field(3, validation={"min_length": "3"}), False, False),
966 ("collection: a min_length that is a boolean", "collection", set_field(3, validation={"min_length": True}), False, False),
967 ("collection: a min_length that is a list", "collection", set_field(3, validation={"min_length": [3]}), False, False),
968 ("collection: a max_length below zero", "collection", set_field(3, validation={"max_length": -1}), False, False),
969 ("collection: a max_length with a fraction", "collection", set_field(3, validation={"max_length": 9.5}), False, False),
970 ("collection: a max_length written as text", "collection", set_field(3, validation={"max_length": "20"}), False, False),
971 ("collection: a max_length that is empty text", "collection", set_field(3, validation={"max_length": ""}), False, False),
972 ("collection: lengths of 0 and 3", "collection", set_field(3, validation={"min_length": 0, "max_length": 3}), True, True),
973 ("collection: a whole length written 3.0", "collection", set_field(3, validation={"max_length": 3.0}), True, True),
974 ("collection: a pattern that is not a regular expression", "collection", set_field(3, validation={"pattern": "("}), False, False),
975 ("collection: a pattern with an unclosed class", "collection", set_field(3, validation={"pattern": "[a-"}), False, False),
976 ("collection: a pattern that is not text", "collection", set_field(3, validation={"pattern": 5}), False, False),
977 # Python's `re` compiles these; they are outside the dialect two engines read alike.
978 ("collection: a pattern with an inline flag", "collection", set_field(3, validation={"pattern": "(?i)[a-z]+"}), False, False),
979 ("collection: a pattern with a lookbehind", "collection", set_field(3, validation={"pattern": "(?<=a)b"}), False, False),
980 ("collection: a pattern with a named group", "collection", set_field(3, validation={"pattern": "(?P<y>[0-9]{4})"}), False, False),
981 ("collection: a pattern with a backreference", "collection", set_field(3, validation={"pattern": "([a-z])\\1"}), False, False),
982 ("collection: a pattern with a word boundary", "collection", set_field(3, validation={"pattern": "\\bword\\b"}), False, False),
983 ("collection: a pattern with a possessive quantifier", "collection", set_field(3, validation={"pattern": "[a-z]++"}), False, False),
984 ("collection: a pattern with an unescaped brace", "collection", set_field(3, validation={"pattern": "{value}"}), False, False),
985 # Once SCHEMA_STRICTER: names the engine looks up, and one computation per field.
986 ("collection: a field with both formula and rollup", "collection",
987 add_field(name="t", type="computed", formula="qty + 1", rollup={'collection': 'gadgets', 'fk_field': 'w', 'op': 'sum', 'field': 'c'}), False, False),
988 ("collection: a rollup collection that is not a name", "collection",
989 add_field(name="t", type="computed", rollup={'collection': 'bad name!', 'fk_field': 'w', 'op': 'sum', 'field': 'c'}), False, False),
990 ("collection: a rollup collection that is not text", "collection",
991 add_field(name="t", type="computed", rollup={'collection': 5, 'fk_field': 'w', 'op': 'sum', 'field': 'c'}), False, False),
992 ("collection: a rollup fk_field that is not a name", "collection",
993 add_field(name="t", type="computed", rollup={'collection': 'gadgets', 'fk_field': '1x', 'op': 'sum', 'field': 'c'}), False, False),
994 ("collection: a rollup field that is not a name", "collection",
995 add_field(name="t", type="computed", rollup={'collection': 'gadgets', 'fk_field': 'w', 'op': 'sum', 'field': 'a b'}), False, False),
996 ("collection: a rollup where that is a list", "collection",
997 add_field(name="t", type="computed", rollup={'collection': 'gadgets', 'fk_field': 'w', 'op': 'sum', 'field': 'c', 'where': ['a']}), False, False),
998 ("collection: a rollup where that is text", "collection",
999 add_field(name="t", type="computed", rollup={'collection': 'gadgets', 'fk_field': 'w', 'op': 'sum', 'field': 'c', 'where': 'a=1'}), False, False),
1000 ("collection: a rollup where that names a bad field", "collection",
1001 add_field(name="t", type="computed", rollup={'collection': 'gadgets', 'fk_field': 'w', 'op': 'sum', 'field': 'c', 'where': {'bad key': 1}}), False, False),
1002 ("collection: a rollup where with a list value", "collection",
1003 add_field(name="t", type="computed", rollup={'collection': 'gadgets', 'fk_field': 'w', 'op': 'sum', 'field': 'c', 'where': {'a': [1]}}), False, False),
1004 ("collection: a relation display_field that is not a name", "collection",
1005 set_field(1, relation={"collection": "gadgets", "display_field": "full name"}), False, False),
1006 ("collection: a relation display_field that is not text", "collection",
1007 set_field(1, relation={"collection": "gadgets", "display_field": 5}), False, False),
1008 ("collection: a rollup with where, names and a bool value", "collection",
1009 add_field(name="t", type="computed", rollup={"collection": "gadgets", "fk_field": "w", "op": "sum", "field": "c", "where": {"paid": True, "n": 3}}), True, True),
1010 ("collection: a relation display_field that is a name", "collection",
1011 set_field(1, relation={"collection": "gadgets", "display_field": "full_name"}), True, True),
1012 ("collection: a formula on a computed field", "collection", add_field(name="t", type="computed", formula="qty + 1"), True, True),
1013 ("collection: a pattern that is a regular expression", "collection", set_field(3, validation={"pattern": "^[a-z]+$"}), True, True),
1014 ("collection: an exclusive_min written with an underscore", "collection", set_field(2, validation={"exclusive_min": "1_0"}), False, False),
1015 ("collection: an exclusive_max written with an underscore", "collection", set_field(2, validation={"exclusive_max": "1_000"}), False, False),
1016 ("collection: exclusive bounds written as text", "collection", set_field(2, validation={"exclusive_min": " 0 ", "exclusive_max": "1e3"}), True, True),
1017 # --- package --------------------------------------------------------
1018 ("package: not an object", "package", lambda p: [], False, False),
1019 ("package: no id", "package", drop("id"), False, False),
1020 ("package: an upper-case id", "package", put("id", "Widgets"), False, False),
1021 ("package: no name", "package", drop("name"), False, False),
1022 ("package: a blank name", "package", put("name", " "), False, False),
1023 ("package: no version", "package", drop("version"), False, False),
1024 ("package: a bad version", "package", put("version", "!!"), False, False),
1025 ("package: compatibility not an object", "package", put("compatibility", []), False, False),
1026 ("package: dependencies not a list", "package", put("dependencies", "app-nav"), False, False),
1027 ("package: a bad dependency id", "package", put("dependencies", ["App Nav"]), False, False),
1028 ("package: an object with no path", "package", put("objects", [{"id": "site_x"}]), False, False),
1029 ("package: an object with a bad id", "package", put("objects", [{"id": "site-x", "path": "a.py"}]), False, False),
1030 ("package: an absolute path", "package", put("schemas", [{"collection": "widgets", "path": "/etc/passwd"}]), False, False),
1031 ("package: a path that climbs out", "package", put("seed", [{"collection": "widgets", "path": "../x.tsv"}]), False, False),
1032 ("package: a bad collection name", "package", put("schemas", [{"collection": "a b", "path": "a.json"}]), False, False),
1033 ("package: a permissions entry with no path", "package", put("permissions", [{}]), False, False),
1034 ("package: a migration with a bad id", "package", put("migrations", [{"id": "-x", "path": "a.py"}]), False, False),
1035 ("package: a connector with a bad entry", "package", put("connectors", [{"collection": "widgets", "module": "a.py", "entry": "not valid"}]), False, False),
1036 ("package: a schedule with a bad id", "package", put("schedules", [{"id": "Nightly", "object_id": "x", "schedule": "10 6 * * *"}]), False, False),
1037 ("package: a schedule type weekly", "package", put("schedules", [{"id": "n", "object_id": "x", "schedule": "10 6 * * *", "type": "weekly"}]), False, False),
1038 ("package: a schedule method PATCH", "package", put("schedules", [{"id": "n", "object_id": "x", "schedule": "10 6 * * *", "method": "PATCH"}]), False, False),
1039 ("package: a schedule payload that is a list", "package", put("schedules", [{"id": "n", "object_id": "x", "schedule": "10 6 * * *", "payload": []}]), False, False),
1040 ("package: a cron with three fields", "package", put("schedules", [{"id": "n", "object_id": "x", "schedule": "* * *"}]), False, False),
1041 ("package: a one-time schedule that is not a timestamp", "package", put("schedules", [{"id": "n", "object_id": "x", "type": "onetime", "schedule": "tomorrow"}]), False, False),
1042 ("package: a schedule with no schedule", "package", put("schedules", [{"id": "n", "object_id": "x"}]), False, False),
1043 ("package: a nav path without a slash", "package", put("nav", [{"id": "n", "label": "N", "path": "widgets"}]), False, False),
1044 ("package: a nav path with a space", "package", put("nav", [{"id": "n", "label": "N", "path": "/a b"}]), False, False),
1045 ("package: a nav surface that is not one", "package", put("nav", [{"id": "n", "label": "N", "path": "/n", "surface": "private"}]), False, False),
1046 ("package: a nav order that is a string", "package", put("nav", [{"id": "n", "label": "N", "path": "/n", "order": "5"}]), False, False),
1047 ("package: a nav order that is a bool", "package", put("nav", [{"id": "n", "label": "N", "path": "/n", "order": True}]), False, False),
1048 ("package: a nav entry with no label", "package", put("nav", [{"id": "n", "path": "/n"}]), False, False),
1049 ("package: attention naming neither source", "package", put("attention", [{"id": "a", "label": "A", "path": "/a"}]), False, False),
1050 ("package: attention naming both sources", "package",
1051 put("attention", [{"id": "a", "label": "A", "path": "/a", "object_id": "x", "collection": "widgets", "where": {"status": "x"}}]), False, False),
1052 ("package: a declared count with no where", "package", put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets"}]), False, False),
1053 ("package: where without a collection", "package", put("attention", [{"id": "a", "label": "A", "path": "/a", "object_id": "x", "where": {"status": "x"}}]), False, False),
1054 ("package: detail without a collection", "package",
1055 put("attention", [{"id": "a", "label": "A", "path": "/a", "object_id": "x", "detail": {"op": "count", "text": "t"}}]), False, False),
1056 ("package: reads on a declared count", "package",
1057 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "x"}, "reads": ["widgets"]}]), False, False),
1058 ("package: a bad attention severity", "package", put("attention", [{"id": "a", "label": "A", "path": "/a", "object_id": "x", "severity": "high"}]), False, False),
1059 ("package: attention reads not a list", "package", put("attention", [{"id": "a", "label": "A", "path": "/a", "object_id": "x", "reads": "orders"}]), False, False),
1060 ("package: a bare list in where", "package",
1061 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": ["a", "b"]}}]), False, False),
1062 ("package: an unknown op in where", "package",
1063 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": {"op": "like", "value": "a"}}}]), False, False),
1064 ("package: a condition with an extra key", "package",
1065 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": {"op": "eq", "value": "a", "x": 1}}}]), False, False),
1066 ("package: older_than_days that is negative", "package",
1067 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "a", "d": {"op": "older_than_days", "value": -1}}}]), False, False),
1068 ("package: older_than_days setting with no default", "package",
1069 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "a", "d": {"op": "older_than_days", "value": {"setting": "a.b"}}}}]), False, False),
1070 ("package: a detail part with an unknown key", "package",
1071 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "a"}, "detail": {"op": "count", "text": "t", "x": 1}}]), False, False),
1072 ("package: a count detail with a field", "package",
1073 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "a"}, "detail": {"op": "count", "text": "t", "field": "qty"}}]), False, False),
1074 ("package: a sum detail with no field", "package",
1075 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "a"}, "detail": {"op": "sum", "text": "t"}}]), False, False),
1076 ("package: a detail text with another placeholder", "package",
1077 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "a"}, "detail": {"op": "count", "text": "{n} old"}}]), False, False),
1078 ("package: a cents format on a count", "package",
1079 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "a"}, "detail": {"op": "count", "text": "t", "format": "cents"}}]), False, False),
1080 ("package: show_zero not a bool", "package",
1081 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "a"}, "detail": {"op": "count", "text": "t", "show_zero": "yes"}}]), False, False),
1082 # Once SCHEMA_STRICTER: object_packages._normalize_manifest now refuses a
1083 # section or entry key DRON does not define (a typo such as "schedule"
1084 # used to ship nothing and install cleanly).
1085 ("package: a section nobody reads", "package", put("widgets", []), False, False),
1086 ("package: an unknown key in an entry", "package", put("objects", [{"id": "site_x", "path": "a.py", "kind": "page"}]), False, False),
1087 # Once SCHEMA_STRICTER: a value of the wrong type is refused, not coerced.
1088 ("package: nav_optional given as a string", "package", put("nav_optional", "yes"), False, False),
1089 ("package: a description that is a number", "package", put("description", 5), False, False),
1090 # Once SCHEMA_STRICTER: refused with DRON's spelling rather than lower-cased.
1091 ("package: a schedule type in capitals", "package",
1092 put("schedules", [{"id": "n", "object_id": "x", "schedule": "10 6 * * *", "type": "CRON"}]), False, False),
1093 ("package: a nav surface in capitals", "package",
1094 put("nav", [{"id": "n", "label": "N", "path": "/n", "surface": "Public"}]), False, False),
1095 # --- permissions ------------------------------------------------------
1096 ("permissions: not an object", "permissions", lambda p: 5, False, False),
1097 ("permissions: no rules key", "permissions", lambda p: {}, False, False),
1098 ("permissions: rules not a list", "permissions", put("rules", {}), False, False),
1099 ("permissions: retracted not a list", "permissions", put("retracted", {}), False, False),
1100 ("permissions: a rule that is not an object", "permissions", put("rules", ["allow"]), False, False),
1101 ("permissions: no effect", "permissions", drop("rules.0.effect"), False, False),
1102 ("permissions: effect permit", "permissions", put("rules.0.effect", "permit"), False, False),
1103 ("permissions: no principal", "permissions", drop("rules.0.principal"), False, False),
1104 ("permissions: no actions", "permissions", drop("rules.0.actions"), False, False),
1105 ("permissions: empty actions", "permissions", put("rules.0.actions", []), False, False),
1106 ("permissions: actions a string", "permissions", put("rules.0.actions", "read"), False, False),
1107 ("permissions: owner_fallback as an allow", "permissions", put("rules.0.principal", "owner_fallback"), False, False),
1108 ("permissions: row_filter a list", "permissions", put("rules.0.row_filter", []), False, False),
1109 ("permissions: fields a string", "permissions", put("rules.0.fields", "id"), False, False),
1110 ("permissions: denied_fields with a blank", "permissions", put("rules.0.denied_fields", [""]), False, False),
1111 ("permissions: reason a list", "permissions", put("rules.0.reason", ["x"]), False, False),
1112 ("permissions: an empty principal", "permissions", put("rules.0.principal", ""), False, False),
1113 # Once SCHEMA_STRICTER: the package loader now holds every rule to DRON
1114 # (object_permissions.check_rule_declaration), so a misspelt row_filter, an
1115 # unknown action, principal, operator or $-variable, a boolean filter value
1116 # and a capitalised effect refuse the install instead of loading as a rule
1117 # that does something other than what it says.
1118 ("permissions: a rule key nobody reads", "permissions", put("rules.0.because", "x"), False, False),
1119 ("permissions: an action that is not one", "permissions", put("rules.0.actions", ["frobnicate"]), False, False),
1120 ("permissions: a principal that is not one", "permissions", put("rules.0.principal", "admin"), False, False),
1121 ("permissions: an effect in capitals", "permissions", put("rules.0.effect", "ALLOW"), False, False),
1122 ("permissions: a boolean filter value", "permissions", put("rules.0.row_filter", {"is_public": True}), False, False),
1123 ("permissions: a null equality", "permissions", put("rules.0.row_filter", {"owner_id": {"op": "eq", "value": None}}), False, False),
1124 ("permissions: a condition with no value", "permissions", put("rules.0.row_filter", {"owner_id": {"op": "eq"}}), False, False),
1125 ("permissions: an operator that is not one", "permissions", put("rules.0.row_filter", {"a": {"op": "like", "value": "x"}}), False, False),
1126 ("permissions: a variable that is not one", "permissions", put("rules.0.row_filter", {"owner_id": "$userid"}), False, False),
1127 ("permissions: an expiry that is not a date", "permissions", put("rules.0.expires_at", "tomorrow"), False, False),
1128 ("permissions: a numeric collection", "permissions", put("rules.0.collection", 5), False, False),
1129 ("permissions: a bare list file", "permissions", lambda p: p["rules"], False, False),
1130]
1131
1132# Cases where the loader accepts and the schema refuses (SCHEMA_STRICTER) and
1133# where the loader refuses and the schema cannot (LOADER_ONLY). Each carries
1134# which side is right and why, and what to do about it. SCHEMA_STRICTER is
1135# empty: every class of declaration the schema refuses, the package loader
1136# refuses at install (unknown keys, unknown names, coercion, synonyms, and the
1137# value checks: a bound that is not a number, an access level, a relation with
1138# no collection, a formula or rollup that cannot apply, a hook name, a list
1139# mode). Each was moved to AGREE as it was fixed, with a note saying so. A new
1140# disagreement found before it is fixed goes here, with why; the test that
1141# reads the list is skipped while it is empty.
1142SCHEMA_STRICTER = []
1143
1144LOADER_ONLY = [
1145 ("collection: required_when naming a field the schema lacks", "collection", set_field(3, validation={"required_when": {"nope": "x"}}),
1146 "needs the whole field list"),
1147 ("collection: required_when naming the field itself", "collection", set_field(3, validation={"required_when": {"note": "x"}}),
1148 "compares a key with the field it sits on"),
1149 ("collection: locked_when fields naming a field the schema lacks", "collection",
1150 put("locked_when", [{"when": {"status": "posted"}, "fields": ["nope"]}]), "needs the whole field list"),
1151 ("collection: locked_when fields naming id", "collection",
1152 put("locked_when", [{"when": {"status": "posted"}, "fields": ["id"]}]), "id is a field name the schema allows"),
1153 ("collection: bounds that leave no value", "collection", set_field(2, validation={"exclusive_min": 5, "max": 5}),
1154 "arithmetic across keys"),
1155 ("collection: unique naming a field twice", "collection", put("unique", [{"fields": ["note"], "scope": ["note"]}]),
1156 "duplicates across two arrays"),
1157 ("collection: unique on a computed field", "collection",
1158 lambda p: (p["fields"].append({"name": "c", "type": "computed"}), p.update(unique=[{"fields": ["c"]}]))[1],
1159 "needs the field list"),
1160 ("collection: unique on an extra-stored field", "collection",
1161 lambda p: (p["fields"].append({"name": "x", "store": "extra"}), p.update(unique=[{"fields": ["x"]}]))[1],
1162 "needs the field list"),
1163 ("collection: two locked checks with one name", "collection",
1164 put("locked_checks", [{"object": "hook_x"}, {"object": "hook_x"}]), "duplicates across entries"),
1165 ("package: a manifest id that is not its directory's", "package", lambda p: p, "needs the directory name"),
1166 ("package: a duplicate nav id", "package",
1167 put("nav", [{"id": "n", "label": "N", "path": "/n"}, {"id": "n", "label": "M", "path": "/m"}]), "duplicates across entries"),
1168 ("package: a duplicate schedule id", "package",
1169 put("schedules", [{"id": "n", "object_id": "x", "schedule": "10 6 * * *"}, {"id": "n", "object_id": "x", "schedule": "10 6 * * *"}]),
1170 "duplicates across entries"),
1171 ("package: a duplicate attention id", "package",
1172 put("attention", [{"id": "a", "label": "A", "path": "/a", "object_id": "x"}, {"id": "a", "label": "A", "path": "/a", "object_id": "x"}]),
1173 "duplicates across entries"),
1174 ("package: a declared count with no literal equality", "package",
1175 put("attention", [{"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"qty": {"op": "gt", "value": 1}}}]),
1176 "'at least one property is a literal' is not expressible over an object's values"),
1177]
1178
1179
1180def _loader_for(kind):
1181 return KINDS[kind][0]
1182
1183
1184def _case_params(cases):
1185 return [pytest.param(*case, id=case[0]) for case in cases]
1186
1187
1188def _payload(kind, change):
1189 return edit(kind, change)
1190
1191
1192# The manifest's `dron` key (docs/dron.md, "Versioning"). The schema can say
1193# what a version looks like; which versions this server reads is the loader's
1194# alone, so a well-formed version it cannot read is LOADER_ONLY.
1195AGREE += [
1196 ("package: dron naming the version the server reads", "package", put("dron", object_packages.DRON_VERSION), True, True),
1197 ("package: dron naming an earlier minor", "package", put("dron", "0.1"), True, True),
1198 ("package: dron as a number", "package", put("dron", 0.2), False, False),
1199 ("package: dron with a patch part", "package", put("dron", "0.2.0"), False, False),
1200 ("package: dron with a leading v", "package", put("dron", "v0.2"), False, False),
1201 ("package: dron with a leading zero", "package", put("dron", "0.02"), False, False),
1202 ("package: dron blank", "package", put("dron", ""), False, False),
1203]
1204LOADER_ONLY += [
1205 ("package: dron naming a later minor", "package", put("dron", "0.3"),
1206 "which versions this server reads is the engine's, not the schema's"),
1207 ("package: dron naming another major", "package", put("dron", "1.0"),
1208 "which versions this server reads is the engine's, not the schema's"),
1209]
1210
1211
1212# Round 4: manifest values the loader used to read as absent or as a default.
1213_MANIFEST_NULLS = ("attention", "nav", "objects", "schemas", "seed", "permissions", "schedules",
1214 "connectors", "dependencies", "migrations", "description", "compatibility")
1215_ATT = {"id": "a", "label": "A", "path": "/a", "collection": "widgets", "where": {"status": "draft"}}
1216
1217
1218def _entry_with(section, base_entry, **keys):
1219 return put(section, [{**base_entry, **keys}])
1220
1221
1222AGREE += [(f"package: a null {name}", "package", put(name, None), False, False) for name in _MANIFEST_NULLS]
1223AGREE += [
1224 ("package: a compatibility value that is not text", "package", put("compatibility", {"object_server": 1}), False, False),
1225 ("package: a schedule description that is not text", "package",
1226 _entry_with("schedules", {"id": "n", "object_id": "x", "schedule": "10 6 * * *"}, description=5), False, False),
1227 ("package: a connector entry that is blank", "package",
1228 _entry_with("connectors", {"collection": "widgets", "module": "a.py"}, entry=""), False, False),
1229 ("package: a connector entry that is not text", "package",
1230 _entry_with("connectors", {"collection": "widgets", "module": "a.py"}, entry=3), False, False),
1231 ("package: a nav blurb that is not text", "package", _entry_with("nav", {"id": "n", "label": "N", "path": "/n"}, blurb=5), False, False),
1232 ("package: a nav group that is null", "package", _entry_with("nav", {"id": "n", "label": "N", "path": "/n"}, group=None), False, False),
1233 ("package: a nav order that is null", "package", _entry_with("nav", {"id": "n", "label": "N", "path": "/n"}, order=None), False, False),
1234 ("package: a nav order that is blank", "package", _entry_with("nav", {"id": "n", "label": "N", "path": "/n"}, order=""), False, False),
1235 ("package: a nav surface that is null", "package", _entry_with("nav", {"id": "n", "label": "N", "path": "/n"}, surface=None), False, False),
1236 ("package: a nav surface that is blank", "package", _entry_with("nav", {"id": "n", "label": "N", "path": "/n"}, surface=""), False, False),
1237 ("package: an attention group that is not text", "package", _entry_with("attention", _ATT, group=3), False, False),
1238 ("package: an attention nav_id that is blank", "package", _entry_with("attention", _ATT, nav_id=""), False, False),
1239 ("package: an attention nav_id that is null", "package", _entry_with("attention", _ATT, nav_id=None), False, False),
1240 ("package: an attention severity that is null", "package", _entry_with("attention", _ATT, severity=None), False, False),
1241 ("package: an attention severity that is blank", "package", _entry_with("attention", _ATT, severity=""), False, False),
1242 ("package: an attention severity in another case", "package", _entry_with("attention", _ATT, severity="Urgent"), False, False),
1243 ("package: an attention severity that is not one", "package", _entry_with("attention", _ATT, severity="dire"), False, False),
1244 ("package: attention reads that is blank", "package",
1245 put("attention", [{"id": "p", "label": "P", "path": "/p", "object_id": "x", "reads": ""}]), False, False),
1246 ("package: attention reads that is null", "package",
1247 put("attention", [{"id": "p", "label": "P", "path": "/p", "object_id": "x", "reads": None}]), False, False),
1248 ("package: attention reads that is empty", "package",
1249 put("attention", [{"id": "p", "label": "P", "path": "/p", "object_id": "x", "reads": []}]), True, True),
1250 ("package: attention detail that is null", "package", _entry_with("attention", _ATT, detail=None), False, False),
1251 ("package: attention detail that is empty", "package", _entry_with("attention", _ATT, detail=[]), False, False),
1252 ("package: attention detail that is an empty object", "package", _entry_with("attention", _ATT, detail={}), False, False),
1253 ("package: attention detail that is blank", "package", _entry_with("attention", _ATT, detail=""), False, False),
1254 ("package: a detail format that is null", "package",
1255 _entry_with("attention", _ATT, detail=[{"op": "count", "text": "n", "format": None}]), False, False),
1256 ("package: a detail format that is 0", "package",
1257 _entry_with("attention", _ATT, detail=[{"op": "count", "text": "n", "format": 0}]), False, False),
1258 ("package: a detail format that is blank", "package",
1259 _entry_with("attention", _ATT, detail=[{"op": "count", "text": "n", "format": ""}]), False, False),
1260 ("package: a detail op that is not text", "package",
1261 _entry_with("attention", _ATT, detail=[{"op": 0, "text": "n"}]), False, False),
1262 ("package: a where operator that is null", "package",
1263 _entry_with("attention", _ATT, where={"status": {"op": None, "value": "x"}}), False, False),
1264 ("package: a where operator that is blank", "package",
1265 _entry_with("attention", _ATT, where={"status": {"op": "", "value": "x"}}), False, False),
1266 ("package: a where operator that is a number", "package",
1267 _entry_with("attention", _ATT, where={"status": {"op": 0, "value": "x"}}), False, False),
1268 ("package: a where condition with no operator", "package",
1269 _entry_with("attention", _ATT, where={"status": {"value": "x"}}), False, False),
1270 ("package: a where operator in capitals", "package",
1271 _entry_with("attention", _ATT, where={"status": "draft", "n": [{"op": "GT", "value": "1"}]}), False, False),
1272 ("package: a detail where operator that is a list", "package",
1273 _entry_with("attention", _ATT, detail=[{"op": "count", "text": "n", "where": {"o": {"op": [], "value": "x"}}}]), False, False),
1274]
1275
1276
1277@pytest.mark.parametrize("label,kind,change,loader_accepts,schema_accepts", _case_params(AGREE))
1278def test_the_loader_and_the_schema_agree(label, kind, change, loader_accepts, schema_accepts):
1279 payload = _payload(kind, change)
1280 loader, schema_file = KINDS[kind]
1281 refusal = loader(copy.deepcopy(payload))
1282 errors = schema_errors(payload, schema_file)
1283 assert (refusal is None) is loader_accepts, f"loader: {refusal!r}"
1284 assert (not errors) is schema_accepts, f"schema errors: {errors}"
1285
1286
1287@pytest.mark.parametrize("label,kind,change,why", _case_params(SCHEMA_STRICTER))
1288def test_where_the_loader_is_laxer_than_the_schema_the_schema_is_right(label, kind, change, why):
1289 payload = _payload(kind, change)
1290 loader, schema_file = KINDS[kind]
1291 assert loader(copy.deepcopy(payload)) is None, "the loader now refuses this: move it to AGREE"
1292 assert schema_errors(payload, schema_file), "the schema now accepts this: it is no longer stricter"
1293
1294
1295@pytest.mark.parametrize("label,kind,change,why", _case_params(LOADER_ONLY))
1296def test_what_only_the_loader_can_see_is_listed(label, kind, change, why):
1297 payload = _payload(kind, change)
1298 loader, schema_file = KINDS[kind]
1299 if label == "package: a manifest id that is not its directory's":
1300 assert package_loader_refuses(payload, package_id="other") is not None
1301 assert not schema_errors(payload, schema_file)
1302 return
1303 assert loader(copy.deepcopy(payload)) is not None, "the loader accepts this now: move it to AGREE"
1304 assert not schema_errors(payload, schema_file), "the schema refuses this now: move it to AGREE"
1305
1306
1307# --- the deployment policy document (dron/dron-policy.schema.json) ------------
1308#
1309# The policy a box keeps at data/permissions/policy.json. The engine's own
1310# reading (object_permissions.policy_from_dict) is lenient on purpose: a box
1311# must not stop serving over its own file. The schema is the intended
1312# definition, so every case below is either one both sides refuse or a place
1313# where the engine is laxer, written down with which side is right.
1314
1315def policy_engine_refuses(payload) -> str | None:
1316 try:
1317 object_permissions.policy_from_dict(copy.deepcopy(payload))
1318 except ValueError as exc:
1319 return str(exc)
1320 return None
1321
1322
1323_RULE = {"effect": "allow", "principal": "public", "actions": ["read"], "collection": "widgets"}
1324
1325
1326def _policy(**keys):
1327 return {"access_mode": "role_based", **keys}
1328
1329
1330def _rule(**keys):
1331 return _policy(rules=[{**_RULE, **keys}])
1332
1333
1334def test_the_built_in_default_policy_validates():
1335 default = object_permissions.policy_to_dict(object_permission_store.DEFAULT_POLICY)
1336 assert not schema_errors(default, POLICY_SCHEMA)
1337 assert policy_engine_refuses(default) is None
1338
1339
1340def test_the_starter_policy_validates_and_the_engine_reads_it():
1341 starter = object_permission_store.starter_policy_payload()
1342 assert not schema_errors(starter, POLICY_SCHEMA)
1343 assert policy_engine_refuses(starter) is None
1344 assert starter["roles"], "the starter policy lists the role presets"
1345
1346
1347def test_a_policy_the_engine_writes_back_validates():
1348 """policy_to_dict adds the defaults a hand-written file leaves out."""
1349 starter = object_permission_store.starter_policy_payload()
1350 again = object_permissions.policy_to_dict(object_permissions.policy_from_dict(starter))
1351 assert not schema_errors(again, POLICY_SCHEMA)
1352
1353
1354def _json_blocks(path: Path):
1355 text = path.read_text(encoding="utf-8")
1356 for block in re.findall(r"```json\n(.*?)\n```", text, flags=re.S):
1357 try:
1358 yield json.loads(block)
1359 except ValueError:
1360 continue # an excerpt with "..." in it
1361
1362
1363def _documented_policies():
1364 for name in ("permissions-model.md", "http-api-contract.md"):
1365 for document in _json_blocks(ROOT / "docs" / name):
1366 if not isinstance(document, dict):
1367 continue
1368 policy = document.get("policy", document)
1369 # a status report also says access_mode; it is not a policy
1370 if isinstance(policy, dict) and "access_mode" in policy and "policy_file_exists" not in policy:
1371 yield pytest.param(policy, id=f"{name}:{policy.get('access_mode')}:{len(str(policy))}")
1372
1373
1374@pytest.mark.parametrize("policy", list(_documented_policies()))
1375def test_every_policy_the_docs_print_validates(policy):
1376 assert not schema_errors(policy, POLICY_SCHEMA)
1377 assert policy_engine_refuses(policy) is None
1378 assert object_permissions.policy_declaration_problems(policy) == []
1379
1380
1381def test_the_docs_print_policies_for_this_test_to_read():
1382 assert len(list(_documented_policies())) >= 4
1383
1384
1385def test_the_policy_schema_reuses_the_rule_definition_packages_are_held_to():
1386 document = VALIDATOR.document(POLICY_SCHEMA)
1387 assert document["properties"]["rules"]["items"] == {"$ref": "dron-permissions.schema.json#/$defs/rule"}
1388 assert "rule" in VALIDATOR.document(PERMISSIONS_SCHEMA)["$defs"]
1389
1390
1391# (label, policy) that the engine and the schema both refuse.
1392POLICY_BOTH_REFUSE = [
1393 ("not an object", []),
1394 ("an access mode that does not exist", _policy(access_mode="open")),
1395 ("an access mode in capitals", _policy(access_mode="PUBLIC")),
1396 ("an access mode that is a number", _policy(access_mode=5)),
1397 ("roles as a list", _policy(roles=[])),
1398 ("a role whose metadata is text", _policy(roles={"a": "x"})),
1399 ("a role with a blank name", _policy(roles={"": {}})),
1400 ("user_roles as a list", _policy(user_roles=[])),
1401 ("a user's roles as text", _policy(user_roles={"u": "admin"})),
1402 ("a user's role that is blank", _policy(user_roles={"u": [""]})),
1403 ("admin_roles null", _policy(admin_roles=None)),
1404 ("admin_roles as text", _policy(admin_roles="admin")),
1405 ("rules as an object", _policy(rules={})),
1406 ("rules null", _policy(rules=None)),
1407 ("a rule that is text", _policy(rules=["x"])),
1408 ("a rule with an effect that is not one", _rule(effect="permit")),
1409 ("a rule with no actions", _rule(actions=[])),
1410 ("a row filter that is a list", _rule(row_filter=[])),
1411 ("owner_fallback on an allow", _rule(principal="owner_fallback")),
1412 ("on_behalf for everyone signed in", _rule(principal="registered", actions=["create"], on_behalf=True)),
1413 ("on_behalf as text", _rule(on_behalf="yes")),
1414]
1415
1416# (label, policy) that both accept, so the schema is not simply refusing everything.
1417POLICY_BOTH_ACCEPT = [
1418 ("nothing at all", {}),
1419 ("a schema pointer", {"$schema": "../../dron/dron-policy.schema.json"}),
1420 ("every access mode", _policy(access_mode="private")),
1421 ("nobody bypasses the rules", _policy(admin_roles=[])),
1422 ("a rule with a package tag", _rule(package="app-widgets")),
1423 ("a rule naming no resource", {"rules": [{"effect": "allow", "principal": "public", "actions": ["read"]}]}),
1424 ("roles and users", _policy(roles={"sales": {"label": "Sales"}}, user_roles={"7": ["sales"]},
1425 admin_roles=["admin"])),
1426 ("an on_behalf staff grant", _rule(principal="role:clerk", actions=["create"], on_behalf=True)),
1427]
1428
1429# (label, policy, which side is right and why) where the engine's READING
1430# accepts what the schema refuses. The schema is right in every case, and
1431# since the save check every one is refused when an operator SAVES it
1432# (object_permissions.check_policy_declaration, through PUT /permissions/
1433# policy): a rule key spelt wrong used to be dropped, so a misspelt
1434# row_filter turned an allow into one covering EVERY row, and a deny with an
1435# unknown principal, a $-variable that is not one or an expiry that is not a
1436# date was silently never applied. They stay on this list, not the both-
1437# refuse one, because READING a stored file stays lenient on purpose: a box
1438# never stops serving, or changes a decision, over its own file. It reports
1439# each instead (object_permissions.stored_policy_findings). The two tests
1440# below the list pin both halves.
1441POLICY_ENGINE_LAXER = [
1442 ("an access mode left null", _policy(access_mode=None), "schema right, harmless: read as role_based, so say role_based"),
1443 ("an access mode left blank", _policy(access_mode=""), "schema right, harmless: read as role_based"),
1444 ("a user's role written as a number", _policy(user_roles={"u": [1]}), "schema right: the engine reads 1 as '1'"),
1445 ("a user's role listed twice", _policy(user_roles={"u": ["a", "a"]}), "schema right, harmless: the engine keeps one"),
1446 ("an effect in capitals", _rule(effect="ALLOW"), "schema right: DRON spells it 'allow'; the engine lowercases"),
1447 ("a misspelt rule key (row_filter)", _rule(rowfilter={"owner_id": "$user_id"}),
1448 "schema right and UNSAFE in the engine: the filter is dropped, so an allow covers every row"),
1449 ("an action that is not one", _rule(actions=["reed"]), "schema right, harmless: it matches nothing"),
1450 ("a principal that is not one", _rule(principal="admin"),
1451 "schema right: matches nobody; on a deny rule the deny is silently never applied"),
1452 ("a $-variable that is not one", _rule(row_filter={"o": "$userid"}),
1453 "schema right: on an allow it hides every row, on a deny it hides none"),
1454 ("a row-filter operator that is not one", _rule(row_filter={"o": {"op": "like", "value": "x"}}),
1455 "schema right: the engine raises at the first request that reads the rule"),
1456 ("a collection written as a number", _rule(collection=5), "schema right: the engine reads 5 as '5'"),
1457 ("an expiry that is not a date", _rule(expires_at="tomorrow"),
1458 "schema right: the engine never applies the rule, so a deny with a bad expiry is silently off"),
1459 ("an unknown top-level key", _policy(rulez=[]), "schema right: a misspelt rules is a policy with no rules"),
1460]
1461
1462
1463@pytest.mark.parametrize("label,policy", POLICY_BOTH_REFUSE, ids=[c[0] for c in POLICY_BOTH_REFUSE])
1464def test_a_bad_policy_is_refused_by_the_engine_and_by_the_schema(label, policy):
1465 assert policy_engine_refuses(policy) is not None, "the engine accepts this now: move it to the lenient list"
1466 assert schema_errors(policy, POLICY_SCHEMA)
1467 # A save runs the DRON check and then the engine's reading, so both refuse it there too.
1468
1469
1470@pytest.mark.parametrize("label,policy", POLICY_BOTH_ACCEPT, ids=[c[0] for c in POLICY_BOTH_ACCEPT])
1471def test_a_good_policy_is_accepted_by_the_engine_and_by_the_schema(label, policy):
1472 assert policy_engine_refuses(policy) is None
1473 assert not schema_errors(policy, POLICY_SCHEMA)
1474
1475
1476@pytest.mark.parametrize("label,policy,why", POLICY_ENGINE_LAXER, ids=[c[0] for c in POLICY_ENGINE_LAXER])
1477def test_where_the_engine_reads_a_stored_policy_more_loosely_than_the_schema_the_schema_is_right(label, policy, why):
1478 assert schema_errors(policy, POLICY_SCHEMA), "the schema accepts this now: it is no longer stricter"
1479 if label == "a row-filter operator that is not one":
1480 assert policy_engine_refuses(policy) is None # raises later, at a request, not at load
1481 else:
1482 assert policy_engine_refuses(policy) is None, "the engine refuses this now: move it to the list both refuse"
1483
1484
1485@pytest.mark.parametrize("label,policy,why", POLICY_ENGINE_LAXER, ids=[c[0] for c in POLICY_ENGINE_LAXER])
1486def test_what_the_engine_reads_loosely_is_refused_at_save_and_reported_at_read(label, policy, why):
1487 """The save check refuses all of them (and only what the schema refuses:
1488 see the both-accept test below); a stored file holding one is read as
1489 before and the mistake is reported."""
1490 assert object_permissions.policy_declaration_problems(copy.deepcopy(policy))
1491 assert object_permissions.stored_policy_findings(copy.deepcopy(policy))
1492
1493
1494@pytest.mark.parametrize("label,policy", POLICY_BOTH_ACCEPT, ids=[c[0] for c in POLICY_BOTH_ACCEPT])
1495def test_a_policy_the_schema_accepts_passes_the_save_check(label, policy):
1496 assert object_permissions.policy_declaration_problems(copy.deepcopy(policy)) == []
1497 assert object_permissions.stored_policy_findings(copy.deepcopy(policy)) == []
1498
1499
1500def test_a_stored_policy_with_a_misspelt_rule_key_is_still_read_as_it_always_was():
1501 """Pinned so nobody tightens the stored-policy reading by accident: a
1502 save refuses this, but a box loads its own file as it always did (and
1503 reports the mistake; tests/test_policy_strict_save.py)."""
1504 policy = object_permissions.policy_from_dict(_rule(rowfilter={"owner_id": "$user_id"}))
1505 assert policy.rules[0].row_filter == {}
1506
1507
1508# --- the exchange envelope (dron/dron-document.schema.json) ------------------
1509#
1510# What boxes send each other (docs/box-to-box-exchange.md). The engine's
1511# definition is object_exchange.validate_envelope; the schema says the same
1512# shape in a form another engine can read. Checks that need computation are
1513# the engine's alone and listed below: the schema must not pretend to them.
1514
1515def envelope_engine_refuses(envelope) -> list[str] | None:
1516 try:
1517 object_exchange.validate_envelope(copy.deepcopy(envelope))
1518 except object_exchange.EnvelopeError as exc:
1519 return list(exc.problems)
1520 return None
1521
1522
1523def _line(**keys):
1524 return {"line_id": "1", "description": "Widget", "quantity": "12", "unit_code": "H87",
1525 "unit_price_minor": 1850, "line_extension_minor": 22200, **keys}
1526
1527
1528_PRICED_BODY = {
1529 "number": "INV-77", "issue_date": "2026-12-03", "due_date": "2027-01-02", "currency": "EUR",
1530 "lines": [_line(tax_rate_bps=0)],
1531 "totals": {"line_extension_minor": 22200, "tax_minor": 0, "payable_minor": 22200},
1532}
1533_REMITTANCE_BODY = {"currency": "EUR", "paid_minor": 100, "paid_on": "2026-12-05",
1534 "payment_reference": "RF18539007547034",
1535 "settles": [{"document_id": "inv-1", "amount_minor": 100}]}
1536_RECEIPT_BODY = {"received_on": "2026-12-05",
1537 "lines": [{"line_id": "1", "description": "Widget", "quantity_received": "3",
1538 "quantity_rejected": "1", "unit_code": "H87"}]}
1539_REFUSAL_BODY = {"document_id": "doc-9", "envelope_sha256": "a" * 64, "code": "not_ours", "reason": "Not ours."}
1540BODIES = {
1541 "purchase_order": _PRICED_BODY,
1542 "order_confirmation": {**_PRICED_BODY, "response": "amended",
1543 "lines": [_line(ref_line_id="1", line_status="changed")]},
1544 "invoice": _PRICED_BODY,
1545 "credit_note": _PRICED_BODY,
1546 "remittance": _REMITTANCE_BODY,
1547 "receipt": _RECEIPT_BODY,
1548 "connection_request": {"note": "Please connect."},
1549 "connection_accept": {},
1550 "connection_end": {"reason": "Ending the account."},
1551 "document_refusal": _REFUSAL_BODY,
1552}
1553
1554
1555def _envelope(doc_type="invoice", body=None, **keys):
1556 envelope = {
1557 "dron_document": "0.1", "id": "doc-1", "type": doc_type, "sender": "supplier.example",
1558 "recipient": "shop.example", "created_at": "2026-12-03T09:30:00Z",
1559 "refs": [{"id": "doc-91ab", "type": "purchase_order"}],
1560 "body": copy.deepcopy(BODIES[doc_type] if body is None else body),
1561 }
1562 envelope.update(keys)
1563 return envelope
1564
1565
1566def _body_with(doc_type="invoice", **keys):
1567 return _envelope(doc_type, {**copy.deepcopy(BODIES[doc_type]), **keys})
1568
1569
1570def _without(doc_type, *names):
1571 return _envelope(doc_type, {k: v for k, v in copy.deepcopy(BODIES[doc_type]).items() if k not in names})
1572
1573
1574def test_every_document_type_the_engine_reads_has_a_body_the_schema_reads():
1575 types = object_exchange.DOCUMENT_TYPES + object_exchange.CONTROL_TYPES
1576 assert set(BODIES) == set(types)
1577 assert set(VALIDATOR.document(DOCUMENT_SCHEMA)["properties"]["type"]["enum"]) == set(types)
1578 assert object_exchange.DRON_DOCUMENT_VERSION == VALIDATOR.document(DOCUMENT_SCHEMA)["properties"]["dron_document"]["const"]
1579
1580
1581@pytest.mark.parametrize("doc_type", sorted(BODIES))
1582def test_an_envelope_of_each_type_is_accepted_by_the_engine_and_the_schema(doc_type):
1583 envelope = _envelope(doc_type)
1584 assert envelope_engine_refuses(envelope) is None
1585 assert not schema_errors(envelope, DOCUMENT_SCHEMA)
1586 bare = {k: v for k, v in envelope.items() if k != "refs"}
1587 assert envelope_engine_refuses(bare) is None and not schema_errors(bare, DOCUMENT_SCHEMA)
1588
1589
1590def _documented_envelopes():
1591 for document in _json_blocks(ROOT / "docs" / "box-to-box-exchange.md"):
1592 if isinstance(document, dict) and "dron_document" in document:
1593 yield document
1594
1595
1596def test_the_envelope_the_docs_print_for_the_built_format_validates():
1597 built = [d for d in _documented_envelopes() if "sender" in d]
1598 assert len(built) == 1
1599 assert envelope_engine_refuses(built[0]) is None
1600 assert not schema_errors(built[0], DOCUMENT_SCHEMA)
1601
1602
1603def test_the_proposal_the_docs_print_as_illustrative_is_refused_by_both():
1604 """Section 3 of the design page shows an early proposal (type "order",
1605 from, to, issued_at), marked illustrative; it is not the built format."""
1606 proposal = [d for d in _documented_envelopes() if "sender" not in d]
1607 assert len(proposal) == 1
1608 assert envelope_engine_refuses(proposal[0])
1609 assert schema_errors(proposal[0], DOCUMENT_SCHEMA)
1610
1611
1612def test_the_documented_line_and_totals_keys_are_the_ones_the_schema_names():
1613 document = VALIDATOR.document(DOCUMENT_SCHEMA)["$defs"]
1614 assert {"line_id", "description", "quantity", "unit_code", "unit_price_minor", "line_extension_minor",
1615 "tax_rate_bps", "ref_line_id", "line_status"} == set(document["line"]["properties"])
1616 assert {"line_extension_minor", "charge_minor", "tax_minor", "payable_minor"} == set(
1617 document["pricedBody"]["properties"]["totals"]["properties"])
1618
1619
1620ENVELOPE_BOTH_REFUSE = [
1621 ("not an object", []),
1622 ("another dron_document version", _envelope(dron_document="0.2")),
1623 ("no dron_document", {k: v for k, v in _envelope().items() if k != "dron_document"}),
1624 ("an empty id", _envelope(id="")),
1625 ("an id of 129 characters", _envelope(id="a" * 129)),
1626 ("an id with a space", _envelope(id="doc 1")),
1627 ("a type that is not one", _envelope(type="order")),
1628 ("a sender in capitals", _envelope(sender="Supplier.example")),
1629 ("a sender that is an IP address", _envelope(sender="10.0.0.1")),
1630 ("a sender that is a bare host", _envelope(sender="localhost")),
1631 ("a recipient with an empty label", _envelope(recipient="a..example")),
1632 ("a created_at that is a date", _envelope(created_at="2026-12-03")),
1633 ("a created_at with an offset", _envelope(created_at="2026-12-03T09:30:00+00:00")),
1634 ("a created_at in month 13", _envelope(created_at="2026-13-03T09:30:00Z")),
1635 ("refs as an object", _envelope(refs={})),
1636 ("a ref to a control message", _envelope(refs=[{"id": "x", "type": "connection_end"}])),
1637 ("a ref with no id", _envelope(refs=[{"type": "invoice"}])),
1638 ("a body that is a list", _envelope(body=[])),
1639 ("no body", {k: v for k, v in _envelope().items() if k != "body"}),
1640 ("a key the envelope does not define", _envelope(signature="x")),
1641 ("an invoice with no number", _without("invoice", "number")),
1642 ("an invoice with a blank number", _body_with(number=" ")),
1643 ("an issue date that is not YYYY-MM-DD", _body_with(issue_date="12/03/2026")),
1644 ("a due date that is not YYYY-MM-DD", _body_with(due_date="soon")),
1645 ("a currency that is not three capitals", _body_with(currency="euro")),
1646 ("no lines", _body_with(lines=[])),
1647 ("a line that is text", _body_with(lines=["x"])),
1648 ("a line with an empty id", _body_with(lines=[_line(line_id="")])),
1649 ("a line with a blank description", _body_with(lines=[_line(description=" ")])),
1650 ("a quantity that is a number", _body_with(lines=[_line(quantity=12)])),
1651 ("a quantity that is NaN", _body_with(lines=[_line(quantity="NaN")])),
1652 ("a quantity that is blank", _body_with(lines=[_line(quantity="")])),
1653 ("a unit code in lower case", _body_with(lines=[_line(unit_code="h87")])),
1654 ("a unit code of four characters", _body_with(lines=[_line(unit_code="ABCD")])),
1655 ("a ref_line_id that is empty", _body_with(lines=[_line(ref_line_id="")])),
1656 ("a line_status that is not one", _body_with(lines=[_line(line_status="ok")])),
1657 ("a unit price that is text", _body_with(lines=[_line(unit_price_minor="1850")])),
1658 ("a unit price that is true", _body_with(lines=[_line(unit_price_minor=True)])),
1659 ("no unit price", _body_with(lines=[{k: v for k, v in _line().items() if k != "unit_price_minor"}])),
1660 ("a tax rate that is a fraction", _body_with(lines=[_line(tax_rate_bps=1.5)])),
1661 ("no totals", _without("invoice", "totals")),
1662 ("a total that is text", _body_with(totals={"line_extension_minor": "1", "tax_minor": 0, "payable_minor": 1})),
1663 ("totals missing payable_minor", _body_with(totals={"line_extension_minor": 1, "tax_minor": 0})),
1664 ("a confirmation with no response", _without("order_confirmation", "response")),
1665 ("a confirmation response that is not one", _body_with("order_confirmation", response="maybe")),
1666 ("a remittance with no settles", _body_with("remittance", settles=[])),
1667 ("a settles item with no document id", _body_with("remittance", settles=[{"amount_minor": 100}])),
1668 ("a settled amount that is text", _body_with("remittance", settles=[{"document_id": "i", "amount_minor": "100"}])),
1669 ("a paid_on that is not a date", _body_with("remittance", paid_on="x")),
1670 ("a remittance in no currency", _without("remittance", "currency")),
1671 ("a receipt with no lines", _body_with("receipt", lines=[])),
1672 ("a receipt with no date", _without("receipt", "received_on")),
1673 ("a received quantity that is a number",
1674 _body_with("receipt", lines=[{"line_id": "1", "description": "W", "quantity_received": 3}])),
1675 ("a connection_end reason that is a number", _body_with("connection_end", reason=5)),
1676 ("a refusal with no document id", _without("document_refusal", "document_id")),
1677 ("a refusal hash in capitals", _body_with("document_refusal", envelope_sha256="A" * 64)),
1678 ("a refusal hash of 63 digits", _body_with("document_refusal", envelope_sha256="a" * 63)),
1679 ("a refusal with a blank reason", _body_with("document_refusal", reason=" ")),
1680]
1681
1682# (label, envelope, why) the engine refuses and a schema cannot, because the
1683# answer needs computation, or because JSON Schema reads the value differently.
1684ENVELOPE_ENGINE_ONLY = [
1685 ("a remittance that does not add up", _body_with("remittance", paid_minor=99),
1686 "needs a sum over an array"),
1687 ("two lines with one id", _body_with(lines=[_line(), _line()]), "needs uniqueness by a key of the items"),
1688 ("a created_at that is not a day in the calendar", _envelope(created_at="2026-02-30T00:00:00Z"),
1689 "needs the calendar"),
1690 ("a price written as a float", _body_with(lines=[_line(unit_price_minor=1850.0)]),
1691 "JSON Schema's integer includes 1850.0; the engine, and the canonical form every signature covers, refuse any float"),
1692]
1693
1694# (label, envelope, why) the engine accepts and the schema refuses. In each the
1695# schema is right.
1696ENVELOPE_SCHEMA_STRICTER = [
1697 ("a quantity written with an underscore", _body_with(lines=[_line(quantity="1_0")]),
1698 "Python's Decimal reads '1_0' as 10; no other engine will"),
1699 ("a unit code that is a number", _body_with(lines=[_line(unit_code=5)]),
1700 "the engine tests str(5); the code is text"),
1701 ("charge_minor as text", _body_with(totals={"line_extension_minor": 1, "tax_minor": 0, "payable_minor": 1,
1702 "charge_minor": "1"}),
1703 "documented as minor units; the engine does not look"),
1704 ("payment_reference as a number", _body_with("remittance", payment_reference=5),
1705 "documented as text; the engine does not look"),
1706 ("quantity_rejected as a number",
1707 _body_with("receipt", lines=[{"line_id": "1", "description": "W", "quantity_received": "3", "quantity_rejected": 1}]),
1708 "documented as a decimal string; the engine does not look"),
1709 ("a refusal code that is a number", _body_with("document_refusal", code=4),
1710 "documented as text; the engine does not look"),
1711]
1712
1713# What no schema can say about a document, written down so nobody expects it:
1714ENVELOPE_CHECKS_ONLY_THE_ENGINE_MAKES = (
1715 "the detached signature over the canonical bytes (Ed25519)",
1716 "the canonical bytes themselves (sorted keys, no floats, ASCII object keys)",
1717 "the SHA-256 of the envelope a delivery or a refusal names",
1718 "the delivery's clock window",
1719 "whether the sender is a pinned partner and may send this type",
1720 "whether the documents in refs and settles are known to this box",
1721)
1722
1723
1724@pytest.mark.parametrize("label,envelope", ENVELOPE_BOTH_REFUSE, ids=[c[0] for c in ENVELOPE_BOTH_REFUSE])
1725def test_an_envelope_the_engine_refuses_is_refused_by_the_schema_too(label, envelope):
1726 assert envelope_engine_refuses(envelope), "the engine accepts this now: move it"
1727 assert schema_errors(envelope, DOCUMENT_SCHEMA)
1728
1729
1730@pytest.mark.parametrize("label,envelope,why", ENVELOPE_ENGINE_ONLY, ids=[c[0] for c in ENVELOPE_ENGINE_ONLY])
1731def test_what_only_the_engine_can_judge_in_an_envelope_is_listed(label, envelope, why):
1732 assert envelope_engine_refuses(envelope), "the engine accepts this now"
1733 assert not schema_errors(envelope, DOCUMENT_SCHEMA), "the schema refuses this now: move it to the refused list"
1734
1735
1736@pytest.mark.parametrize("label,envelope,why", ENVELOPE_SCHEMA_STRICTER, ids=[c[0] for c in ENVELOPE_SCHEMA_STRICTER])
1737def test_where_the_engine_reads_an_envelope_more_loosely_than_the_schema_the_schema_is_right(label, envelope, why):
1738 assert envelope_engine_refuses(envelope) is None, "the engine refuses this now: move it to the refused list"
1739 assert schema_errors(envelope, DOCUMENT_SCHEMA)
1740
1741
1742def test_a_float_in_a_document_has_no_canonical_form_so_it_could_never_be_signed():
1743 envelope = _body_with(lines=[_line(unit_price_minor=1850.0)])
1744 with pytest.raises(object_exchange.CanonicalError):
1745 object_exchange.canonical(envelope)
1746
1747
1748def test_an_envelope_key_outside_ascii_has_no_canonical_form():
1749 envelope = _body_with(note="x")
1750 envelope["body"]["n\u00e4me"] = 1
1751 assert not schema_errors(envelope, DOCUMENT_SCHEMA), "keys beyond those defined are allowed in a body"
1752 with pytest.raises(object_exchange.CanonicalError):
1753 object_exchange.canonical(envelope)
1754
1755
1756def test_the_checks_only_the_engine_makes_are_written_down():
1757 assert len(ENVELOPE_CHECKS_ONLY_THE_ENGINE_MAKES) >= 5
1758 text = (ROOT / "docs" / "dron.md").read_text(encoding="utf-8")
1759 assert "dron-document.schema.json" in text
1760
1761
1762# --- the editor mechanism ---------------------------------------------------
1763
1764def test_a_dollar_schema_key_is_tolerated_by_every_loader_for_every_shipped_file_kind():
1765 """Pointing an editor at the schema must never break an install. Tried on
1766 one real file of each kind, through the real loaders."""
1767 schema_path = next(PACKAGES.glob("app-notes/schemas/*.json"))
1768 manifest = PACKAGES / "app-notes" / "dbbasic-package.json"
1769 rules = next(PACKAGES.glob("app-notes/permissions/*.json"))
1770
1771 collection = json.loads(schema_path.read_text())
1772 collection["$schema"] = "../../../dron/dron-collection.schema.json"
1773 normalized = object_schemas.normalize_schema(schema_path.stem, collection)
1774 assert "$schema" not in normalized, "normalization drops the key; the file on disk is unchanged"
1775
1776 package = json.loads(manifest.read_text())
1777 package["$schema"] = "../../dron/dron-package.schema.json"
1778 assert package_loader_refuses(package, package_id="app-notes") is None
1779
1780 permissions = json.loads(rules.read_text())
1781 permissions["$schema"] = "../../../dron/dron-permissions.schema.json"
1782 assert permissions_loader_refuses(permissions) is None
1783
1784 for payload, schema_file in ((collection, COLLECTION_SCHEMA), (package, PACKAGE_SCHEMA),
1785 (permissions, PERMISSIONS_SCHEMA)):
1786 assert not schema_errors(payload, schema_file)
1787
1788
1789def test_the_documented_editor_mappings_match_the_files_on_disk():
1790 """docs/package-authoring.md tells an editor which schema covers which
1791 file; the globs it prints must select the files this test validates."""
1792 text = (ROOT / "docs" / "package-authoring.md").read_text(encoding="utf-8")
1793 for needle in ("dron/dron-collection.schema.json", "dron/dron-package.schema.json",
1794 "dron/dron-permissions.schema.json"):
1795 assert needle in text
1796 for glob in ("packages/*/schemas/*.json", "packages/*/dbbasic-package.json",
1797 "packages/*/permissions/*.json"):
1798 assert glob in text