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_hidden_fields.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_hidden_fields.py · 9.0 KB · 205 lines
1"""A declared attention count must not be derived from a field its viewer
2cannot read, through the real app with enforcement on.
3
4`object_attention.count` checked that the viewer may read each ROW, then
5evaluated `where`, sums, ages and detail parts on the whole row. A support
6agent who may read every ticket but not its `salary_band` or `amount_cents`
7(a rule's field list) or its `due_on` (hidden in the schema) was shown
8
9- "Band A tickets: 2", a count of rows by the value of the hidden field;
10- "400.00 outstanding", the hidden field summed;
11- "1 in band A, oldest due 30 days ago", a sentence about two hidden fields.
12
13With enforcement on each row is now judged as the viewer may read it. With
14enforcement off the record API serves every field, and nothing changes.
15"""
16
17import json
18import shutil
19from datetime import datetime, timedelta, timezone
20from pathlib import Path
21
22import pytest
23
24import object_access
25import object_attention
26from scripts.try_package import Sandbox
27
28REPO = Path(__file__).resolve().parents[1]
29RECORDS = "/collections/tickets/records"
30
31OWN_ROWS = {"effect": "allow", "principal": "registered",
32 "actions": ["create", "read", "update", "delete"], "collection": "tickets",
33 "row_filter": {"owner_id": "$user_id"}, "reason": "own tickets"}
34SUPPORT = {"effect": "allow", "principal": "role:support", "actions": ["read"],
35 "collection": "tickets",
36 "fields": ["id", "title", "owner_id", "status", "due_on", "bonus_cents"],
37 "reason": "support sees every ticket, not the salary band or the amount"}
38LEAD = {"effect": "allow", "principal": "role:lead", "actions": ["read"],
39 "collection": "tickets", "reason": "a lead sees every ticket, whole"}
40
41ATTENTION = [
42 # a count whose `where` names a hidden field
43 {"id": "band_a", "label": "Band A tickets", "path": "/tickets",
44 "collection": "tickets", "where": {"status": "open", "salary_band": "A"}},
45 # ... and one whose hidden-field condition a missing value would satisfy
46 {"id": "not_band_z", "label": "Not band Z", "path": "/tickets",
47 "collection": "tickets",
48 "where": {"status": "open", "salary_band": {"op": "ne", "value": "Z"}}},
49 # a sum over a hidden field
50 {"id": "open_amount", "label": "Open tickets", "path": "/tickets",
51 "collection": "tickets", "where": {"status": "open"},
52 "detail": {"op": "sum", "field": "amount_cents", "format": "cents",
53 "show_zero": True, "text": "{value} outstanding"}},
54 # detail sentences about hidden fields, beside one about a visible field
55 {"id": "open_detail", "label": "Open tickets, in detail", "path": "/tickets",
56 "collection": "tickets", "where": {"status": "open"},
57 "detail": [
58 {"op": "count", "where": {"salary_band": "A"}, "show_zero": True,
59 "text": "{value} in band A"},
60 {"op": "count", "where": {"salary_band": {"op": "ne", "value": "A"}},
61 "text": "some outside band A"},
62 {"op": "max_age_days", "field": "due_on", "text": "oldest due {value} days ago"},
63 {"op": "count", "where": {"title": "Printer"}, "text": "{value} about the printer"}]},
64 # a field hidden row by row (from the row's owner, in the schema)
65 {"id": "open_bonus", "label": "Open bonuses", "path": "/tickets",
66 "collection": "tickets", "where": {"status": "open"},
67 "detail": {"op": "sum", "field": "bonus_cents", "text": "{value} in bonuses"}},
68]
69
70
71def _packages(root):
72 shutil.copytree(REPO / "packages" / "app-nav", root / "app-nav")
73 pkg = root / "tickets"
74 (pkg / "schemas").mkdir(parents=True)
75 (pkg / "permissions").mkdir()
76 (pkg / "dbbasic-package.json").write_text(json.dumps({
77 "id": "tickets", "name": "Tickets", "version": "0.1.0",
78 "dependencies": ["app-nav"],
79 "schemas": [{"collection": "tickets", "path": "schemas/tickets.json"}],
80 "permissions": [{"path": "permissions/rules.json"}],
81 "attention": ATTENTION}))
82 (pkg / "schemas" / "tickets.json").write_text(json.dumps({
83 "name": "tickets", "version": 1,
84 "fields": [{"name": "id"}, {"name": "title", "type": "text"},
85 {"name": "status", "type": "text"},
86 {"name": "salary_band", "type": "text"},
87 {"name": "amount_cents", "type": "text"},
88 {"name": "bonus_cents", "type": "text", "permissions": {"owner": "hidden"}},
89 {"name": "due_on", "type": "text",
90 "permissions": {"role:support": "hidden"}},
91 {"name": "owner_id", "type": "text"}]}))
92 (pkg / "permissions" / "rules.json").write_text(json.dumps({"rules": [OWN_ROWS, SUPPORT, LEAD]}))
93 return root
94
95
96def _day(days_ago):
97 return (datetime.now(timezone.utc).astimezone().date() - timedelta(days=days_ago)).isoformat()
98
99
100def _box(tmp_path, enforce):
101 sandbox = Sandbox(["app-nav", "tickets"], packages_dir=_packages(tmp_path), enforce=enforce)
102 sandbox.__enter__()
103 sandbox.add_user("ann")
104 sandbox.add_user("sam", roles=["support"])
105 sandbox.add_user("lee", roles=["lead"])
106 sandbox.add_user("ada", roles=["admin"])
107 for row in (
108 {"title": "Printer", "status": "open", "salary_band": "A", "amount_cents": "10000",
109 "bonus_cents": "5", "due_on": _day(30), "owner_id": "ann"},
110 {"title": "Laptop", "status": "open", "salary_band": "A", "amount_cents": "30000",
111 "bonus_cents": "7", "due_on": _day(3), "owner_id": "lee"},
112 {"title": "Badge", "status": "open", "salary_band": "B", "amount_cents": "2500",
113 "bonus_cents": "11", "due_on": "", "owner_id": "bob"},
114 {"title": "Chair", "status": "closed", "salary_band": "A", "amount_cents": "999",
115 "bonus_cents": "13", "due_on": _day(90), "owner_id": "ann"},
116 ):
117 status, body = sandbox.call("admin", "POST", RECORDS, row)
118 assert status == 201, body
119 return sandbox
120
121
122@pytest.fixture
123def box(tmp_path):
124 sandbox = _box(tmp_path, True)
125 yield sandbox
126 sandbox.__exit__(None, None, None)
127
128
129@pytest.fixture
130def open_box(tmp_path):
131 sandbox = _box(tmp_path, False)
132 yield sandbox
133 sandbox.__exit__(None, None, None)
134
135
136def _attention(box, user):
137 """{id: (count, detail)} of the non-zero queues the nav shows `user`."""
138 status, body = box.call(user, "GET", "/objects/action_nav_entries")
139 assert status == 200, body
140 return {row["id"]: (row["count"], row["detail"]) for row in body["attention"]}
141
142
143WHOLE = {
144 "band_a": (2, ""),
145 "not_band_z": (3, ""),
146 "open_amount": (3, "425.00 outstanding"),
147 "open_detail": (3, "2 in band A, some outside band A, oldest due 30 days ago, "
148 "1 about the printer"),
149 "open_bonus": (3, "23 in bonuses"),
150}
151
152
153def test_premise_sam_reads_every_ticket_but_not_these_fields(box):
154 status, body = box.call("sam", "GET", RECORDS)
155 assert status == 200 and len(body["records"]) == 4
156 for record in body["records"]:
157 assert not {"salary_band", "amount_cents", "due_on"} & set(record)
158
159
160def test_a_viewer_who_reads_every_field_sees_the_whole_queue(box):
161 assert _attention(box, "ada") == WHOLE
162
163
164def test_a_count_whose_where_names_a_hidden_field_counts_nothing(box):
165 shown = _attention(box, "sam")
166 # Zero queues are not listed. `ne` on a field that is not there would
167 # have matched every row: a condition on a hidden field is false instead.
168 assert "band_a" not in shown and "not_band_z" not in shown
169
170
171def test_a_sum_over_a_hidden_field_is_not_shown_not_even_as_zero(box):
172 assert _attention(box, "sam")["open_amount"] == (3, "")
173
174
175def test_detail_parts_about_hidden_fields_are_left_out_and_the_rest_kept(box):
176 count, detail = _attention(box, "sam")["open_detail"]
177 assert (count, detail) == (3, "1 about the printer")
178 for told in ("band", "due", "30"):
179 assert told not in detail
180
181
182def test_a_field_hidden_on_some_rows_adds_nothing_from_those_rows(box):
183 # bonus_cents is hidden from a ticket's owner: lee, who otherwise reads
184 # every field of every ticket, owns the one with 7.
185 assert _attention(box, "lee") == {**WHOLE, "open_bonus": (3, "16 in bonuses")}
186 # ann reads only her own open ticket, and not its bonus.
187 assert _attention(box, "ann") == {
188 "band_a": (1, ""), "not_band_z": (1, ""), "open_amount": (1, "100.00 outstanding"),
189 "open_detail": (1, "1 in band A, oldest due 30 days ago, 1 about the printer"),
190 "open_bonus": (1, "")}
191
192
193def test_with_enforcement_off_the_same_declarations_are_unchanged(open_box):
194 """Off (or audit-only) no field is redacted anywhere, so the counts are
195 the row-level ones they always were, for sam as for an admin."""
196 assert _attention(open_box, "sam") == WHOLE
197 assert _attention(open_box, "ada") == WHOLE
198
199
200def test_an_unknown_mode_counts_nothing(box, monkeypatch):
201 def unknown():
202 raise RuntimeError("mode unknown")
203 monkeypatch.setattr(object_access, "enforcement_enabled", unknown)
204 rows = object_attention.rows_for({"user_id": "ada", "roles": ["admin"]}, base_dir=box.data_dir)
205 assert {(row["count"], row["detail"]) for row in rows} == {("0", "")}