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_permission_missing_column.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_permission_missing_column.py · 29.7 KB · 629 lines
1"""A row filter never matches a field the record does not have.
2
3What broke. ``_condition_matches`` compared a scalar ``eq`` as
4``actual == _string_value(resolved)``. Both sides can be None: ``actual``
5when the record dict has no such key (the collection's records.tsv header
6has no such column -- a column exists only once some record was written
7with it), ``resolved`` when a $-variable resolves to nothing (``$user_id``
8for an anonymous visitor, ``$account_id`` for a signed-in user with no
9account) or the rule says a literal null. None == None, the rule matched,
10and the subject got every row -- to read, and to update or delete where the
11rule's actions said so. The same column present but empty was always
12refused ("" != None), so the hole closed itself the first time anyone wrote
13the field, which is how it went unnoticed.
14
15Every other positive operator already refused a None ``actual`` (``in``,
16the tuple-membership branch ``$accessible_projects`` takes, the ordered
17ops). Scalar ``eq`` was the one gap.
18
19The rule now, which an index planner has to mirror exactly -- it is pinned
20as a table in ``COMPARISON_TABLE`` below:
21
22 A positive condition (eq, in, gte/lte/gt/lt) never matches a field that
23 is missing or None. Where the expected value comes from -- a $-variable
24 or a literal -- makes no difference, and neither does the rule's effect:
25 allow and deny rules run the one comparison.
26
27``ne`` is deliberately unchanged by this fix (see
28``test_ne_is_unchanged_and_is_not_the_negation_of_eq_for_a_null_value``).
29
30Each test that would have failed against the old engine says so. That was
31checked by running this file against the module from
32``git show HEAD:object_permissions.py`` (pre-fix) and against a build with
33the one-line fix reverted.
34"""
35
36import json
37
38import pytest
39
40from test_object_server import request, save_permission_policy, write_records
41
42import object_api_keys
43import object_identity
44import object_permissions as permissions
45import object_records
46import object_server
47
48MISSING = object()
49
50ANONYMOUS = permissions.PermissionSubject.anonymous()
51NO_ACCOUNT = permissions.PermissionSubject(user_id="7")
52NO_ACCOUNT_WITH_ROLE = permissions.PermissionSubject(user_id="7", roles=("sales",))
53NO_ACCOUNT_SUBSCRIBER = permissions.PermissionSubject(user_id="7", subscriptions=("pro",))
54ACME_MEMBER = permissions.PermissionSubject(user_id="7", account_id="acme")
55# Subjects with authority but no user id. The server builds these only from
56# trusted identity headers (roles/account/subscriptions sent without a user
57# id); the engine has to be safe for them regardless.
58ROLE_NO_USER = permissions.PermissionSubject(roles=("sales",))
59ACCOUNT_NO_USER = permissions.PermissionSubject(account_id="acme")
60SUBSCRIBER_NO_USER = permissions.PermissionSubject(subscriptions=("pro",))
61
62WRITE_ACTIONS = (permissions.READ, permissions.UPDATE, permissions.DELETE)
63
64
65def record_with(field, value, **extra):
66 """A record whose ``field`` is absent (MISSING), None, or a value."""
67 record = {"id": "r1", "name": "x", **extra}
68 if value is not MISSING:
69 record[field] = value
70 return record
71
72
73def allow_policy(principal, row_filter, *, collection="things"):
74 return permissions.PermissionPolicy(
75 access_mode="role_based",
76 rules=(
77 permissions.PermissionRule.allow(
78 principal, WRITE_ACTIONS, collection=collection, row_filter=row_filter
79 ),
80 ),
81 )
82
83
84# (principal, subject, variable, field) -- every principal kind that admits a
85# subject for whom the variable resolves to None. `registered`, `owner` and
86# `user:N` require a user id, so they can only be reached with $account_id;
87# `account:X` requires an account id, so only with $user_id.
88UNRESOLVED_VARIABLE_CASES = [
89 ("public", ANONYMOUS, "$user_id", "owner_id"),
90 ("role:sales", ROLE_NO_USER, "$user_id", "owner_id"),
91 ("account:acme", ACCOUNT_NO_USER, "$user_id", "owner_id"),
92 ("subscription:pro", SUBSCRIBER_NO_USER, "$user_id", "owner_id"),
93 ("public", ANONYMOUS, "$account_id", "customer_account_id"),
94 ("public", NO_ACCOUNT, "$account_id", "customer_account_id"),
95 ("registered", NO_ACCOUNT, "$account_id", "customer_account_id"),
96 ("owner", NO_ACCOUNT, "$account_id", "customer_account_id"),
97 ("role:sales", NO_ACCOUNT_WITH_ROLE, "$account_id", "customer_account_id"),
98 ("user:7", NO_ACCOUNT, "$account_id", "customer_account_id"),
99 ("subscription:pro", NO_ACCOUNT_SUBSCRIBER, "$account_id", "customer_account_id"),
100]
101
102# The three spellings of an `eq` a rule can use. All reach the same line.
103EQ_SHAPES = {
104 "bare": lambda value: value,
105 "op-eq": lambda value: {"op": "eq", "value": value},
106 "anded-list": lambda value: [{"op": "eq", "value": value}, {"op": "ne", "value": "zzz"}],
107}
108
109
110@pytest.mark.parametrize("field_state", [MISSING, None], ids=["column-missing", "value-None"])
111@pytest.mark.parametrize("shape", sorted(EQ_SHAPES))
112@pytest.mark.parametrize(
113 "principal, subject, variable, field",
114 UNRESOLVED_VARIABLE_CASES,
115 ids=[f"{c[0]}-{c[2]}-{i}" for i, c in enumerate(UNRESOLVED_VARIABLE_CASES)],
116)
117def test_a_variable_that_resolves_to_nothing_never_matches_a_row_without_the_field(
118 principal, subject, variable, field, shape, field_state
119):
120 """FAILED before the fix (all 66 cases): the rule matched and the subject
121 could read, update and delete every row. Why it matters: the subject here
122 has, by construction, no identity for the rule to be about."""
123 policy = allow_policy(principal, {field: EQ_SHAPES[shape](variable)})
124 # owner_id=7 so that the `owner` principal itself matches and the row
125 # filter is what is under test.
126 record = record_with(field, field_state, **({"owner_id": "7"} if principal == "owner" else {}))
127
128 decision = permissions.check_permission(
129 subject, permissions.READ, policy=policy, collection="things", record=record
130 )
131 if principal != "owner":
132 assert decision.allowed is False, decision
133 for action in (permissions.UPDATE, permissions.DELETE):
134 assert permissions.check_permission(
135 subject, action, policy=policy, collection="things", record=record
136 ).allowed is False
137 else:
138 # An owner keeps their own row either way, so `allowed` cannot tell
139 # the two engines apart here; the reason can. It has to be the owner
140 # fallback, not the account rule that used to match by accident
141 # (reason "owner rule") and would have carried that rule's
142 # fields/denied_fields with it.
143 assert decision.allowed is True
144 assert decision.reason == "record owner"
145
146
147@pytest.mark.parametrize("field_state", [MISSING, None], ids=["column-missing", "value-None"])
148@pytest.mark.parametrize("shape", sorted(EQ_SHAPES))
149@pytest.mark.parametrize(
150 "principal, subject",
151 [("public", ANONYMOUS), ("registered", NO_ACCOUNT), ("account:acme", ACME_MEMBER)],
152 ids=["public", "registered", "account"],
153)
154def test_a_literal_null_filter_value_never_matches_a_row_without_the_field(
155 principal, subject, shape, field_state
156):
157 """FAILED before the fix. A literal null was the same trap as an
158 unresolved variable: it matched every row while the column was absent
159 and no row once it existed. Nothing documented, tested or shipped relied
160 on it, and object_rollups/object_materialize refuse a null filter value
161 outright; this pins that the permission engine now agrees with them."""
162 policy = allow_policy(principal, {"archived_by": EQ_SHAPES[shape](None)})
163 record = record_with("archived_by", field_state)
164
165 for action in WRITE_ACTIONS:
166 assert permissions.check_permission(
167 subject, action, policy=policy, collection="things", record=record
168 ).allowed is False
169
170
171def test_the_documented_account_sharing_rule_was_safe_only_because_of_its_principal():
172 """docs/permissions-model.md shows `account:customer-acme` +
173 `{"customer_account_id": "$account_id"}`. That exact rule was never
174 exploitable -- the principal already requires the account id to be
175 non-None -- but the same row filter under `registered` was (FAILED before
176 the fix), and that is the obvious generalisation ("each customer sees
177 their own invoices") a reader would write next."""
178 invoice = {"id": "i1", "total": "100"} # no customer_account_id column
179
180 documented = allow_policy(
181 "account:customer-acme", {"customer_account_id": "$account_id"}, collection="invoices"
182 )
183 assert permissions.check_permission(
184 NO_ACCOUNT, permissions.READ, policy=documented, collection="invoices", record=invoice
185 ).allowed is False
186
187 generalised = allow_policy(
188 "registered", {"customer_account_id": "$account_id"}, collection="invoices"
189 )
190 assert permissions.check_permission(
191 NO_ACCOUNT, permissions.READ, policy=generalised, collection="invoices", record=invoice
192 ).allowed is False
193
194
195def test_a_multi_field_filter_is_not_carried_by_its_other_fields():
196 """FAILED before the fix: with the identity clause matching by accident,
197 the rule reduced to its literal clause alone."""
198 policy = allow_policy("public", {"status": "open", "owner_id": "$user_id"})
199
200 assert permissions.check_permission(
201 ANONYMOUS, permissions.READ, policy=policy, collection="things",
202 record={"id": "r1", "status": "open"},
203 ).allowed is False
204
205
206def test_a_transition_guard_is_not_satisfied_by_an_identity_that_is_nothing():
207 """FAILED before the fix. Schema transition guards (`when` clauses, 80 of
208 them shipped, all `{"owner_id"|"assigned_to": "$user_id"}`) reuse this
209 evaluator through record_matches_filter, so the same None == None let a
210 subject with no user id make an owner-only move on a row with no owner
211 column."""
212 assert permissions.record_matches_filter({"id": "o1"}, {"owner_id": "$user_id"}, ANONYMOUS) is False
213 assert permissions.record_matches_filter(
214 {"id": "o1", "owner_id": None}, {"owner_id": "$user_id"}, ANONYMOUS
215 ) is False
216
217
218@pytest.mark.parametrize("field_state", [MISSING, None], ids=["column-missing", "value-None"])
219def test_a_deny_rule_does_not_fire_on_an_identity_that_is_nothing(field_state):
220 """FAILED before the fix, in the other direction: the deny rule matched
221 by the same accident and refused a row it had no claim on
222 (over-restrictive, not a leak). Allow and deny share one comparison, so
223 the deny now behaves on a missing column exactly as it always did on an
224 empty one. Why pin it: "nobody may delete their own submission" must not
225 turn into "nobody anonymous may delete anything" depending on whether a
226 column happens to have been written yet."""
227 policy = permissions.PermissionPolicy(
228 access_mode="role_based",
229 rules=(
230 permissions.PermissionRule.deny(
231 "public", [permissions.READ], collection="things", row_filter={"owner_id": "$user_id"}
232 ),
233 permissions.PermissionRule.allow("public", [permissions.READ], collection="things"),
234 ),
235 )
236
237 def decide(record):
238 return permissions.check_permission(
239 ANONYMOUS, permissions.READ, policy=policy, collection="things", record=record
240 ).allowed
241
242 assert decide(record_with("owner_id", field_state)) is True
243 assert decide(record_with("owner_id", "")) is True # always was
244 # ...and the deny still fires for the identity it is actually about.
245 assert permissions.check_permission(
246 NO_ACCOUNT, permissions.READ, policy=policy, collection="things",
247 record=record_with("owner_id", "7"),
248 ).allowed is False
249
250
251# --- what was never affected: pinned so it stays that way --------------------
252
253SET_VARIABLES = [
254 "$accessible_projects",
255 "$owned_projects",
256 "$writable_projects",
257 "$shared_records",
258 "$writable_shared_records",
259]
260
261
262@pytest.mark.parametrize("field_state", [MISSING, None, ""], ids=["missing", "None", "empty"])
263@pytest.mark.parametrize("shape", ["bare", "op-eq", "op-in"])
264@pytest.mark.parametrize("variable", SET_VARIABLES)
265@pytest.mark.parametrize("subject", [ANONYMOUS, NO_ACCOUNT], ids=["anonymous", "no-grants"])
266def test_an_empty_grant_set_matches_no_row(subject, variable, shape, field_state):
267 """Passed before and after: the membership branch always guarded a None
268 field, and an empty set has no "" in it. A user with no project grants
269 must not see the rows that have no project."""
270 value = variable if shape == "bare" else {"op": shape.removeprefix("op-"), "value": variable}
271 policy = allow_policy("public", {"project_id": value})
272
273 assert permissions.check_permission(
274 subject, permissions.READ, policy=policy, collection="things",
275 record=record_with("project_id", field_state),
276 ).allowed is False
277
278
279@pytest.mark.parametrize("field_state", [MISSING, None, ""], ids=["missing", "None", "empty"])
280@pytest.mark.parametrize("value", ["$user_id", "$account_id", None, [None], (None,), ()])
281def test_in_never_matches_a_row_without_the_field(value, field_state):
282 """Passed before and after. `in` is the operator the scalar `eq` now
283 agrees with."""
284 policy = allow_policy("public", {"owner_id": {"op": "in", "value": value}})
285
286 assert permissions.check_permission(
287 ANONYMOUS, permissions.READ, policy=policy, collection="things",
288 record=record_with("owner_id", field_state),
289 ).allowed is False
290
291
292@pytest.mark.parametrize("action", WRITE_ACTIONS)
293def test_the_owner_fallback_never_treated_a_missing_owner_as_the_anonymous_visitor(action):
294 """Passed before and after: _subject_owns refuses a None user id before
295 it compares anything, so neither the `owner` principal nor the
296 record-owner fallback had the None == None problem."""
297 ownerless = {"id": "r1", "name": "x"}
298 private = permissions.PermissionPolicy(access_mode="private")
299 owner_rule = permissions.PermissionPolicy(
300 access_mode="role_based",
301 rules=(permissions.PermissionRule.allow("owner", WRITE_ACTIONS, collection="things"),),
302 )
303
304 for policy in (private, owner_rule):
305 for record in (ownerless, {**ownerless, "owner_id": None}, {**ownerless, "owner_id": ""}):
306 assert permissions.check_permission(
307 ANONYMOUS, action, policy=policy, collection="things", record=record
308 ).allowed is False
309
310
311# --- the normal cases still work ---------------------------------------------
312
313
314@pytest.mark.parametrize("shape", sorted(EQ_SHAPES))
315def test_a_resolved_variable_still_matches_the_row_that_has_it(shape):
316 owner_policy = allow_policy("registered", {"owner_id": EQ_SHAPES[shape]("$user_id")})
317 account_policy = allow_policy("registered", {"customer_account_id": EQ_SHAPES[shape]("$account_id")})
318
319 for action in WRITE_ACTIONS:
320 assert permissions.check_permission(
321 NO_ACCOUNT, action, policy=owner_policy, collection="things",
322 record={"id": "r1", "owner_id": "7"},
323 ).allowed is True
324 assert permissions.check_permission(
325 ACME_MEMBER, action, policy=account_policy, collection="things",
326 record={"id": "r1", "customer_account_id": "acme"},
327 ).allowed is True
328
329
330@pytest.mark.parametrize("stored", ["8", "", MISSING, None], ids=["other", "empty", "missing", "None"])
331def test_a_resolved_variable_still_refuses_every_other_row(stored):
332 """Another value and an empty column were always refused; a missing
333 column was too when the variable resolved (None != "7"). All four are
334 the same answer now for the same reason."""
335 owner_policy = allow_policy("registered", {"owner_id": "$user_id"})
336 account_policy = allow_policy("registered", {"customer_account_id": "$account_id"})
337 other_owner = permissions.PermissionSubject(user_id="9", account_id="acme")
338
339 assert permissions.check_permission(
340 other_owner, permissions.READ, policy=owner_policy, collection="things",
341 record=record_with("owner_id", stored),
342 ).allowed is False
343 assert permissions.check_permission(
344 other_owner, permissions.READ, policy=account_policy, collection="things",
345 record=record_with("customer_account_id", "globex" if stored == "8" else stored),
346 ).allowed is False
347
348
349def test_a_column_present_but_empty_is_refused_for_an_unresolved_variable():
350 """The case that always worked, and the reason the bug hid."""
351 for subject, row_filter in (
352 (ANONYMOUS, {"owner_id": "$user_id"}),
353 (NO_ACCOUNT, {"customer_account_id": "$account_id"}),
354 ):
355 field = next(iter(row_filter))
356 assert permissions.check_permission(
357 subject, permissions.READ, policy=allow_policy("public", row_filter),
358 collection="things", record=record_with(field, ""),
359 ).allowed is False
360
361
362def test_literal_filters_keep_their_meaning():
363 """A literal "" still selects the rows whose field is present and empty
364 ("rows with no project") -- and, as before, not rows of a file that has
365 no such column at all. Literal values and membership are untouched."""
366 subject = ANONYMOUS
367 matches = permissions.record_matches_filter
368
369 assert matches({"project_id": ""}, {"project_id": ""}, subject) is True
370 assert matches({}, {"project_id": ""}, subject) is False
371 assert matches({"project_id": "p1"}, {"project_id": ""}, subject) is False
372 assert matches({"status": "open"}, {"status": "open"}, subject) is True
373 assert matches({"status": "shut"}, {"status": "open"}, subject) is False
374 assert matches({}, {"status": "open"}, subject) is False
375 assert matches({"n": 5}, {"n": "5"}, subject) is True # values compare as strings
376 granted = permissions.PermissionSubject(user_id="8", project_ids=("p1", "p2"))
377 assert matches({"project_id": "p2"}, {"project_id": "$accessible_projects"}, granted) is True
378 assert matches({"project_id": "p3"}, {"project_id": "$accessible_projects"}, granted) is False
379
380
381# --- the comparison table an index planner must mirror -----------------------
382
383SEVEN = permissions.PermissionSubject(user_id="7", project_ids=("p1",))
384
385# (operator shape, expected, subject, {field state: matches?})
386COMPARISON_TABLE = [
387 # eq, scalar. None expected -> never. Otherwise string equality, and a
388 # missing/None field equals nothing.
389 ("eq", "$user_id", ANONYMOUS, {"missing": False, "None": False, "empty": False, "7": False}),
390 ("eq", "$account_id", SEVEN, {"missing": False, "None": False, "empty": False, "7": False}),
391 ("eq", None, SEVEN, {"missing": False, "None": False, "empty": False, "7": False}),
392 ("eq", "$user_id", SEVEN, {"missing": False, "None": False, "empty": False, "7": True}),
393 ("eq", "7", SEVEN, {"missing": False, "None": False, "empty": False, "7": True}),
394 ("eq", "", SEVEN, {"missing": False, "None": False, "empty": True, "7": False}),
395 # eq with a set-valued $-variable is membership.
396 ("eq", "$accessible_projects", ANONYMOUS, {"missing": False, "None": False, "empty": False, "p1": False}),
397 ("eq", "$accessible_projects", SEVEN, {"missing": False, "None": False, "empty": False, "p1": True}),
398 # in: membership over the non-None members; a scalar is a set of one.
399 ("in", "$user_id", ANONYMOUS, {"missing": False, "None": False, "empty": False, "7": False}),
400 ("in", "$user_id", SEVEN, {"missing": False, "None": False, "empty": False, "7": True}),
401 ("in", None, SEVEN, {"missing": False, "None": False, "empty": False, "7": False}),
402 ("in", (), SEVEN, {"missing": False, "None": False, "empty": False, "7": False}),
403 ("in", (None, "7"), SEVEN, {"missing": False, "None": False, "empty": False, "7": True}),
404 ("in", ("", "7"), SEVEN, {"missing": False, "None": False, "empty": True, "7": True}),
405 ("in", "$accessible_projects", ANONYMOUS, {"missing": False, "None": False, "empty": False, "p1": False}),
406 ("in", "$accessible_projects", SEVEN, {"missing": False, "None": False, "empty": False, "p1": True}),
407 # ne: UNCHANGED by the fix. Scalar ne is plain inequality with None as a
408 # value, so a None expected value matches every field that is present
409 # and no field that is absent; set-valued ne matches an absent field.
410 ("ne", "$user_id", ANONYMOUS, {"missing": False, "None": False, "empty": True, "7": True}),
411 ("ne", None, SEVEN, {"missing": False, "None": False, "empty": True, "7": True}),
412 ("ne", "$user_id", SEVEN, {"missing": True, "None": True, "empty": True, "7": False}),
413 ("ne", "", SEVEN, {"missing": True, "None": True, "empty": False, "7": True}),
414 ("ne", "$accessible_projects", ANONYMOUS, {"missing": True, "None": True, "empty": True, "p1": True}),
415 ("ne", "$accessible_projects", SEVEN, {"missing": True, "None": True, "empty": True, "p1": False}),
416 # ordered: a missing/None/blank field against a number bound, or any
417 # field against a None value, cannot be compared (UNKNOWN): an allow
418 # does not match it, and a deny holds -- the one place effect changes
419 # the answer (docs/dron-write-semantics.md S92). It used to be "no
420 # match" for both, which let a deny refuse nothing.
421 ("gte", "$user_id", ANONYMOUS, {"missing": "UNKNOWN", "None": "UNKNOWN", "empty": "UNKNOWN", "7": "UNKNOWN"}),
422 ("gte", "7", SEVEN, {"missing": "UNKNOWN", "None": "UNKNOWN", "empty": "UNKNOWN", "7": True}),
423]
424
425_FIELD_STATES = {"missing": MISSING, "None": None, "empty": ""}
426
427
428def _table_rows():
429 for op, expected, subject, outcomes in COMPARISON_TABLE:
430 for state, matches in outcomes.items():
431 yield pytest.param(
432 op, expected, subject, state, matches,
433 id=f"{op}-{expected!r}-{'anon' if subject is ANONYMOUS else 'user7'}-{state}",
434 )
435
436
437@pytest.mark.parametrize("op, expected, subject, state, matches", list(_table_rows()))
438def test_comparison_table(op, expected, subject, state, matches):
439 """The whole None/missing/empty contract in one place. Only the three
440 `eq`-against-None rows changed with the fix (their "missing" and "None"
441 columns were True); every other row is pinned so that a planner built to
442 mirror this engine has something to be wrong against. Each row is checked
443 in both spellings an `eq` has, and through an allow rule AND a deny rule,
444 because effect must not change what "matches" means -- except for an
445 ordered condition that cannot be compared (UNKNOWN), where an allow does
446 not match and a deny holds."""
447 record = record_with("f", _FIELD_STATES.get(state, state))
448 shapes = [{"op": op, "value": expected}] + ([expected] if op == "eq" else [])
449 deny_matches = True if matches == "UNKNOWN" else matches
450 matches = False if matches == "UNKNOWN" else matches
451
452 for shape in shapes:
453 assert permissions.record_matches_filter(record, {"f": shape}, subject) is matches
454
455 allow = permissions.PermissionPolicy(
456 access_mode="role_based",
457 rules=(permissions.PermissionRule.allow("public", ["read"], collection="t", row_filter={"f": shape}),),
458 )
459 deny = permissions.PermissionPolicy(
460 access_mode="role_based",
461 rules=(
462 permissions.PermissionRule.deny("public", ["read"], collection="t", row_filter={"f": shape}),
463 permissions.PermissionRule.allow("public", ["read"], collection="t"),
464 ),
465 )
466 assert permissions.check_permission(
467 subject, "read", policy=allow, collection="t", record=record
468 ).allowed is matches
469 assert permissions.check_permission(
470 subject, "read", policy=deny, collection="t", record=record
471 ).allowed is (not deny_matches)
472
473
474def test_ne_is_unchanged_and_is_not_the_negation_of_eq_for_a_null_value():
475 """An open question left open on purpose, pinned so that closing it is a
476 decision and not an accident. `eq` against a None value now never
477 matches; `ne` against a None value is still plain inequality, which is
478 False for a missing field. So for a missing column neither
479 `{"owner_id": "$user_id"}` nor `{"owner_id": {"op": "ne", "value":
480 "$user_id"}}` matches an anonymous visitor. Making `ne` the exact
481 negation would turn that second answer to True -- which widens an allow
482 rule, so it is not something a fail-closed fix gets to do in passing."""
483 eq = {"owner_id": {"op": "eq", "value": "$user_id"}}
484 ne = {"owner_id": {"op": "ne", "value": "$user_id"}}
485
486 assert permissions.record_matches_filter({}, eq, ANONYMOUS) is False
487 assert permissions.record_matches_filter({}, ne, ANONYMOUS) is False
488 assert permissions.record_matches_filter({"owner_id": ""}, ne, ANONYMOUS) is True
489
490
491# --- end to end: the collection's file really has no such column -------------
492
493POLICY = {
494 "access_mode": "role_based",
495 "rules": [
496 {"effect": "allow", "principal": "registered", "actions": ["read", "update", "delete"],
497 "collection": "invoices", "row_filter": {"customer_account_id": "$account_id"},
498 "reason": "customers see their own invoices"},
499 {"effect": "allow", "principal": "public", "actions": ["read", "update", "delete"],
500 "collection": "drafts", "row_filter": {"owner_id": "$user_id"},
501 "reason": "your own drafts"},
502 ],
503}
504
505
506def serve(tmp_path, monkeypatch, *, invoices, drafts):
507 data = tmp_path / "data"
508 write_records(data, "invoices", invoices)
509 write_records(data, "drafts", drafts)
510 save_permission_policy(data, POLICY)
511 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data))
512 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
513 monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true")
514 return data
515
516
517def api_key_headers(data, user_id):
518 _, token = object_api_keys.create_api_key(user_id, "script", base_dir=data)
519 return [("authorization", f"Bearer {token}"), ("content-type", "application/json")]
520
521
522def stored_rows(collection):
523 """What is really in the file, read past the permission layer."""
524 return sorted(
525 (record["id"], record["name"])
526 for record in object_records.read_collection_records(
527 collection, base_dir=object_server._data_dir()
528 )
529 )
530
531
532def assert_nothing_is_reachable(collection, headers):
533 """List, read, update and delete, compared in one assertion so that a
534 failure shows every door that was open rather than only the first."""
535 before = stored_rows(collection)
536 assert [row[0] for row in before] == ["a", "b", "c"]
537
538 list_status, _, listed = request(f"/collections/{collection}/records", headers=headers)
539 get_status, _, _ = request(f"/collections/{collection}/records/a", headers=headers)
540 put_status, _, _ = request(
541 f"/collections/{collection}/records/a", method="PUT",
542 body=json.dumps({"name": "changed"}).encode(), headers=headers,
543 )
544 delete_status, _, _ = request(
545 f"/collections/{collection}/records/b", method="DELETE", headers=headers
546 )
547
548 assert {
549 "list": (list_status, [record["id"] for record in listed.get("records", [])]),
550 "get": get_status,
551 "put": put_status,
552 "delete": delete_status,
553 "stored": stored_rows(collection),
554 } == {
555 "list": (200, []),
556 "get": 404, # a row it may not read answers like a missing one
557 "put": 403,
558 "delete": 403,
559 "stored": before,
560 }
561
562
563def test_signed_in_user_with_no_account_reaches_no_invoice_when_the_file_has_no_account_column(
564 tmp_path, monkeypatch
565):
566 """FAILED before the fix: the list returned all three invoices, GET was
567 200, and DELETE removed the row. The file below is what a collection
568 looks like before any record has been written with the column."""
569 data = serve(
570 tmp_path, monkeypatch,
571 invoices="id\tname\na\tone\nb\ttwo\nc\tthree\n",
572 drafts="id\tname\n",
573 )
574
575 assert_nothing_is_reachable("invoices", api_key_headers(data, "dan"))
576
577
578def test_anonymous_visitor_reaches_no_draft_when_the_file_has_no_owner_column(tmp_path, monkeypatch):
579 """FAILED before the fix, same three ways, with no credentials at all."""
580 serve(
581 tmp_path, monkeypatch,
582 invoices="id\tname\n",
583 drafts="id\tname\na\tone\nb\ttwo\nc\tthree\n",
584 )
585
586 assert_nothing_is_reachable("drafts", [("content-type", "application/json")])
587
588
589def test_the_same_files_with_the_column_present_but_empty_were_always_refused(tmp_path, monkeypatch):
590 """Passed before and after -- the control for the two tests above."""
591 data = serve(
592 tmp_path, monkeypatch,
593 invoices="id\tname\tcustomer_account_id\na\tone\t\nb\ttwo\t\nc\tthree\t\n",
594 drafts="id\tname\towner_id\na\tone\t\nb\ttwo\t\nc\tthree\t\n",
595 )
596
597 assert_nothing_is_reachable("invoices", api_key_headers(data, "dan"))
598 assert_nothing_is_reachable("drafts", [("content-type", "application/json")])
599
600
601def test_an_account_member_still_reaches_exactly_their_accounts_invoices(tmp_path, monkeypatch):
602 """Passed before and after: the rule keeps doing what it was written to
603 do once the variable resolves and the row carries the value."""
604 data = serve(
605 tmp_path, monkeypatch,
606 invoices="id\tname\tcustomer_account_id\na\tone\tacme\nb\ttwo\tglobex\nc\tthree\t\n",
607 drafts="id\tname\n",
608 )
609 object_identity.create_account({"account_id": "acme", "name": "Acme"}, base_dir=data)
610 object_identity.create_user({"user_id": "ann", "account_id": "acme"}, base_dir=data)
611 headers = api_key_headers(data, "ann")
612
613 status, _, listed = request("/collections/invoices/records", headers=headers)
614 assert status == 200, listed
615 assert [record["id"] for record in listed["records"]] == ["a"]
616
617 status, _, _ = request("/collections/invoices/records/a", headers=headers)
618 assert status == 200
619 status, _, _ = request("/collections/invoices/records/b", headers=headers)
620 assert status == 404 # a hidden row answers like a missing one
621 status, _, _ = request("/collections/invoices/records/c", headers=headers)
622 assert status == 404 # a hidden row answers like a missing one
623
624 status, _, updated = request(
625 "/collections/invoices/records/a", method="PUT",
626 body=json.dumps({"name": "renamed"}).encode(), headers=headers,
627 )
628 assert status == 200, updated
629 assert updated["record"]["name"] == "renamed"