askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_object_access_guard.py · 26.8 KB · 589 lines
| 1 | """Guard: a page or action must not touch records without asking who is asking. |
| 2 | |
| 3 | Most access bugs found in November 2026 were an object under |
| 4 | ``packages/*/objects/site`` or ``objects/action`` that read or changed a |
| 5 | record straight through ``object_records`` and never asked the permission |
| 6 | engine. ``object_records`` gives the raw row: no rule, no row filter, no |
| 7 | owner check. The generic collection API asks the engine about every row; an |
| 8 | object that reads storage directly is the only gate in front of what it shows |
| 9 | or changes. The platform remembers the other rules for people; this is the |
| 10 | one a person has to remember, so forgetting it fails here. |
| 11 | |
| 12 | THE RULE (the file is parsed with ``ast``; nothing is matched by text except |
| 13 | the exemption comment): |
| 14 | |
| 15 | Every reference to a public ``object_records`` reader or writer in a package's |
| 16 | site or action object -- ``read_collection_records``, ``get_collection_record``, |
| 17 | ``create_/update_/delete_collection_record``, ``read_collection_records_where`` |
| 18 | and the rest of READERS / WRITERS below, through ``object_records.x``, an |
| 19 | alias of the module, or ``from object_records import x`` -- must be one of: |
| 20 | |
| 21 | 1. DECIDED THROUGH object_access. The file asks the permission engine about |
| 22 | THAT collection, through an ``Access`` (a name assigned from |
| 23 | ``object_access.Access(...)``, a parameter called ``access`` or annotated |
| 24 | as one; a plain dict's ``.get`` is not an ask): ``.get(collection, id)``, |
| 25 | ``.can(action, collection, record)``, ``.visible(collection, rows)`` or |
| 26 | ``.reads_every_row(collection)`` somewhere in the same file. The |
| 27 | collection is the call's first argument, compared as a string literal |
| 28 | (module-level ``NAME = "literal"`` constants are resolved) or, when it is |
| 29 | a variable, as the same expression text. Asking about ``orders`` does not |
| 30 | cover a read of ``order_lines``: each collection the object touches needs |
| 31 | its own question, or its own exemption. The test checks that the file |
| 32 | asks, not that the answer is used or that it comes first; reading the |
| 33 | diff for that is still a person's job. |
| 34 | |
| 35 | 2. EXEMPT, with a comment on the call's line or on a comment line directly |
| 36 | above it (for a call that spans lines: anywhere from the line above the |
| 37 | statement to the end of the first argument):: |
| 38 | |
| 39 | # access: <reason> |
| 40 | |
| 41 | The reason is a plain sentence a reviewer can check against the code |
| 42 | around it. Reasons that name a fact the repository can state are CHECKED, |
| 43 | so they cannot rot into a lie: |
| 44 | |
| 45 | - ``# access: admin-only object (execute grant role:admin)`` -- the |
| 46 | object's id (from its package manifest) must have no ``execute`` allow |
| 47 | rule across ``packages/*/permissions/rules.json`` for anyone but |
| 48 | ``role:admin``. With no grant at all the engine refuses everybody but |
| 49 | an admin, which is also admin-only. A page the engine refuses to |
| 50 | everybody else decides who may reach it for every call in it. |
| 51 | - ``# access: role-only object (execute grant role:manager)`` -- at |
| 52 | least one ``execute`` allow rule, and every one of them for a |
| 53 | ``role:*`` principal (never ``registered`` or ``public``). |
| 54 | - ``# access: public <what>`` (``public catalog``) -- the collection must |
| 55 | be a literal and some rule must allow ``public`` to read it. Reads only. |
| 56 | |
| 57 | Other reasons are accepted as free text of at least two words, for |
| 58 | example ``box configuration`` (an ``app_settings`` read), ``system write |
| 59 | after access check above`` (the record being written was just read through |
| 60 | Access, or the caller was refused earlier), ``caller's own row, keyed by |
| 61 | identity``, or ``in-process job, no request subject``. A reviewer is |
| 62 | expected to refuse a reason the code around it does not back. A |
| 63 | hand-written ``owner_id == user_id`` filter is exempt only where it is |
| 64 | strictly tighter than the engine (the caller's own rows and nothing |
| 65 | else); the ones that let a blank-owner row through were the bugs, and use |
| 66 | ``Access`` now (docs/permissions-model.md, "The guard test"). |
| 67 | |
| 68 | Not scanned: ``objects/system``, ``hook`` and ``webhook`` objects (they run |
| 69 | for the platform or an event, not for a person's request), and helper |
| 70 | modules at the repository root that read records for a caller (object_stock, |
| 71 | object_wallet, object_cart ...). A helper that takes the request's caller is |
| 72 | the helper's contract to document; an object that calls one still needs to |
| 73 | decide access for the collection it passes. |
| 74 | |
| 75 | ``test_every_public_record_function_is_classified`` fails when somebody adds |
| 76 | a public function to ``object_records`` without saying whether it reads rows, |
| 77 | writes rows or does neither, so the list this guard polices cannot go stale. |
| 78 | """ |
| 79 | |
| 80 | from __future__ import annotations |
| 81 | |
| 82 | import ast |
| 83 | import inspect |
| 84 | import json |
| 85 | import re |
| 86 | import warnings |
| 87 | from pathlib import Path |
| 88 | |
| 89 | import pytest |
| 90 | |
| 91 | import object_records |
| 92 | |
| 93 | ROOT = Path(__file__).resolve().parent.parent |
| 94 | PACKAGES = ROOT / "packages" |
| 95 | |
| 96 | # Public object_records functions that return or change rows of a collection |
| 97 | # (or reveal whether a collection has any). Every one of them skips the |
| 98 | # permission engine. |
| 99 | READERS = frozenset({ |
| 100 | "list_collection_records", |
| 101 | "read_collection_records", |
| 102 | "read_collection_records_where", |
| 103 | "read_collection_records_for_plan", |
| 104 | "read_collection_records_and_candidates", |
| 105 | "collection_records_payload", |
| 106 | "get_collection_record", |
| 107 | "list_append_collection_stats", |
| 108 | "collection_has_records", |
| 109 | }) |
| 110 | WRITERS = frozenset({ |
| 111 | "create_collection_record", |
| 112 | "update_collection_record", |
| 113 | "delete_collection_record", |
| 114 | "compact_collection", |
| 115 | "prune_collection_records", |
| 116 | "append_collection_stats", |
| 117 | }) |
| 118 | # Public functions that neither read nor write a caller's rows: id and |
| 119 | # payload helpers, pure row filters, file locations, a lock-state probe, the |
| 120 | # names of collections. |
| 121 | NEUTRAL = frozenset({ |
| 122 | "compute_record_rev", |
| 123 | "client_record_rev", |
| 124 | "validate_record_id", |
| 125 | "normalize_record_payload", |
| 126 | "filter_records", |
| 127 | "normalize_filter_value", |
| 128 | "candidate_positions", |
| 129 | "find_unique_violations", |
| 130 | "collection_records_file", |
| 131 | "iter_record_collections", |
| 132 | "append_compact_min_rows", |
| 133 | "in_locked_check", |
| 134 | "recompute_computed_fields", |
| 135 | "committed_prefix_len", |
| 136 | }) |
| 137 | RECORD_IO = READERS | WRITERS |
| 138 | |
| 139 | # The Access methods that decide one collection, and where the collection |
| 140 | # sits among their positional arguments. |
| 141 | ASK = {"get": 0, "visible": 0, "reads_every_row": 0, "can": 1} |
| 142 | |
| 143 | EXEMPT_RE = re.compile(r"#\s*access:\s*(?P<reason>\S.*?)\s*$") |
| 144 | MIN_REASON_WORDS = 2 |
| 145 | |
| 146 | HOW_TO_FIX = ( |
| 147 | "Ask the permission engine for this collection:\n" |
| 148 | " access = object_access.Access(request.get(\"_identity\"), base_dir=base)\n" |
| 149 | " record = access.get(\"<collection>\", record_id) # None: missing OR refused\n" |
| 150 | " rows = access.visible(\"<collection>\", rows) # what the API would list\n" |
| 151 | " if not access.can(\"update\", \"<collection>\", record): ... # before a write\n" |
| 152 | "or, if the call is legitimately outside a person's access, say why on the same\n" |
| 153 | "line or the line above:\n" |
| 154 | " # access: <reason a reviewer can check against the code around it>\n" |
| 155 | "(for example 'box configuration', 'system write after access check above',\n" |
| 156 | "'admin-only object (execute grant role:admin)', 'public catalog'). " |
| 157 | "See tests/test_object_access_guard.py and docs/permissions-model.md " |
| 158 | "(\"The guard test\")." |
| 159 | ) |
| 160 | |
| 161 | |
| 162 | def _object_files(): |
| 163 | files = sorted(PACKAGES.glob("*/objects/site/*.py")) |
| 164 | files += sorted(PACKAGES.glob("*/objects/action/*.py")) |
| 165 | return [path for path in files if path.name != "__init__.py"] |
| 166 | |
| 167 | |
| 168 | def _rel(path: Path) -> str: |
| 169 | return str(path.relative_to(ROOT)) |
| 170 | |
| 171 | |
| 172 | def _constants(tree: ast.Module) -> dict[str, str]: |
| 173 | """Module-level NAME = "literal" assignments.""" |
| 174 | found: dict[str, str] = {} |
| 175 | for node in tree.body: |
| 176 | if (isinstance(node, ast.Assign) and len(node.targets) == 1 |
| 177 | and isinstance(node.targets[0], ast.Name) |
| 178 | and isinstance(node.value, ast.Constant) |
| 179 | and isinstance(node.value.value, str)): |
| 180 | found[node.targets[0].id] = node.value.value |
| 181 | return found |
| 182 | |
| 183 | |
| 184 | def _collection_key(node: ast.AST | None, constants: dict[str, str]) -> tuple[str, bool]: |
| 185 | """(key, is_literal) for a collection argument.""" |
| 186 | if node is None: |
| 187 | return "<no collection argument>", False |
| 188 | if isinstance(node, ast.Constant) and isinstance(node.value, str): |
| 189 | return node.value, True |
| 190 | if isinstance(node, ast.Name) and node.id in constants: |
| 191 | return constants[node.id], True |
| 192 | return ast.unparse(node), False |
| 193 | |
| 194 | |
| 195 | class _Scan: |
| 196 | """What one object file does with object_records and object_access.""" |
| 197 | |
| 198 | def __init__(self, path: Path): |
| 199 | self.path = path |
| 200 | self.source = path.read_text(encoding="utf-8") |
| 201 | self.lines = self.source.splitlines() |
| 202 | with warnings.catch_warnings(): |
| 203 | # A shipped object with a regex in a plain string would warn here. |
| 204 | warnings.simplefilter("ignore", SyntaxWarning) |
| 205 | self.tree = ast.parse(self.source) |
| 206 | self.constants = _constants(self.tree) |
| 207 | self.module_names: set[str] = set() # names bound to object_records |
| 208 | self.function_names: dict[str, str] = {} # local name -> record function |
| 209 | self.access_module_names: set[str] = set() |
| 210 | self.access_names: set[str] = set() # names holding an Access |
| 211 | self.asked: set[str] = set() # collection keys asked of Access |
| 212 | self.sites: list[dict] = [] |
| 213 | self._imports() |
| 214 | self._access_values() |
| 215 | self._asked() |
| 216 | self._sites() |
| 217 | |
| 218 | def _imports(self): |
| 219 | for node in ast.walk(self.tree): |
| 220 | if isinstance(node, ast.Import): |
| 221 | for alias in node.names: |
| 222 | if alias.name == "object_records": |
| 223 | self.module_names.add(alias.asname or alias.name) |
| 224 | if alias.name == "object_access": |
| 225 | self.access_module_names.add(alias.asname or alias.name) |
| 226 | elif isinstance(node, ast.ImportFrom): |
| 227 | if node.module == "object_records": |
| 228 | for alias in node.names: |
| 229 | if alias.name in RECORD_IO: |
| 230 | self.function_names[alias.asname or alias.name] = alias.name |
| 231 | if node.module == "object_access": |
| 232 | for alias in node.names: |
| 233 | if alias.name == "Access": |
| 234 | self.access_module_names.add("<from>") |
| 235 | |
| 236 | def _is_access_ctor(self, node: ast.AST | None) -> bool: |
| 237 | return (isinstance(node, ast.Call) |
| 238 | and isinstance(node.func, ast.Attribute) and node.func.attr == "Access" |
| 239 | and isinstance(node.func.value, ast.Name) |
| 240 | and node.func.value.id in self.access_module_names) or ( |
| 241 | isinstance(node, ast.Call) and isinstance(node.func, ast.Name) |
| 242 | and node.func.id == "Access" and "<from>" in self.access_module_names) |
| 243 | |
| 244 | def _access_values(self): |
| 245 | """Names that hold an Access: assigned from one, or a parameter that |
| 246 | is named ``access`` or annotated as one.""" |
| 247 | for node in ast.walk(self.tree): |
| 248 | if isinstance(node, (ast.Assign, ast.AnnAssign)): |
| 249 | value = node.value |
| 250 | targets = node.targets if isinstance(node, ast.Assign) else [node.target] |
| 251 | if self._is_access_ctor(value): |
| 252 | for target in targets: |
| 253 | if isinstance(target, ast.Name): |
| 254 | self.access_names.add(target.id) |
| 255 | elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): |
| 256 | args = node.args |
| 257 | for arg in args.posonlyargs + args.args + args.kwonlyargs: |
| 258 | annotated = arg.annotation is not None and "Access" in ast.unparse(arg.annotation) |
| 259 | if annotated or arg.arg == "access": |
| 260 | self.access_names.add(arg.arg) |
| 261 | |
| 262 | def _is_access(self, node: ast.AST) -> bool: |
| 263 | if isinstance(node, ast.Name): |
| 264 | return node.id in self.access_names |
| 265 | return self._is_access_ctor(node) |
| 266 | |
| 267 | def _asked(self): |
| 268 | for node in ast.walk(self.tree): |
| 269 | if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) |
| 270 | and node.func.attr in ASK and self._is_access(node.func.value)): |
| 271 | continue |
| 272 | index = ASK[node.func.attr] |
| 273 | if len(node.args) > index: |
| 274 | key, _literal = _collection_key(node.args[index], self.constants) |
| 275 | self.asked.add(key) |
| 276 | |
| 277 | def _is_record_io(self, node: ast.AST) -> str | None: |
| 278 | if (isinstance(node, ast.Attribute) and node.attr in RECORD_IO |
| 279 | and isinstance(node.value, ast.Name) and node.value.id in self.module_names): |
| 280 | return node.attr |
| 281 | if isinstance(node, ast.Name) and node.id in self.function_names: |
| 282 | return self.function_names[node.id] |
| 283 | return None |
| 284 | |
| 285 | def _sites(self): |
| 286 | parents: dict[int, ast.AST] = {} |
| 287 | for parent in ast.walk(self.tree): |
| 288 | for child in ast.iter_child_nodes(parent): |
| 289 | parents[id(child)] = parent |
| 290 | for node in sorted(ast.walk(self.tree), key=lambda n: (getattr(n, "lineno", 0), getattr(n, "col_offset", 0))): |
| 291 | function = self._is_record_io(node) |
| 292 | if function is None: |
| 293 | continue |
| 294 | parent = parents.get(id(node)) |
| 295 | call = parent if isinstance(parent, ast.Call) and parent.func is node else None |
| 296 | # A bare reference (passed around, aliased) is a use too: it has no |
| 297 | # argument to resolve, so it can only be exempted or refused. |
| 298 | first = None |
| 299 | if call is not None: |
| 300 | first = call.args[0] if call.args else next( |
| 301 | (kw.value for kw in call.keywords if kw.arg in ("collection", "name")), None) |
| 302 | key, literal = _collection_key(first, self.constants) if call is not None else ( |
| 303 | "<referenced, not called>", False) |
| 304 | statement = node |
| 305 | while id(statement) in parents and not isinstance(statement, ast.stmt): |
| 306 | statement = parents[id(statement)] |
| 307 | top = getattr(statement, "lineno", node.lineno) |
| 308 | end = max(node.lineno, getattr(first, "end_lineno", None) or node.lineno) |
| 309 | self.sites.append({ |
| 310 | "function": function, "line": node.lineno, "key": key, "literal": literal, |
| 311 | "writes": function in WRITERS, |
| 312 | "window": (top, node.lineno, end), |
| 313 | }) |
| 314 | |
| 315 | def exemption(self, site) -> str | None: |
| 316 | top, line, end = site["window"] |
| 317 | # The line above counts only when it is a comment line of its own: a |
| 318 | # trailing comment on the previous statement belongs to that statement. |
| 319 | above = self.lines[top - 2] if top >= 2 else "" |
| 320 | candidates = ([above] if above.lstrip().startswith("#") else []) + [ |
| 321 | self.lines[number - 1] for number in range(top, end + 1) |
| 322 | if 0 < number <= len(self.lines)] |
| 323 | for text in candidates: |
| 324 | match = EXEMPT_RE.search(text) |
| 325 | if match: |
| 326 | return match.group("reason") |
| 327 | return None |
| 328 | |
| 329 | |
| 330 | # ---------------------------------------------------------------- manifests |
| 331 | |
| 332 | def _manifest_objects() -> dict[str, str]: |
| 333 | """repo-relative object path -> object id, from every package manifest.""" |
| 334 | found = {} |
| 335 | for manifest in sorted(PACKAGES.glob("*/dbbasic-package.json")): |
| 336 | data = json.loads(manifest.read_text(encoding="utf-8")) |
| 337 | for entry in data.get("objects", []): |
| 338 | found[_rel(manifest.parent / entry["path"])] = entry["id"] |
| 339 | return found |
| 340 | |
| 341 | |
| 342 | def _all_rules() -> list[dict]: |
| 343 | rules = [] |
| 344 | for rules_file in sorted(PACKAGES.glob("*/permissions/*.json")): |
| 345 | data = json.loads(rules_file.read_text(encoding="utf-8")) |
| 346 | rules.extend(rule for rule in data.get("rules", []) if isinstance(rule, dict)) |
| 347 | return rules |
| 348 | |
| 349 | |
| 350 | def _execute_grants(path: Path, objects: dict[str, str], rules: list[dict]): |
| 351 | """(object id, the principals of every rule that lets someone execute it).""" |
| 352 | object_id = objects.get(_rel(path)) |
| 353 | if object_id is None: |
| 354 | return None, [] |
| 355 | return object_id, [ |
| 356 | str(rule.get("principal")) for rule in rules |
| 357 | if rule.get("effect") == "allow" and rule.get("object_id") == object_id |
| 358 | and "execute" in (rule.get("actions") or [])] |
| 359 | |
| 360 | |
| 361 | def _admin_only_problem(path: Path, objects: dict[str, str], rules: list[dict]) -> str | None: |
| 362 | object_id, principals = _execute_grants(path, objects, rules) |
| 363 | if object_id is None: |
| 364 | return f"{_rel(path)} is not listed in its package manifest, so its grants cannot be read" |
| 365 | others = sorted(set(principals) - {"role:admin"}) |
| 366 | if others: |
| 367 | return f"{object_id} is also executable by {', '.join(others)}, so it is not admin-only" |
| 368 | return None |
| 369 | |
| 370 | |
| 371 | def _role_only_problem(path: Path, objects: dict[str, str], rules: list[dict]) -> str | None: |
| 372 | object_id, principals = _execute_grants(path, objects, rules) |
| 373 | if object_id is None: |
| 374 | return f"{_rel(path)} is not listed in its package manifest, so its grants cannot be read" |
| 375 | if not principals: |
| 376 | return f"no rule grants execute on {object_id}; name the role that may run it" |
| 377 | open_to = sorted(p for p in set(principals) if not p.startswith("role:")) |
| 378 | if open_to: |
| 379 | return f"{object_id} is also executable by {', '.join(open_to)}, so it is not role-only" |
| 380 | return None |
| 381 | |
| 382 | |
| 383 | def _public_read_problem(site, rules: list[dict]) -> str | None: |
| 384 | if site["writes"]: |
| 385 | return "'public' covers reads; a write needs its own reason" |
| 386 | if not site["literal"]: |
| 387 | return "the collection is not a literal here, so what is public cannot be checked" |
| 388 | for rule in rules: |
| 389 | if (rule.get("effect") == "allow" and rule.get("principal") == "public" |
| 390 | and rule.get("collection") == site["key"] and "read" in (rule.get("actions") or [])): |
| 391 | return None |
| 392 | return f"no rule allows public to read {site['key']!r}" |
| 393 | |
| 394 | |
| 395 | def _check_reason(reason: str, site, scan: _Scan, objects, rules) -> str | None: |
| 396 | """None when the exemption stands, otherwise why it does not.""" |
| 397 | lowered = reason.lower() |
| 398 | if lowered.startswith("admin-only"): |
| 399 | return _admin_only_problem(scan.path, objects, rules) |
| 400 | if lowered.startswith("role-only"): |
| 401 | return _role_only_problem(scan.path, objects, rules) |
| 402 | if lowered.startswith("public"): |
| 403 | return _public_read_problem(site, rules) |
| 404 | if len(reason.split()) < MIN_REASON_WORDS: |
| 405 | return "give a reason a reviewer can check, in at least two words" |
| 406 | return None |
| 407 | |
| 408 | |
| 409 | # -------------------------------------------------------------------- tests |
| 410 | |
| 411 | def _violations() -> list[str]: |
| 412 | objects = _manifest_objects() |
| 413 | rules = _all_rules() |
| 414 | problems = [] |
| 415 | for path in _object_files(): |
| 416 | scan = _Scan(path) |
| 417 | for site in scan.sites: |
| 418 | reason = scan.exemption(site) |
| 419 | where = f"{_rel(path)}:{site['line']}" |
| 420 | what = f"object_records.{site['function']}({site['key']})" |
| 421 | if reason is not None: |
| 422 | bad = _check_reason(reason, site, scan, objects, rules) |
| 423 | if bad: |
| 424 | problems.append(f"{where} {what}\n '# access: {reason}' does not hold: {bad}") |
| 425 | continue |
| 426 | if site["literal"] and site["key"] in scan.asked: |
| 427 | continue |
| 428 | if not site["literal"] and site["key"] in scan.asked: |
| 429 | continue |
| 430 | if scan.asked: |
| 431 | asked = ", ".join(sorted(repr(key) for key in scan.asked)) |
| 432 | detail = (f"this file asks object_access about {asked} but not about " |
| 433 | f"{site['key']!r}") |
| 434 | else: |
| 435 | detail = "this file never asks object_access" |
| 436 | problems.append(f"{where} {what}\n {detail}") |
| 437 | return problems |
| 438 | |
| 439 | |
| 440 | def test_objects_that_touch_records_decide_access_or_say_why(): |
| 441 | problems = _violations() |
| 442 | assert not problems, ( |
| 443 | f"{len(problems)} direct record call(s) in a page or action neither ask the " |
| 444 | f"permission engine nor say why they need not:\n\n" |
| 445 | + "\n".join(problems) + "\n\n" + HOW_TO_FIX) |
| 446 | |
| 447 | |
| 448 | def test_every_public_record_function_is_classified(): |
| 449 | public = { |
| 450 | name for name, value in vars(object_records).items() |
| 451 | if inspect.isfunction(value) and not name.startswith("_") |
| 452 | and value.__module__ == object_records.__name__ |
| 453 | } |
| 454 | unclassified = sorted(public - RECORD_IO - NEUTRAL) |
| 455 | assert not unclassified, ( |
| 456 | "object_records gained public function(s) the access guard has not classified: " |
| 457 | f"{unclassified}. Add each to READERS or WRITERS (it reads or changes a " |
| 458 | "collection's rows) or to NEUTRAL (it does neither) in tests/test_object_access_guard.py.") |
| 459 | stale = sorted((RECORD_IO | NEUTRAL) - public) |
| 460 | assert not stale, f"the guard names object_records functions that no longer exist: {stale}" |
| 461 | |
| 462 | |
| 463 | # The guard itself, on code that is wrong and code that is right. |
| 464 | |
| 465 | def _scan_source(tmp_path, source: str, name="probe.py"): |
| 466 | path = tmp_path / name |
| 467 | path.write_text(source, encoding="utf-8") |
| 468 | return _Scan(path) |
| 469 | |
| 470 | |
| 471 | def _unexplained(scan: _Scan) -> list[dict]: |
| 472 | return [s for s in scan.sites |
| 473 | if scan.exemption(s) is None and not (s["key"] in scan.asked)] |
| 474 | |
| 475 | |
| 476 | def test_the_guard_flags_a_read_with_no_access_question(tmp_path): |
| 477 | scan = _scan_source(tmp_path, ( |
| 478 | "import object_records\n" |
| 479 | "def run(base):\n" |
| 480 | " return object_records.get_collection_record('orders', 'o1', base_dir=base)\n")) |
| 481 | assert [s["key"] for s in _unexplained(scan)] == ["orders"] |
| 482 | |
| 483 | |
| 484 | def test_the_guard_flags_every_spelling_of_the_import(tmp_path): |
| 485 | scan = _scan_source(tmp_path, ( |
| 486 | "import object_records as r\n" |
| 487 | "from object_records import update_collection_record as put\n" |
| 488 | "def run(base):\n" |
| 489 | " r.read_collection_records('orders', base_dir=base)\n" |
| 490 | " put('orders', 'o1', {}, base_dir=base)\n" |
| 491 | " fn = r.delete_collection_record\n")) |
| 492 | assert [s["function"] for s in scan.sites] == [ |
| 493 | "read_collection_records", "update_collection_record", "delete_collection_record"] |
| 494 | assert len(_unexplained(scan)) == 3 |
| 495 | |
| 496 | |
| 497 | def test_asking_about_one_collection_does_not_cover_another(tmp_path): |
| 498 | scan = _scan_source(tmp_path, ( |
| 499 | "import object_access, object_records\n" |
| 500 | "def run(request, base):\n" |
| 501 | " access = object_access.Access(request.get('_identity'), base_dir=base)\n" |
| 502 | " order = access.get('orders', 'o1')\n" |
| 503 | " object_records.get_collection_record('orders', 'o1', base_dir=base)\n" |
| 504 | " object_records.read_collection_records('order_lines', base_dir=base)\n")) |
| 505 | assert [s["key"] for s in _unexplained(scan)] == ["order_lines"] |
| 506 | |
| 507 | |
| 508 | def test_a_dict_get_is_not_an_access_question(tmp_path): |
| 509 | scan = _scan_source(tmp_path, ( |
| 510 | "import object_access, object_records\n" |
| 511 | "def run(row, base):\n" |
| 512 | " row.get('orders')\n" |
| 513 | " object_records.read_collection_records('orders', base_dir=base)\n")) |
| 514 | assert [s["key"] for s in _unexplained(scan)] == ["orders"] |
| 515 | |
| 516 | |
| 517 | def test_constants_and_each_ask_method_are_resolved(tmp_path): |
| 518 | scan = _scan_source(tmp_path, ( |
| 519 | "import object_access, object_records\n" |
| 520 | "RUNS = 'template_runs'\n" |
| 521 | "def run(request, base, access):\n" |
| 522 | " mine = object_access.Access(None, base_dir=base)\n" |
| 523 | " mine.can('update', RUNS, {})\n" |
| 524 | " access.visible('wallets', [])\n" |
| 525 | " access.reads_every_row(collection)\n" |
| 526 | " object_records.update_collection_record(RUNS, 'r1', {}, base_dir=base)\n" |
| 527 | " object_records.read_collection_records('wallets', base_dir=base)\n" |
| 528 | " object_records.read_collection_records(collection, base_dir=base)\n")) |
| 529 | assert _unexplained(scan) == [] |
| 530 | |
| 531 | |
| 532 | def test_an_exemption_comment_covers_its_own_line_or_the_line_above(tmp_path): |
| 533 | scan = _scan_source(tmp_path, ( |
| 534 | "import object_records\n" |
| 535 | "def run(base):\n" |
| 536 | " # access: box configuration\n" |
| 537 | " a = object_records.read_collection_records('app_settings', base_dir=base)\n" |
| 538 | " b = object_records.read_collection_records('app_settings', base_dir=base) # access: box configuration\n" |
| 539 | " c = object_records.read_collection_records('app_settings', base_dir=base)\n" |
| 540 | " d = object_records.read_collection_records(\n" |
| 541 | " 'app_settings', # access: box configuration\n" |
| 542 | " base_dir=base)\n")) |
| 543 | assert [s["line"] for s in _unexplained(scan)] == [6] |
| 544 | |
| 545 | |
| 546 | def test_an_exemption_must_give_a_reason(tmp_path): |
| 547 | scan = _scan_source(tmp_path, ( |
| 548 | "import object_records\n" |
| 549 | "def run(base):\n" |
| 550 | " object_records.read_collection_records('x', base_dir=base) # access: ok\n")) |
| 551 | [site] = scan.sites |
| 552 | reason = scan.exemption(site) |
| 553 | assert _check_reason(reason, site, scan, {}, []) is not None |
| 554 | assert _check_reason("system write after access check above", site, scan, {}, []) is None |
| 555 | |
| 556 | |
| 557 | def test_admin_only_and_public_reasons_are_checked_against_the_rules(tmp_path): |
| 558 | scan = _scan_source(tmp_path, ( |
| 559 | "import object_records\n" |
| 560 | "def run(base):\n" |
| 561 | " object_records.read_collection_records('products', base_dir=base)\n" |
| 562 | " object_records.update_collection_record('products', 'p', {}, base_dir=base)\n")) |
| 563 | read, write = scan.sites |
| 564 | rules = [ |
| 565 | {"effect": "allow", "principal": "public", "actions": ["read"], "collection": "products"}, |
| 566 | {"effect": "allow", "principal": "role:admin", "actions": ["execute"], "object_id": "site_probe"}, |
| 567 | ] |
| 568 | assert _check_reason("public catalog", read, scan, {}, rules) is None |
| 569 | assert _check_reason("public catalog", read, scan, {}, []) is not None |
| 570 | assert _check_reason("public catalog", write, scan, {}, rules) is not None |
| 571 | scan.path = ROOT / "probe.py" |
| 572 | objects = {_rel(scan.path): "site_probe"} |
| 573 | admin_only = "admin-only object (execute grant role:admin)" |
| 574 | assert _check_reason(admin_only, read, scan, objects, rules) is None |
| 575 | assert _check_reason(admin_only, read, scan, objects, rules[:1]) is None # no grant: admin only |
| 576 | # A role-only claim needs a grant, and only role grants. |
| 577 | assert _check_reason("role-only object (role:manager)", read, scan, objects, rules[:1]) is not None |
| 578 | manager = {"effect": "allow", "principal": "role:manager", "actions": ["execute"], |
| 579 | "object_id": "site_probe"} |
| 580 | assert _check_reason("role-only object (role:manager)", read, scan, objects, rules + [manager]) is None |
| 581 | rules.append({"effect": "allow", "principal": "registered", "actions": ["execute"], |
| 582 | "object_id": "site_probe"}) |
| 583 | assert _check_reason(admin_only, read, scan, objects, rules) is not None |
| 584 | assert _check_reason("role-only object (role:manager)", read, scan, objects, rules + [manager]) is not None |
| 585 | assert _check_reason("admin-only object", read, scan, {}, rules) is not None # not in a manifest |
| 586 | |
| 587 | |
| 588 | def test_the_failure_message_says_what_to_do(): |
| 589 | assert "object_access.Access" in HOW_TO_FIX and "# access: <reason" in HOW_TO_FIX |