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_attention_declared.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_attention_declared.py · 30.0 KB · 650 lines
1"""A declared attention count: `collection` + `where`, counted for the viewer.
2
3Ten packages shipped a Python object whose whole job was "count the rows
4of one collection in a waiting state". The declaration says that instead,
5and these are the properties that make it safe to say:
6
7- `where` is the permission row-filter language and nothing else, plus one
8 documented operator (`older_than_days`, whose threshold may be read from
9 app_settings by key). A bare list is refused rather than given a meaning
10 row filters do not give it.
11- the count is over the rows the VIEWER may read, through the permission
12 engine (object_access), and fails closed: no identity, no policy, no
13 grant all count nothing.
14- it reads the queue through the field index, never the whole collection:
15 a declaration without a literal equality is refused at install.
16- the rollup never computes it, and a global number a replaced provider
17 left behind in attention_counts is neither shown nor kept.
18- what stays code still has one global number, and it reaches only a viewer
19 who may read every row of each collection its entry `reads` (admins
20 only without one); attention_counts itself is not readable over the API.
21"""
22
23from __future__ import annotations
24
25import json
26from datetime import datetime, timedelta, timezone
27
28import pytest
29
30import object_access
31import object_attention
32import object_daemon
33import object_packages
34import object_permission_store
35import object_permissions
36import object_records
37
38POLICY = {
39 "access_mode": "role_based",
40 "rules": [
41 {"effect": "allow", "principal": "registered", "actions": ["read"],
42 "collection": "claims", "row_filter": {"owner_id": "$user_id"}},
43 {"effect": "allow", "principal": "role:manager", "actions": ["read"],
44 "collection": "claims"},
45 ],
46}
47
48NOW = datetime(2026, 11, 29, 12, 0, tzinfo=timezone.utc)
49
50
51def _stamp(days_ago, hours=0):
52 return (NOW - timedelta(days=days_ago, hours=hours)).isoformat()
53
54
55@pytest.fixture
56def box(tmp_path):
57 data = tmp_path / "data"
58 (data / "schemas").mkdir(parents=True)
59 (data / "schemas" / "claims.json").write_text(json.dumps({
60 "name": "claims", "fields": [
61 {"name": "id"}, {"name": "owner_id"}, {"name": "status"},
62 {"name": "amount_cents"}, {"name": "opened_on"}, {"name": "created_at"}]}))
63 object_permission_store.replace_policy(POLICY, data)
64 rows = [
65 {"id": "c1", "owner_id": "ann", "status": "waiting", "amount_cents": "125000",
66 "opened_on": "2026-11-01"},
67 {"id": "c2", "owner_id": "ann", "status": "waiting", "amount_cents": "50",
68 "opened_on": "2026-11-28"},
69 {"id": "c3", "owner_id": "bob", "status": "waiting", "amount_cents": "oops",
70 "opened_on": ""},
71 {"id": "c4", "owner_id": "bob", "status": "done", "amount_cents": "999"},
72 ]
73 for row in rows:
74 object_records.create_collection_record("claims", row, base_dir=data)
75 return data
76
77
78def declare(**overrides):
79 entry = {"collection": "claims", "where": {"status": "waiting"}}
80 entry.update(overrides)
81 return {"collection": entry["collection"],
82 "where": object_attention.parse_where(entry["where"]),
83 "detail": object_attention.parse_detail(entry.get("detail"))}
84
85
86def count_for(box, identity, **overrides):
87 access = object_access.Access(identity, base_dir=box)
88 return object_attention.count(declare(**overrides), access, base_dir=box, now=NOW)
89
90
91ADMIN = {"user_id": "ops", "roles": ["admin"]}
92MANAGER = {"user_id": "meg", "roles": ["manager"]}
93ANN = {"user_id": "ann"}
94NOBODY = {"user_id": "zed"}
95
96
97# --- the vocabulary ----------------------------------------------------------
98
99@pytest.mark.parametrize("where, message", [
100 ({}, "non-empty"),
101 ({"status": ["a", "b"]}, "membership"),
102 ({"status": {"op": "like", "value": "a"}}, "unknown op"),
103 ({"status": {"op": "in", "value": "a"}}, "list of strings"),
104 ({"created_at": {"op": "older_than_days", "value": "7"}}, "whole number"),
105 ({"created_at": {"op": "older_than_days", "value": -1}}, "whole number"),
106 ({"created_at": {"op": "older_than_days", "value": {"setting": "a.b"}}}, "exactly setting"),
107 ({"created_at": {"op": "older_than_days",
108 "value": {"setting": "a.b", "default": 7, "max": 9}}}, "exactly setting"),
109 ({"created_at": {"op": "older_than_days",
110 "value": {"setting": "nodot", "default": 7}}}, "invalid setting key"),
111 ({"created_at": {"op": "older_than_days",
112 "value": {"setting": "a.b", "default": "7"}}}, "as its default"),
113 ({"created_at": {"op": "gte", "value": {"setting": "a.b", "default": 7}}}, "string or number"),
114 ({"amount": {"op": "gte", "value": "3"}}, "literal equality"),
115 ({"owner_id": "$user_id"}, "literal equality"),
116 ({"bad field": "x"}, "invalid field"),
117])
118def test_a_where_outside_the_row_filter_language_is_refused(where, message):
119 with pytest.raises(object_attention.InvalidDeclarationError, match=message):
120 object_attention.parse_where(where)
121
122
123def test_a_where_is_exactly_what_a_row_filter_accepts():
124 where = object_attention.parse_where({
125 "status": {"op": "in", "value": ["waiting", ""]},
126 "owner_id": "$user_id",
127 "amount": [{"op": "gte", "value": 3}, {"op": "lt", "value": "10"}],
128 "created_at": {"op": "older_than_days", "value": 7},
129 })
130 assert where["amount"] == [{"op": "gte", "value": "3"}, {"op": "lt", "value": "10"}]
131
132
133@pytest.mark.parametrize("detail, message", [
134 ({"op": "avg", "text": "{value}"}, "op must be"),
135 ({"op": "sum", "text": "{value}"}, "field"),
136 ({"op": "count", "text": " "}, "short sentence"),
137 ({"op": "count", "text": "x" * 201}, "short sentence"),
138 ({"op": "count", "text": "{value} of {total}"}, "no placeholder"),
139 ({"op": "count", "format": "cents", "text": "{value}"}, "format"),
140 ({"op": "count", "text": "{value}", "colour": "red"}, "unknown keys"),
141])
142def test_a_detail_that_could_not_render_is_refused(detail, message):
143 with pytest.raises(object_attention.InvalidDeclarationError, match=message):
144 object_attention.parse_detail(detail)
145
146
147# --- the viewer --------------------------------------------------------------
148
149def test_an_admin_counts_every_waiting_row(box):
150 assert count_for(box, ADMIN)["count"] == 3
151
152
153def test_a_manager_with_a_collection_grant_counts_every_waiting_row(box):
154 assert count_for(box, MANAGER)["count"] == 3
155
156
157def test_a_member_counts_only_the_rows_they_may_read(box):
158 assert count_for(box, ANN)["count"] == 2
159 assert count_for(box, {"user_id": "bob"})["count"] == 1
160
161
162def test_someone_with_no_grant_counts_nothing(box):
163 assert count_for(box, NOBODY) == {"count": 0, "detail": ""}
164
165
166@pytest.mark.parametrize("identity", [None, {}, {"user_id": ""}])
167def test_no_identity_counts_nothing(box, identity):
168 assert count_for(box, identity)["count"] == 0
169
170
171def test_an_unreadable_policy_counts_nothing_even_for_an_admin(box):
172 (box / "permissions" / "policy.json").write_text("{not json")
173 assert count_for(box, ADMIN)["count"] == 0
174
175
176def test_the_viewer_variable_is_how_a_queue_says_my_own(box):
177 """No `scope` switch: "my rows" is `$user_id`, resolved for the viewer
178 by the same function that resolves it in a row filter."""
179 mine = {"status": "waiting", "owner_id": "$user_id"}
180 assert count_for(box, ADMIN, where=mine)["count"] == 0
181 assert count_for(box, MANAGER, where=mine)["count"] == 0
182 assert count_for(box, ANN, where=mine)["count"] == 2
183
184
185def test_a_collection_that_is_not_installed_counts_zero(box):
186 assert count_for(box, ADMIN, collection="nothing_here")["count"] == 0
187
188
189def test_the_rows_are_read_through_the_index_not_the_whole_collection(box, monkeypatch):
190 seen = {}
191 real = object_records.read_collection_records_for_plan
192
193 def spy(collection, groups, **kwargs):
194 rows, narrowed = real(collection, groups, **kwargs)
195 seen.update(groups=groups, narrowed=narrowed, rows=len(rows))
196 return rows, narrowed
197
198 monkeypatch.setattr(object_records, "read_collection_records_for_plan", spy)
199 object_records.read_collection_records("claims", base_dir=box) # warm the cache
200 assert count_for(box, ADMIN)["count"] == 3
201 assert seen["groups"] == (((("status", frozenset({"waiting"})),),),)
202 assert seen["narrowed"] is True and seen["rows"] == 3
203
204
205# --- the detail --------------------------------------------------------------
206
207def test_a_sum_in_cents_is_integer_arithmetic_and_skips_unparseable_cells(box):
208 detail = {"op": "sum", "field": "amount_cents", "format": "cents",
209 "text": "{value} waiting"}
210 assert count_for(box, ADMIN, detail=detail)["detail"] == "1,250.50 waiting"
211 assert count_for(box, ANN, detail=detail)["detail"] == "1,250.50 waiting"
212 # bob's only waiting row has an unparseable amount: zero, so no sentence
213 assert count_for(box, {"user_id": "bob"}, detail=detail)["detail"] == ""
214
215
216def test_the_dollars_format_is_the_one_the_runner_printed():
217 assert object_attention._format(125050, "dollars") == "$1250.50"
218 assert object_attention._format(-5, "dollars") == "-$0.05"
219 assert object_attention._format(-5, "cents") == "-0.05"
220 assert object_attention._format(5400, "hours") == "1.5"
221
222
223def test_parts_join_and_a_zero_part_is_left_out_unless_asked_for(box):
224 detail = [{"op": "count", "text": "{value} waiting"},
225 {"op": "count", "where": {"status": "nope"}, "text": "{value} odd"},
226 {"op": "count", "where": {"status": "nope"}, "text": "{value} shown",
227 "show_zero": True}]
228 assert count_for(box, ADMIN, detail=detail)["detail"] == "3 waiting, 0 shown"
229
230
231def test_older_than_days_ages_a_date_in_calendar_days(box):
232 today = NOW.astimezone().date()
233 object_records.update_collection_record(
234 "claims", "c2", {"opened_on": (today - timedelta(days=7)).isoformat()}, base_dir=box)
235 object_records.update_collection_record(
236 "claims", "c3", {"opened_on": (today - timedelta(days=6)).isoformat()}, base_dir=box)
237 stale = {"op": "count", "where": {"opened_on": {"op": "older_than_days", "value": 7}},
238 "text": "{value} over a week"}
239 # c1 (weeks ago) and c2 (exactly seven days); c3 is six days
240 assert count_for(box, ADMIN, detail=stale)["detail"] == "2 over a week"
241
242
243def test_older_than_days_ages_a_datetime_in_elapsed_days_and_an_empty_one_not_at_all(tmp_path):
244 rows = [{"created_at": _stamp(7)}, {"created_at": _stamp(6, hours=23)},
245 {"created_at": _stamp(30).replace("+00:00", "Z")},
246 {"created_at": _stamp(9).replace("+00:00", "")}, # naive reads as UTC
247 {"created_at": ""}, {"created_at": "garbage"}]
248 compiled = object_attention._split_where(object_attention.parse_where(
249 {"created_at": {"op": "older_than_days", "value": 7}}, require_equality=False))
250 matched = [row for row in rows if object_attention._matches(
251 row, compiled, None, now=NOW, today=NOW.date())]
252 assert len(matched) == 3
253
254
255def _settings(box, *rows):
256 (box / "schemas" / "app_settings.json").write_text(json.dumps({
257 "name": "app_settings", "fields": [{"name": "id"}, {"name": "key"}, {"name": "value"}]}))
258 for index, (key, value) in enumerate(rows):
259 object_records.create_collection_record(
260 "app_settings", {"id": f"s{index}", "key": key, "value": value}, base_dir=box)
261
262
263STALE_BY_SETTING = {"op": "count", "text": "{value} stale",
264 "where": {"opened_on": {"op": "older_than_days",
265 "value": {"setting": "claims.stale_days",
266 "default": 20}}}}
267
268
269def test_a_threshold_may_be_read_from_a_setting_with_a_default(box):
270 """c1 is 28 days old by NOW, c2 one day. The default (20) counts c1."""
271 assert count_for(box, ADMIN, detail=STALE_BY_SETTING)["detail"] == "1 stale"
272 _settings(box, ("claims.stale_days", " 0 "))
273 assert count_for(box, ADMIN, detail=STALE_BY_SETTING)["detail"] == "2 stale"
274
275
276@pytest.mark.parametrize("value", ["soon", "7.5", "-3", "", " "])
277def test_a_setting_that_is_not_a_whole_number_of_days_reads_as_the_default(box, value):
278 _settings(box, ("claims.stale_days", value))
279 assert count_for(box, ADMIN, detail=STALE_BY_SETTING)["detail"] == "1 stale"
280
281
282def test_the_first_non_blank_setting_row_is_the_one_read(box):
283 """The rule the providers used (app_settings declares the key unique,
284 so a second row is a hand edit)."""
285 _settings(box, ("claims.stale_days", ""), ("claims.stale_days", "0"),
286 ("claims.stale_days", "99"), ("other.stale_days", "99"))
287 assert count_for(box, ADMIN, detail=STALE_BY_SETTING)["detail"] == "2 stale"
288
289
290def test_a_settings_threshold_in_the_top_level_where_decides_the_count(box):
291 where = {"status": "waiting", "opened_on": {
292 "op": "older_than_days", "value": {"setting": "claims.stale_days", "default": 20}}}
293 assert count_for(box, ADMIN, where=where)["count"] == 1
294 _settings(box, ("claims.stale_days", "1"))
295 assert count_for(box, ADMIN, where=where)["count"] == 2
296
297
298def test_a_part_without_value_is_a_fixed_sentence_shown_when_it_counts(box):
299 detail = {"op": "count", "where": {"status": "nope"}, "text": "something is wrong"}
300 assert count_for(box, ADMIN, detail=detail)["detail"] == ""
301 detail = {"op": "count", "text": "failed 3 or more syncs in a row"}
302 assert count_for(box, ADMIN, detail=detail)["detail"] == "failed 3 or more syncs in a row"
303
304
305def test_max_age_names_the_oldest_and_ignores_undated_and_future_rows(box):
306 oldest = {"op": "max_age_days", "field": "opened_on", "text": "oldest {value} days"}
307 today = NOW.astimezone().date()
308 expected = (today - datetime(2026, 11, 1).date()).days
309 assert count_for(box, ADMIN, detail=oldest)["detail"] == f"oldest {expected} days"
310 # bob's waiting row has no date: no age, so no sentence at all
311 assert count_for(box, {"user_id": "bob"}, detail=oldest)["detail"] == ""
312
313
314# --- the manifest and the registry -------------------------------------------
315
316def _normalize(entry):
317 base = {"id": "claims_waiting", "label": "Claims", "path": "/claims"}
318 return object_packages._normalize_attention([{**base, **entry}], package_id="app-demo")
319
320
321def test_a_declared_entry_normalizes_to_canonical_json():
322 [entry] = _normalize({"collection": "claims", "where": {"status": "waiting"},
323 "detail": {"op": "count", "text": "{value} waiting"}})
324 assert entry["object_id"] == ""
325 assert entry["where"] == '{"status":"waiting"}'
326 assert json.loads(entry["detail"]) == [{"op": "count", "text": "{value} waiting"}]
327
328
329@pytest.mark.parametrize("entry, message", [
330 ({"collection": "claims", "where": {"status": "w"}, "object_id": "system_x"}, "both"),
331 ({"object_id": "system_x", "where": {"status": "w"}}, "needs a collection"),
332 ({"collection": "claims"}, "non-empty"),
333 ({"collection": "claims", "where": {"status": ["w"]}}, "membership"),
334 ({"collection": "Bad-Name", "where": {"status": "w"}}, "Invalid package attention collection"),
335])
336def test_a_declaration_that_could_not_work_is_refused_in_the_manifest(entry, message):
337 with pytest.raises(object_packages.InvalidPackageManifestError, match=message):
338 _normalize(entry)
339
340
341def _sources_box(box):
342 schema = json.loads(
343 (object_packages.Path(object_packages.__file__).parent
344 / "packages" / "app-nav" / "schemas" / "attention_sources.json").read_text())
345 (box / "schemas" / "attention_sources.json").write_text(json.dumps(schema))
346 counts = json.loads(
347 (object_packages.Path(object_packages.__file__).parent
348 / "packages" / "app-nav" / "schemas" / "attention_counts.json").read_text())
349 (box / "schemas" / "attention_counts.json").write_text(json.dumps(counts))
350 [entry] = _normalize({"collection": "claims", "where": {"status": "waiting"},
351 "nav_id": "claims", "group": "Work",
352 "detail": {"op": "count", "text": "{value} waiting"}})
353 object_records.create_collection_record("attention_sources", {
354 "id": entry["id"], "package": "app-demo", "operator_muted": "false",
355 **{k: entry[k] for k in object_packages._ATTENTION_PACKAGE_FIELDS}}, base_dir=box)
356 return entry
357
358
359def test_rows_for_counts_a_declared_source_for_the_viewer(box):
360 _sources_box(box)
361 [row] = object_attention.rows_for(ANN, base_dir=box, now=NOW)
362 assert (row["id"], row["label"], row["path"], row["count"], row["detail"]) == (
363 "claims_waiting", "Claims", "/claims", "2", "2 waiting")
364 assert object_attention.rows_for(ADMIN, base_dir=box, now=NOW)[0]["count"] == "3"
365 assert object_attention.rows_for(NOBODY, base_dir=box, now=NOW)[0]["count"] == "0"
366 assert object_attention.rows_for({}, base_dir=box, now=NOW) == []
367
368
369def test_a_global_number_left_by_a_replaced_provider_is_not_shown(box):
370 _sources_box(box)
371 object_records.create_collection_record("attention_counts", {
372 "id": "claims_waiting", "source_id": "claims_waiting", "label": "Claims",
373 "path": "/claims", "count": "40", "detail": "everybody's"}, base_dir=box)
374 rows = object_attention.rows_for(NOBODY, base_dir=box, now=NOW)
375 assert [(row["id"], row["count"]) for row in rows] == [("claims_waiting", "0")]
376
377
378def test_a_muted_declared_source_is_not_counted(box):
379 _sources_box(box)
380 object_records.update_collection_record(
381 "attention_sources", "claims_waiting", {"operator_muted": "true"}, base_dir=box)
382 assert object_attention.rows_for(ADMIN, base_dir=box, now=NOW) == []
383
384
385def test_a_hand_broken_declaration_is_left_out_not_shown_as_a_number(box):
386 _sources_box(box)
387 object_records.update_collection_record(
388 "attention_sources", "claims_waiting", {"where": "{not json"}, base_dir=box)
389 assert object_attention.rows_for(ADMIN, base_dir=box, now=NOW) == []
390
391
392def test_the_rollup_never_counts_a_declared_source_and_removes_its_old_number(box, monkeypatch):
393 _sources_box(box)
394 object_records.create_collection_record("attention_counts", {
395 "id": "claims_waiting", "source_id": "claims_waiting", "count": "40"}, base_dir=box)
396 monkeypatch.setenv(object_daemon.ATTENTION_INTERVAL_ENV, "0")
397 result = object_daemon.process_attention(base_dir=box)
398 assert result == {"sources": 1, "counted": 0, "failed": 0, "muted": 0, "declared": 1}
399 assert object_records.read_collection_records("attention_counts", base_dir=box) == []
400
401
402def test_every_shipped_declaration_parses_and_counts_on_an_empty_box(tmp_path):
403 """Each declaration in the tree normalizes, and counts zero (not an
404 error) where its collection is not installed."""
405 root = object_packages.Path(object_packages.__file__).parent / "packages"
406 access = object_access.Access(ADMIN, base_dir=tmp_path)
407 found = 0
408 for manifest in sorted(root.glob("*/dbbasic-package.json")):
409 payload = json.loads(manifest.read_text())
410 for entry in object_packages._normalize_attention(
411 payload.get("attention", []), package_id=payload["id"]):
412 if not entry["collection"]:
413 continue
414 found += 1
415 declaration = object_attention.declaration_from_source(entry)
416 assert object_attention.count(declaration, access, base_dir=tmp_path) == {
417 "count": 0, "detail": ""}
418 assert found >= 11
419
420
421def shipped_count(package_id, attention_id, base_dir, identity=ADMIN):
422 """What a shipped declaration counts on `base_dir` for `identity` (an
423 admin by default, i.e. the whole queue) -- the helper the package tests
424 use where they used to call the provider object's COUNT."""
425 root = object_packages.Path(object_packages.__file__).parent / "packages"
426 manifest = json.loads((root / package_id / "dbbasic-package.json").read_text())
427 [entry] = [entry for entry in object_packages._normalize_attention(
428 manifest["attention"], package_id=package_id) if entry["id"] == attention_id]
429 access = object_access.Access(identity, base_dir=base_dir)
430 return object_attention.count(object_attention.declaration_from_source(entry),
431 access, base_dir=base_dir)
432
433
434# --- what a code provider's number may reach -----------------------------------
435#
436# The providers that stay code (a fold across collections, arithmetic between
437# fields, a coalesce) are still computed by the daemon with no viewer. Their
438# number is shown only to someone the rows themselves could reach whole.
439
440def _provider_box(box, *, reads, rules=()):
441 _sources_box(box)
442 object_records.create_collection_record("attention_sources", {
443 "id": "claims_total", "package": "app-demo", "operator_muted": "false",
444 "object_id": "system_claims_total", "label": "All claims", "path": "/claims",
445 "reads": object_attention.canonical_json(reads)}, base_dir=box)
446 object_records.create_collection_record("attention_counts", {
447 "id": "claims_total", "source_id": "claims_total", "label": "All claims",
448 "path": "/claims", "count": "4", "detail": "1,374.00 across everybody"}, base_dir=box)
449 if rules:
450 object_permission_store.replace_policy(
451 {**POLICY, "rules": POLICY["rules"] + list(rules)}, box)
452
453
454def _shown(box, identity):
455 return {row["id"]: row["count"]
456 for row in object_attention.rows_for(identity, base_dir=box, now=NOW)}
457
458
459def test_a_providers_number_reaches_only_viewers_who_read_every_row(box):
460 """The manager's rule grants claims unfiltered; ann's grants her own."""
461 _provider_box(box, reads=["claims"])
462 assert _shown(box, ADMIN)["claims_total"] == "4"
463 assert _shown(box, MANAGER)["claims_total"] == "4"
464 assert "claims_total" not in _shown(box, ANN)
465 assert "claims_total" not in _shown(box, NOBODY)
466 assert _shown(box, {}) == {}
467
468
469def test_a_provider_that_names_no_collection_is_shown_only_to_an_admin(box):
470 _provider_box(box, reads=[])
471 assert "claims_total" in _shown(box, ADMIN)
472 assert "claims_total" not in _shown(box, MANAGER)
473
474
475def test_a_count_with_no_source_left_is_shown_only_to_an_admin(box):
476 _provider_box(box, reads=["claims"])
477 object_records.delete_collection_record("attention_sources", "claims_total", base_dir=box)
478 assert "claims_total" in _shown(box, ADMIN)
479 assert "claims_total" not in _shown(box, MANAGER)
480
481
482def test_a_hand_broken_reads_is_shown_only_to_an_admin(box):
483 _provider_box(box, reads=["claims"])
484 object_records.update_collection_record(
485 "attention_sources", "claims_total", {"reads": "claims"}, base_dir=box)
486 assert "claims_total" in _shown(box, ADMIN)
487 assert "claims_total" not in _shown(box, MANAGER)
488
489
490def test_every_collection_read_must_be_readable_whole(box):
491 (box / "schemas" / "claim_notes.json").write_text(json.dumps({
492 "name": "claim_notes", "fields": [{"name": "id"}, {"name": "owner_id"}]}))
493 _provider_box(box, reads=["claims", "claim_notes"])
494 assert "claims_total" not in _shown(box, MANAGER)
495 object_permission_store.replace_policy({**POLICY, "rules": POLICY["rules"] + [
496 {"effect": "allow", "principal": "role:manager", "actions": ["read"],
497 "collection": "claim_notes"}]}, box)
498 assert _shown(box, MANAGER)["claims_total"] == "4"
499
500
501def test_a_collection_the_box_does_not_have_holds_no_rows_and_is_skipped(box):
502 _provider_box(box, reads=["claims", "never_installed"])
503 assert _shown(box, MANAGER)["claims_total"] == "4"
504 # ...but a source whose every collection is absent is hidden.
505 object_records.update_collection_record(
506 "attention_sources", "claims_total",
507 {"reads": object_attention.canonical_json(["never_installed"])}, base_dir=box)
508 assert "claims_total" not in _shown(box, MANAGER)
509
510
511def _claims_schema(box, memo_permissions):
512 (box / "schemas" / "claims.json").write_text(json.dumps({
513 "name": "claims", "fields": [
514 {"name": "id"}, {"name": "owner_id"}, {"name": "status"},
515 {"name": "amount_cents", "permissions": memo_permissions},
516 {"name": "opened_on"}, {"name": "created_at"}]}))
517
518
519ENFORCE = object_access.PERMISSION_ENFORCEMENT_ENV
520
521
522@pytest.mark.parametrize("permissions, hidden_from", [
523 ({"role:manager": "hidden"}, {"manager"}),
524 # Anyone can be a row's owner, the admin included.
525 ({"owner": "hidden"}, {"manager", "admin"}),
526 ({"role:manager": "read", "default": "hidden"}, {"admin"}),
527 ({"owner": "read", "default": "hidden"}, {"manager", "admin"}),
528 ({"registered": "hidden"}, {"manager", "admin"}),
529 ("hidden", {"manager", "admin"}),
530 ({"role:manager": "sometimes"}, {"manager", "admin"}), # malformed: refuse
531 ({"role:clerk": "hidden", "default": "read"}, set()),
532 ({"edit": ["role:admin"], "default": "read"}, set()),
533])
534def test_a_schema_field_permission_that_could_hide_a_field_hides_the_providers_number(
535 box, monkeypatch, permissions, hidden_from):
536 """`reads_every_row` asks the rules only. The manager's rule grants
537 claims with no field list, yet the record API (enforcing) would not
538 show them a field the SCHEMA hides -- and the provider's number and
539 sentence were folded from whole rows."""
540 _provider_box(box, reads=["claims"])
541 _claims_schema(box, permissions)
542 manager = object_access.Access(MANAGER, base_dir=box)
543 assert manager.reads_every_row("claims") # the rules alone say yes
544 monkeypatch.setenv(ENFORCE, "true")
545 for name, identity in (("manager", MANAGER), ("admin", ADMIN)):
546 assert ("claims_total" not in _shown(box, identity)) == (name in hidden_from), name
547 # Not enforced: no field is redacted anywhere, and nothing changes.
548 monkeypatch.delenv(ENFORCE)
549 assert _shown(box, MANAGER)["claims_total"] == "4"
550 assert _shown(box, ADMIN)["claims_total"] == "4"
551
552
553def test_enforcing_alone_hides_no_providers_number(box, monkeypatch):
554 monkeypatch.setenv(ENFORCE, "true")
555 test_a_providers_number_reaches_only_viewers_who_read_every_row(box)
556
557
558def test_a_providers_number_is_shown_to_nobody_when_the_mode_is_unknown(box, monkeypatch):
559 _provider_box(box, reads=["claims"])
560
561 def unknown():
562 raise RuntimeError("mode unknown")
563 monkeypatch.setattr(object_access, "enforcement_enabled", unknown)
564 assert "claims_total" not in _shown(box, ADMIN)
565 assert "claims_total" not in _shown(box, MANAGER)
566
567
568def test_a_deny_that_depends_on_the_row_means_not_every_row(box):
569 """The collection-level question skips a filtered deny, so it is asked
570 separately: a manager denied bob's rows does not read every row."""
571 _provider_box(box, reads=["claims"], rules=[
572 {"effect": "deny", "principal": "role:manager", "actions": ["read"],
573 "collection": "claims", "row_filter": {"owner_id": "bob"}}])
574 assert "claims_total" not in _shown(box, MANAGER)
575 assert "claims_total" in _shown(box, ADMIN)
576
577
578def test_a_field_restricted_grant_is_not_a_whole_read(box):
579 _provider_box(box, reads=["claims"], rules=[])
580 object_permission_store.replace_policy({**POLICY, "rules": [
581 POLICY["rules"][0], {**POLICY["rules"][1], "denied_fields": ["amount_cents"]}]}, box)
582 assert "claims_total" not in _shown(box, MANAGER)
583
584
585def test_an_unreadable_policy_shows_a_providers_number_to_nobody(box):
586 _provider_box(box, reads=["claims"])
587 (box / "permissions" / "policy.json").write_text("{not json")
588 assert "claims_total" not in _shown(box, ADMIN)
589
590
591def test_a_registered_access_mode_reads_every_row(box):
592 _provider_box(box, reads=["claims"])
593 object_permission_store.replace_policy({"access_mode": "registered", "rules": []}, box)
594 assert _shown(box, NOBODY)["claims_total"] == "4"
595
596
597def test_every_shipped_provider_says_what_it_reads():
598 """A provider entry without `reads` is shown to admins only -- safe, and
599 silently narrower than its package meant. Every shipped one names the
600 collections it folds, except backup_problems, whose empty `reads` is
601 the point: it folds no collection, and whether this box's backups work
602 is an admin's business."""
603 root = object_packages.Path(object_packages.__file__).parent / "packages"
604 providers = {}
605 for manifest in sorted(root.glob("*/dbbasic-package.json")):
606 payload = json.loads(manifest.read_text())
607 for entry in object_packages._normalize_attention(
608 payload.get("attention", []), package_id=payload["id"]):
609 if entry["object_id"]:
610 providers[entry["id"]] = json.loads(entry["reads"] or "[]")
611 assert providers == {
612 "orders_to_pick": ["orders", "order_lines", "shipments", "shipment_lines"],
613 "pos_short_received": ["orders", "order_lines", "receipts", "receipt_lines"],
614 "products_to_reorder": ["reorder_suggestions"],
615 "pickup_orders_overdue": ["orders"],
616 "scheduler_failures": ["scheduler_runs"],
617 "backup_problems": [],
618 }
619
620
621@pytest.mark.parametrize("entry, message", [
622 ({"object_id": "system_x", "reads": "claims"}, "list of collection names"),
623 ({"object_id": "system_x", "reads": ["Bad-Name"]}, "list of collection names"),
624 ({"collection": "claims", "where": {"status": "w"}, "reads": ["claims"]},
625 "reads is for a provider"),
626])
627def test_a_reads_that_could_not_work_is_refused_in_the_manifest(entry, message):
628 with pytest.raises(object_packages.InvalidPackageManifestError, match=message):
629 _normalize(entry)
630
631
632def test_a_provider_entry_stores_its_reads_as_canonical_json():
633 [entry] = _normalize({"object_id": "system_x", "reads": ["claims", "notes", "claims"]})
634 assert entry["reads"] == '["claims","notes"]'
635 [entry] = _normalize({"object_id": "system_x"})
636 assert entry["reads"] == ""
637
638
639def test_attention_counts_is_not_readable_by_a_signed_in_user():
640 """The table holds the providers' global numbers. The menu reads it in
641 process and gates each row; the record API must not hand it out whole."""
642 root = object_packages.Path(object_packages.__file__).parent / "packages" / "app-nav"
643 rules = json.loads((root / "permissions" / "rules.json").read_text())["rules"]
644 policy = object_permissions.policy_from_dict({"access_mode": "role_based", "rules": rules})
645 member = object_permissions.PermissionSubject(user_id="ann")
646 row = {"id": "orders_to_pick", "count": "4"}
647 assert not object_permissions.check_permission(
648 member, "read", policy=policy, collection="attention_counts", record=row).allowed
649 assert not object_permissions.check_permission(
650 member, "read", policy=policy, collection="attention_counts").allowed