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_write_path_guard.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_write_path_guard.py · 6.7 KB · 155 lines
1"""Guard: a network route writes a record only through the write path.
2
3Every security defect found in the record routes in one week of November
42026 was a check that one route forgot, ran in a different order, or ran
5outside the lock. docs/dron-write-semantics.md now states the steps of a
6create, an update and a delete; object_server runs them in one function per
7operation (_gated_create, _gated_update, _gated_delete), and every route
8that creates, updates or deletes a record for a caller calls one of them.
9
10THE RULE (object_server.py is parsed with ``ast``): a call to
11``object_records.create_collection_record``, ``update_collection_record``
12or ``delete_collection_record`` is allowed inside the three gated functions
13and nowhere else in object_server.py, unless the call carries, on its line
14or on a comment line directly above it, an exemption::
15
16 # write-path: <reason>
17
18The reason is a plain sentence a reviewer checks against the code around it:
19a server-authored write with no caller's values in it (analytics, the chat
20history the server keeps), or a route whose own rule is the only gate by
21design (record_shares has no policy rules; the share route is its gate).
22Those writes are storage writers in the sense of S55 and skip every gate.
23"""
24
25from __future__ import annotations
26
27import ast
28import re
29from pathlib import Path
30
31ROOT = Path(__file__).resolve().parent.parent
32SERVER = ROOT / "object_server.py"
33
34GATED = frozenset({"_gated_create", "_gated_update", "_gated_delete"})
35WRITERS = frozenset({
36 "create_collection_record",
37 "update_collection_record",
38 "delete_collection_record",
39})
40EXEMPT_RE = re.compile(r"#\s*write-path:\s*(?P<reason>\S.*?)\s*$")
41MIN_REASON_WORDS = 3
42
43
44def _tree_and_lines(source: str):
45 return ast.parse(source), source.splitlines()
46
47
48def _enclosing_functions(tree: ast.Module) -> dict[int, str]:
49 """id(node) -> name of the top-level function it sits in."""
50 owner: dict[int, str] = {}
51 for top in tree.body:
52 if isinstance(top, (ast.FunctionDef, ast.AsyncFunctionDef)):
53 for node in ast.walk(top):
54 owner[id(node)] = top.name
55 return owner
56
57
58def _exemption(lines: list[str], node: ast.Call) -> str | None:
59 """The exemption reason on the call's line, or on the comment lines
60 directly above the statement it starts."""
61 first = node.lineno - 1
62 match = EXEMPT_RE.search(lines[first])
63 if match:
64 return match.group("reason")
65 above = first - 1
66 while above >= 0 and lines[above].strip().startswith("#"):
67 match = EXEMPT_RE.search(lines[above])
68 if match:
69 return match.group("reason")
70 above -= 1
71 return None
72
73
74def unguarded_writes(source: str) -> list[str]:
75 """Each direct write outside the gated functions without an exemption,
76 as 'line N in function: call'."""
77 tree, lines = _tree_and_lines(source)
78 owner = _enclosing_functions(tree)
79 problems: list[str] = []
80 for node in ast.walk(tree):
81 if isinstance(node, ast.ImportFrom) and node.module == "object_records":
82 for alias in node.names:
83 if alias.name in WRITERS or alias.name == "*":
84 problems.append(f"line {node.lineno}: imports object_records.{alias.name} by name")
85 if isinstance(node, ast.Import):
86 for alias in node.names:
87 if alias.name == "object_records" and alias.asname:
88 problems.append(f"line {node.lineno}: imports object_records as {alias.asname}")
89 if not isinstance(node, ast.Call):
90 continue
91 func = node.func
92 if not (isinstance(func, ast.Attribute) and func.attr in WRITERS
93 and isinstance(func.value, ast.Name) and func.value.id == "object_records"):
94 continue
95 where = owner.get(id(node), "<module>")
96 if where in GATED:
97 continue
98 reason = _exemption(lines, node)
99 if reason is not None and len(reason.split()) >= MIN_REASON_WORDS:
100 continue
101 problems.append(f"line {node.lineno} in {where}: object_records.{func.attr}")
102 return sorted(problems, key=lambda text: int(text.split()[1].rstrip(":")))
103
104
105def test_no_route_writes_a_record_around_the_write_path():
106 problems = unguarded_writes(SERVER.read_text(encoding="utf-8"))
107 assert not problems, (
108 "object_server.py writes a record outside _gated_create/_gated_update/"
109 "_gated_delete:\n " + "\n ".join(problems) + "\n"
110 "A write a caller asks for goes through the gated function for its "
111 "operation (docs/dron-write-semantics.md). A server-authored write "
112 "says why on its line or the comment line above:\n"
113 " # write-path: <reason a reviewer can check>"
114 )
115
116
117def test_each_operation_has_its_gated_function_and_it_writes():
118 tree, _ = _tree_and_lines(SERVER.read_text(encoding="utf-8"))
119 owner = _enclosing_functions(tree)
120 writes: dict[str, set[str]] = {}
121 for node in ast.walk(tree):
122 if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
123 and node.func.attr in WRITERS):
124 writes.setdefault(owner.get(id(node), "<module>"), set()).add(node.func.attr)
125 assert writes.get("_gated_create") == {"create_collection_record"}
126 assert writes.get("_gated_update") == {"update_collection_record"}
127 assert writes.get("_gated_delete") == {"delete_collection_record"}
128
129
130def test_the_guard_catches_a_route_that_writes_directly():
131 """The rule itself: a direct write in a handler fails, an exempted one
132 with a reason passes, a bare exemption does not."""
133 bad = (
134 "import object_records\n"
135 "async def _handle_thing(send, headers):\n"
136 " object_records.update_collection_record('c', 'id', {}, base_dir='.')\n"
137 )
138 assert unguarded_writes(bad) == ["line 3 in _handle_thing: object_records.update_collection_record"]
139 exempted = (
140 "import object_records\n"
141 "def _bookkeeping():\n"
142 " # write-path: server-authored row, no caller values\n"
143 " object_records.create_collection_record('c', {}, base_dir='.')\n"
144 )
145 assert unguarded_writes(exempted) == []
146 too_short = exempted.replace("server-authored row, no caller values", "fine")
147 assert unguarded_writes(too_short) == ["line 4 in _bookkeeping: object_records.create_collection_record"]
148 aliased = "from object_records import delete_collection_record\n"
149 assert unguarded_writes(aliased) == ["line 1: imports object_records.delete_collection_record by name"]
150 gated = (
151 "import object_records\n"
152 "async def _gated_delete(headers):\n"
153 " return lambda: object_records.delete_collection_record('c', 'id', base_dir='.')\n"
154 )
155 assert unguarded_writes(gated) == []