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/object_permissions.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, 7 minutes ago History
object_permissions.py · 101.9 KB · 2354 lines
1"""Permission primitives for DBBASIC objects and collections.
2
3The object server owns authorization. Scroll can edit and preview permissions,
4but clients should not be trusted to enforce them.
5"""
6
7from __future__ import annotations
8
9import difflib
10import json
11import math
12import re
13from dataclasses import dataclass, field, replace
14import os
15from datetime import datetime, timezone
16from typing import Any, Collection, Iterable, Mapping
17
18from object_namespace import parse_user_object_id
19
20PUBLIC_USER_ID = "public"
21
22# Query/filter operator vocabulary (plan/vocabulary/58-query-filter-spec.md).
23# `eq` is the implicit default everywhere a filter condition omits an
24# operator (a bare literal or $-variable, the pre-existing row-filter/
25# transition-guard shape). The others are additive: `record_matches_filter`
26# below is the ONE evaluator for all of it -- row filters, transition
27# guards, and 58's field filters all reuse it rather than each carrying
28# their own condition matcher.
29FILTER_OPERATORS = frozenset({"eq", "ne", "in", "gte", "lte", "gt", "lt"})
30_ORDERED_FILTER_OPERATORS = frozenset({"gte", "lte", "gt", "lt"})
31# The operators whose answer is "the field's value is one of a known set of
32# strings" (`_equality_match_values` computes the set). They are the only
33# conditions a per-field equality index can answer, so they are the only ones
34# the row-filter planner (`plan_row_filter`) narrows on. One constant, read
35# by the evaluator and by the planner: an operator added here without the
36# helper being taught its set is a visible mistake in one place, where a
37# planner keeping its own list would simply have gone on hiding rows.
38_EQUALITY_FILTER_OPERATORS = frozenset({"eq", "in"})
39
40# The record fields that make a subject the owner of a row: `_subject_owns`
41# reads them, and so does everything that must find "the rows this user
42# owns" without asking the engine about every row (`plan_row_filter`).
43OWNER_KEYS = ("owner_id", "user_id", "created_by")
44
45# The principal of a rule that is not about a subject at all: a deny rule
46# naming it switches the owner fallback off for the rule's actions and
47# resource (see `_owner_fallback_opt_out`). It matches nobody in the deny
48# and allow passes, and it is refused on an allow rule, where it would
49# grant nothing while reading as if it granted something.
50OWNER_FALLBACK = "owner_fallback"
51
52READ = "read"
53CREATE = "create"
54UPDATE = "update"
55DELETE = "delete"
56EXECUTE = "execute"
57SOURCE = "source"
58STATE = "state"
59LOGS = "logs"
60FILES = "files"
61VERSIONS = "versions"
62ADMIN = "admin"
63SHARE = "share"
64
65PUBLIC_READ_ACTIONS = frozenset({READ, EXECUTE})
66OWNER_ACTIONS = frozenset({READ, UPDATE, DELETE, EXECUTE, SOURCE, STATE, LOGS, FILES, VERSIONS, SHARE})
67ADMIN_ACTIONS = frozenset(
68 {READ, CREATE, UPDATE, DELETE, EXECUTE, SOURCE, STATE, LOGS, FILES, VERSIONS, ADMIN, SHARE}
69)
70ACCESS_MODES = frozenset({"public", "password", "registered", "subscription", "role_based", "private"})
71RULE_EFFECTS = frozenset({"allow", "deny"})
72
73
74@dataclass(frozen=True)
75class PermissionSubject:
76 """The authenticated actor being checked.
77
78 ``project_ids`` are the projects shared with this subject and
79 ``writable_project_ids`` narrows that to grants with ``permission ==
80 "write"``; both are resolved by the server from grant records before
81 checks run — the engine itself stays pure and does no IO.
82
83 ``shared_records`` / ``writable_shared_records`` are the generic
84 equivalent for the sharing capability: per-collection sets of record ids
85 granted to this subject via ``record_shares`` (any grant, and write
86 grants). Resolved collection-aware by ``$shared_records`` /
87 ``$writable_shared_records`` in a row filter (the collection being checked
88 is threaded in), so a shared task never leaks a same-id row in another
89 collection.
90 """
91
92 user_id: str | None = None
93 account_id: str | None = None
94 roles: tuple[str, ...] = ()
95 subscriptions: tuple[str, ...] = ()
96 project_ids: tuple[str, ...] = ()
97 owned_project_ids: tuple[str, ...] = ()
98 writable_project_ids: tuple[str, ...] = ()
99 shared_records: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
100 writable_shared_records: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
101
102 @classmethod
103 def anonymous(cls) -> "PermissionSubject":
104 return cls()
105
106 @property
107 def is_authenticated(self) -> bool:
108 return self.user_id is not None
109
110 def with_projects(
111 self,
112 project_ids: Iterable[str],
113 owned_project_ids: Iterable[str] = (),
114 writable_project_ids: Iterable[str] = (),
115 ) -> "PermissionSubject":
116 return replace(
117 self,
118 project_ids=tuple(project_ids),
119 owned_project_ids=tuple(owned_project_ids),
120 writable_project_ids=tuple(writable_project_ids),
121 )
122
123 def with_shares(
124 self,
125 shared_records: Mapping[str, Iterable[str]],
126 writable_shared_records: Mapping[str, Iterable[str]] | None = None,
127 ) -> "PermissionSubject":
128 return replace(
129 self,
130 shared_records={k: tuple(v) for k, v in dict(shared_records).items()},
131 writable_shared_records={
132 k: tuple(v) for k, v in dict(writable_shared_records or {}).items()
133 },
134 )
135
136
137@dataclass(frozen=True)
138class PermissionRule:
139 """One allow/deny rule.
140
141 Principal values intentionally stay stringly and portable:
142 ``public``, ``registered``, ``owner``, ``role:admin``, ``user:42``,
143 ``account:acme``, or ``subscription:pro``.
144 """
145
146 effect: str
147 actions: frozenset[str]
148 principal: str
149 collection: str | None = None
150 object_id: str | None = None
151 row_filter: Mapping[str, Any] = field(default_factory=dict)
152 fields: frozenset[str] | None = None
153 denied_fields: frozenset[str] = field(default_factory=frozenset)
154 valid_from: str | None = None
155 expires_at: str | None = None
156 reason: str = ""
157 package: str | None = None
158 # A create this rule allows may name ANOTHER user in owner_id: staff
159 # entering a record on behalf of a member, donor or patient. Without it a
160 # signed-in create may only own its row itself (see
161 # check_create_on_behalf). Valid only on an allow that covers create, for
162 # a role or a named user (rule_from_dict refuses the rest).
163 on_behalf: bool = False
164 # Set only by apply_fail_closed (DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS):
165 # this stored ALLOW has a serious finding -- a key that would narrow it was
166 # dropped -- and grants nothing; every decision skips it. Never read from
167 # or written to the policy file (rule_from_dict, rule_to_dict), and not
168 # part of a rule's equality: the rule is still the rule the file holds.
169 # Meaningless on a deny, which is applied whatever this says.
170 not_applied: bool = field(default=False, compare=False)
171
172 def __post_init__(self) -> None:
173 if self.on_behalf is not False:
174 _check_on_behalf_rule(self)
175
176 @classmethod
177 def allow(
178 cls,
179 principal: str,
180 actions: Iterable[str],
181 *,
182 collection: str | None = None,
183 object_id: str | None = None,
184 row_filter: Mapping[str, Any] | None = None,
185 fields: Iterable[str] | None = None,
186 denied_fields: Iterable[str] = (),
187 valid_from: str | None = None,
188 expires_at: str | None = None,
189 reason: str = "",
190 on_behalf: bool = False,
191 ) -> "PermissionRule":
192 return cls(
193 effect="allow",
194 principal=principal,
195 actions=frozenset(actions),
196 collection=collection,
197 object_id=object_id,
198 row_filter=dict(row_filter or {}),
199 fields=frozenset(fields) if fields is not None else None,
200 denied_fields=frozenset(denied_fields),
201 valid_from=valid_from,
202 expires_at=expires_at,
203 reason=reason,
204 on_behalf=on_behalf,
205 )
206
207 @classmethod
208 def deny(
209 cls,
210 principal: str,
211 actions: Iterable[str],
212 *,
213 collection: str | None = None,
214 object_id: str | None = None,
215 row_filter: Mapping[str, Any] | None = None,
216 valid_from: str | None = None,
217 expires_at: str | None = None,
218 reason: str = "",
219 ) -> "PermissionRule":
220 return cls(
221 effect="deny",
222 principal=principal,
223 actions=frozenset(actions),
224 collection=collection,
225 object_id=object_id,
226 row_filter=dict(row_filter or {}),
227 valid_from=valid_from,
228 expires_at=expires_at,
229 reason=reason,
230 )
231
232
233@dataclass(frozen=True)
234class PermissionPolicy:
235 """Portable server-side permission state.
236
237 ``roles`` names broad roles such as ``admin`` or ``sales``. ``user_roles``
238 assigns users to roles. ``rules`` contains grants and explicit denies.
239 """
240
241 access_mode: str = "role_based"
242 roles: Mapping[str, Mapping[str, Any]] = field(default_factory=dict)
243 user_roles: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
244 rules: tuple[PermissionRule, ...] = ()
245 admin_roles: tuple[str, ...] = ("admin", "superuser")
246
247
248@dataclass(frozen=True)
249class PermissionDecision:
250 """The result Scroll and the server can explain."""
251
252 allowed: bool
253 reason: str
254 code: str
255 http_status: int
256 row_filter: Mapping[str, Any] = field(default_factory=dict)
257 fields: frozenset[str] | None = None
258 denied_fields: frozenset[str] = field(default_factory=frozenset)
259
260 @classmethod
261 def allow(
262 cls,
263 reason: str,
264 *,
265 row_filter: Mapping[str, Any] | None = None,
266 fields: Iterable[str] | None = None,
267 denied_fields: Iterable[str] = (),
268 ) -> "PermissionDecision":
269 return cls(
270 True,
271 reason,
272 "allowed",
273 200,
274 row_filter=dict(row_filter or {}),
275 fields=frozenset(fields) if fields is not None else None,
276 denied_fields=frozenset(denied_fields),
277 )
278
279 @classmethod
280 def deny(
281 cls,
282 reason: str,
283 *,
284 code: str = "forbidden",
285 http_status: int = 403,
286 ) -> "PermissionDecision":
287 return cls(False, reason, code, http_status)
288
289
290def check_permission(
291 subject: PermissionSubject | None,
292 action: str,
293 *,
294 policy: PermissionPolicy | None = None,
295 collection: str | None = None,
296 object_id: str | None = None,
297 record: Mapping[str, Any] | None = None,
298 now: datetime | None = None,
299) -> PermissionDecision:
300 """Return allow/deny/reason for one action.
301
302 If a matching allow rule has a row filter and no record was supplied, the
303 decision is allowed with the filter attached so list/query code can apply it.
304 """
305
306 actor = subject or PermissionSubject.anonymous()
307 normalized_action = action.lower()
308 explicit_policy = policy is not None
309 active_policy = policy or PermissionPolicy(access_mode="public")
310 roles = _subject_roles(actor, active_policy)
311 checked_at = now or datetime.now(timezone.utc)
312
313 if _has_admin_role(roles, active_policy):
314 return PermissionDecision.allow("admin role")
315
316 explicit_deny = _matching_rule(
317 active_policy.rules,
318 actor,
319 roles,
320 normalized_action,
321 collection=collection,
322 object_id=object_id,
323 record=record,
324 effect="deny",
325 now=checked_at,
326 )
327 if explicit_deny is not None:
328 return PermissionDecision.deny(explicit_deny.reason or "explicit deny")
329
330 mode_decision = _access_mode_decision(
331 actor,
332 active_policy.access_mode,
333 normalized_action,
334 collection=collection,
335 object_id=object_id,
336 )
337 if mode_decision.allowed:
338 return mode_decision
339
340 allow_rule = _matching_rule(
341 active_policy.rules,
342 actor,
343 roles,
344 normalized_action,
345 collection=collection,
346 object_id=object_id,
347 record=record,
348 effect="allow",
349 now=checked_at,
350 )
351 if allow_rule is not None:
352 return PermissionDecision.allow(
353 allow_rule.reason or f"{allow_rule.principal} rule",
354 row_filter=allow_rule.row_filter,
355 fields=allow_rule.fields,
356 denied_fields=allow_rule.denied_fields,
357 )
358
359 fallback = _owner_fallback(
360 actor,
361 normalized_action,
362 object_id=object_id,
363 record=record,
364 allow_system_public=not explicit_policy or active_policy.access_mode == "public",
365 )
366 if fallback.allowed:
367 opt_out = _owner_fallback_opt_out(
368 active_policy.rules,
369 actor,
370 normalized_action,
371 collection=collection,
372 object_id=object_id,
373 record=record,
374 now=checked_at,
375 )
376 if opt_out is None:
377 return fallback
378 return PermissionDecision.deny(
379 opt_out.reason or "the owner fallback is switched off for this resource"
380 )
381
382 return mode_decision
383
384
385def subject_from_dict(payload: Mapping[str, Any] | None) -> PermissionSubject:
386 """Build a subject from JSON-compatible data."""
387 if payload is None:
388 return PermissionSubject.anonymous()
389 if not isinstance(payload, Mapping):
390 raise ValueError("Permission subject must be an object")
391
392 return PermissionSubject(
393 user_id=_optional_string(payload.get("user_id")),
394 account_id=_optional_string(payload.get("account_id")),
395 roles=_string_tuple(payload.get("roles", ()), "subject.roles"),
396 subscriptions=_string_tuple(payload.get("subscriptions", ()), "subject.subscriptions"),
397 project_ids=_string_tuple(payload.get("project_ids", ()), "subject.project_ids"),
398 owned_project_ids=_string_tuple(
399 payload.get("owned_project_ids", ()), "subject.owned_project_ids"
400 ),
401 writable_project_ids=_string_tuple(
402 payload.get("writable_project_ids", ()), "subject.writable_project_ids"
403 ),
404 )
405
406
407def rule_from_dict(payload: Mapping[str, Any]) -> PermissionRule:
408 """Build one rule from JSON-compatible data."""
409 if not isinstance(payload, Mapping):
410 raise ValueError("Permission rule must be an object")
411
412 effect = _required_string(payload, "effect").lower()
413 if effect not in RULE_EFFECTS:
414 raise ValueError(f"Permission rule effect must be one of: {', '.join(sorted(RULE_EFFECTS))}")
415
416 actions = _string_set(payload.get("actions"), "rule.actions")
417 if not actions:
418 raise ValueError("Permission rule actions must not be empty")
419
420 principal = _required_string(payload, "principal")
421 if principal == OWNER_FALLBACK and effect != "deny":
422 raise ValueError(
423 "Permission rule principal 'owner_fallback' is only valid on a deny rule: "
424 "it switches the owner fallback off and cannot grant anything"
425 )
426 row_filter = payload.get("row_filter", {})
427 if not isinstance(row_filter, Mapping):
428 raise ValueError("Permission rule row_filter must be an object")
429
430 fields_payload = payload.get("fields")
431 fields = _string_set(fields_payload, "rule.fields") if fields_payload is not None else None
432 denied_fields = _string_set(payload.get("denied_fields", ()), "rule.denied_fields")
433
434 on_behalf = payload.get("on_behalf", False)
435 if not isinstance(on_behalf, bool):
436 # "yes" or 1 would read as a grant to a reviewer and as nothing (or
437 # everything) to a parser; only the JSON literal counts.
438 raise ValueError("Permission rule on_behalf must be true or false")
439
440 return PermissionRule(
441 effect=effect,
442 actions=frozenset(actions),
443 principal=principal,
444 collection=_optional_string(payload.get("collection")),
445 object_id=_optional_string(payload.get("object_id")),
446 row_filter=dict(row_filter),
447 fields=frozenset(fields) if fields is not None else None,
448 denied_fields=frozenset(denied_fields),
449 valid_from=_optional_string(payload.get("valid_from")),
450 expires_at=_optional_string(payload.get("expires_at")),
451 reason=_optional_string(payload.get("reason")) or "",
452 package=_optional_string(payload.get("package")),
453 on_behalf=on_behalf,
454 )
455
456
457# --- what a package may DECLARE (DRON 0.1, dron/dron-permissions.schema.json) ---
458#
459# rule_from_dict is deliberately forgiving: it also reads the deployment's
460# own policy file and every rule a box has recorded, and a box must not stop
461# serving because a stored rule carries an old key. A package's rules file
462# is different. It is a declaration somebody is about to install, and every
463# laxity there was a way to install a rule that does not do what it says:
464#
465# - a misspelt `row_filter` was dropped, so the rule covered EVERY row
466# (an allow silently widened);
467# - `"principal": "admin"` (meaning role:admin) matched nobody;
468# - `"$userid"` was read as a literal that never matches, so an allow hid
469# every row and a deny hid none;
470# - `{"is_public": true}` compared "True" with the stored "true";
471# - an unknown operator loaded fine and raised on the first request.
472#
473# check_rule_declaration refuses all of these at install, before anything
474# is written (object_packages._load_permission_fragment). The vocabulary is
475# the schema's; tests/test_dron_schema.py holds the two side by side.
476
477RULE_KEYS = frozenset({
478 "effect", "principal", "actions", "collection", "object_id", "row_filter",
479 "fields", "denied_fields", "valid_from", "expires_at", "on_behalf", "reason",
480 # Provenance the installer writes over; tolerated so a rule copied out of
481 # a policy file reads back.
482 "package",
483})
484RULE_ACTIONS = ADMIN_ACTIONS | {"*"}
485FILTER_VARIABLES = frozenset({
486 "$user_id", "$account_id", "$accessible_projects", "$owned_projects",
487 "$writable_projects", "$shared_records", "$writable_shared_records",
488})
489_STATIC_PRINCIPALS = ("public", "registered", "owner", OWNER_FALLBACK)
490_PRINCIPAL_PREFIXES = ("role:", "user:", "account:", "subscription:")
491_DECLARED_NAME_RE = re.compile(r"^[A-Za-z0-9_]{1,64}$")
492_DECLARED_FIELD_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
493_DECLARED_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}")
494
495
496def did_you_mean(value: str, choices: Iterable[str]) -> str:
497 """' (did you mean 'x'?)' for the closest spelling, or ''."""
498 match = difflib.get_close_matches(value, sorted(choices), n=1, cutoff=0.6)
499 return f" (did you mean {match[0]!r}?)" if match else ""
500
501
502def check_rule_declaration(payload: Any) -> None:
503 """Refuse a declared rule DRON refuses; raise ValueError naming the key.
504
505 Stricter than rule_from_dict on purpose (see the note above RULE_KEYS):
506 unknown keys, unknown actions, principals, operators and $-variables,
507 capitalised effects and every value of the wrong type are errors rather
508 than something read loosely. The message names the key path inside the
509 rule; the caller adds which file and which rule.
510 """
511 if not isinstance(payload, Mapping):
512 raise ValueError("a rule must be an object")
513 for key in payload:
514 if key not in RULE_KEYS:
515 raise ValueError(f"unknown key {key!r}{did_you_mean(str(key), RULE_KEYS)}")
516 for key in ("effect", "principal", "actions"):
517 if key not in payload:
518 raise ValueError(f"'{key}' is required")
519
520 effect = payload["effect"]
521 if effect not in RULE_EFFECTS:
522 hint = f" (DRON spells it {effect.lower()!r})" if isinstance(effect, str) and effect.lower() in RULE_EFFECTS else ""
523 raise ValueError(f"effect {effect!r} is not 'allow' or 'deny'{hint}")
524
525 principal = payload["principal"]
526 if not isinstance(principal, str) or not (
527 principal in _STATIC_PRINCIPALS
528 or any(principal.startswith(prefix) and len(principal) > len(prefix) for prefix in _PRINCIPAL_PREFIXES)
529 ):
530 hint = ""
531 if isinstance(principal, str) and principal and ":" not in principal:
532 hint = did_you_mean(principal, _STATIC_PRINCIPALS) or f" (did you mean 'role:{principal}'?)"
533 raise ValueError(
534 f"principal {principal!r} is not public, registered, owner, owner_fallback "
535 f"or role:/user:/account:/subscription:<name>{hint}"
536 )
537
538 actions = payload["actions"]
539 if not isinstance(actions, list) or not actions:
540 raise ValueError("'actions' must be a non-empty list")
541 for action in actions:
542 if action not in RULE_ACTIONS:
543 hint = did_you_mean(action, RULE_ACTIONS) if isinstance(action, str) else ""
544 raise ValueError(f"actions: {action!r} is not an action{hint}")
545 if len(set(actions)) != len(actions):
546 raise ValueError("actions: an action is listed twice")
547
548 for key in ("collection", "object_id"):
549 if key in payload and not (isinstance(payload[key], str) and _DECLARED_NAME_RE.fullmatch(payload[key])):
550 raise ValueError(f"{key} {payload[key]!r} is not a name (letters, digits, underscores)")
551 for key in ("fields", "denied_fields"):
552 if key in payload:
553 value = payload[key]
554 if not isinstance(value, list) or not all(
555 isinstance(item, str) and _DECLARED_FIELD_RE.fullmatch(item) for item in value
556 ):
557 raise ValueError(f"'{key}' must be a list of field names")
558 for key in ("valid_from", "expires_at"):
559 if key in payload:
560 value = payload[key]
561 if not isinstance(value, str) or not _DECLARED_DATE_RE.match(value) or _parse_timestamp(value) is None:
562 raise ValueError(
563 f"{key} {value!r} is not an ISO-8601 date or timestamp (an unparseable "
564 "bound makes the rule never apply)"
565 )
566 if "reason" in payload and not isinstance(payload["reason"], str):
567 raise ValueError("'reason' must be text")
568 if "package" in payload and not isinstance(payload["package"], str):
569 raise ValueError("'package' must be text")
570 if "on_behalf" in payload and not isinstance(payload["on_behalf"], bool):
571 raise ValueError("on_behalf must be true or false")
572 if "row_filter" in payload:
573 check_row_filter_declaration(payload["row_filter"], where="row_filter")
574
575
576def check_row_filter_declaration(row_filter: Any, *, where: str) -> None:
577 """Refuse a declared row filter outside DRON's row-filter language.
578
579 `where` is the key path for the message ("row_filter")."""
580 if not isinstance(row_filter, Mapping):
581 raise ValueError(f"{where} must be an object of field: test")
582 for name, test in row_filter.items():
583 at = f"{where}.{name}"
584 if not isinstance(name, str) or not _DECLARED_FIELD_RE.fullmatch(name):
585 raise ValueError(f"{where}: {name!r} is not a field name")
586 if isinstance(test, list):
587 if not test:
588 raise ValueError(f"{at}: an empty list of conditions")
589 for index, condition in enumerate(test):
590 if not isinstance(condition, Mapping):
591 raise ValueError(
592 f"{at}[{index}]: a list holds conditions like "
593 '{"op": "gte", "value": ...}; for one of several values use {"op": "in", "value": [...]}'
594 )
595 _check_filter_condition(condition, where=f"{at}[{index}]")
596 elif isinstance(test, Mapping):
597 _check_filter_condition(test, where=at)
598 else:
599 _check_filter_operand(test, where=at)
600
601
602def _check_filter_operand(value: Any, *, where: str) -> None:
603 if isinstance(value, bool):
604 raise ValueError(
605 f"{where}: {value!r} is not a filter value: stored booleans are the text "
606 f'"true" and "false", so write "{str(value).lower()}"'
607 )
608 if isinstance(value, (int, float)):
609 if not math.isfinite(value):
610 raise ValueError(f"{where}: {value!r} is not a finite number")
611 return
612 if not isinstance(value, str):
613 raise ValueError(f"{where}: {value!r} is not a string, number or $-variable")
614 if value.startswith("$") and value not in FILTER_VARIABLES:
615 raise ValueError(
616 f"{where}: {value!r} is not a $-variable{did_you_mean(value, FILTER_VARIABLES)} "
617 "(any other text starting with $ would be compared literally and never match)"
618 )
619
620
621def _check_filter_condition(condition: Mapping[str, Any], *, where: str) -> None:
622 for key in condition:
623 if key not in ("op", "value"):
624 raise ValueError(f"{where}: unknown key {key!r}{did_you_mean(str(key), ('op', 'value'))}")
625 op = condition.get("op")
626 if op not in FILTER_OPERATORS:
627 hint = did_you_mean(op, FILTER_OPERATORS) if isinstance(op, str) else ""
628 raise ValueError(f"{where}: op {op!r} is not one of {', '.join(sorted(FILTER_OPERATORS))}{hint}")
629 if "value" not in condition:
630 raise ValueError(f"{where}: op {op!r} needs a value")
631 value = condition["value"]
632 if op == "in":
633 if isinstance(value, str) and value in FILTER_VARIABLES:
634 return
635 if not isinstance(value, list) or not value:
636 raise ValueError(f"{where}: op 'in' needs a non-empty list or a set-valued $-variable")
637 for index, item in enumerate(value):
638 _check_filter_operand(item, where=f"{where}.value[{index}]")
639 return
640 if value is None:
641 if op == "ne":
642 return
643 raise ValueError(f"{where}: op {op!r} with null matches no row")
644 _check_filter_operand(value, where=f"{where}.value")
645
646
647# --- what an operator may SAVE as the deployment's policy ---------------------
648#
649# The deployment policy (data/permissions/policy.json, dron/dron-policy.schema
650# .json) has two moments, held to different standards:
651#
652# - SAVING it (PUT /permissions/policy, object_permission_store.replace_
653# policy) is a new write by an operator, so it is held to DRON the way a
654# package's rules file is: the same check_rule_declaration for every rule
655# the operator wrote, plus the policy's own keys. Rules already in the
656# stored policy are not re-judged (see policy_declaration_problems), so a
657# policy the server produced saves back -- unless the stored file holds a
658# serious finding the save would write back widened (widened_findings_kept).
659# - READING the stored file stays lenient (policy_from_dict, rule_from_
660# dict): a box never stops serving, and never changes a decision, over
661# its own file. stored_policy_findings says what the engine is doing with
662# each such mistake, for /admin/status, /permissions/status, /permissions/
663# unshipped and the startup log.
664# - One thing an operator can switch on (off by default):
665# DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS makes a stored ALLOW with a
666# serious finding grant nothing (apply_fail_closed, applied by
667# object_permission_store.load_policy). Deny rules are never touched; the
668# deny side is the owner's open decision (docs/dron.md).
669
670POLICY_KEYS = frozenset({"$schema", "access_mode", "roles", "user_roles", "admin_roles", "rules"})
671
672# Keys that NARROW an allow rule: dropping one (a misspelling the engine
673# ignores) makes the allow apply more widely than written. What it then does:
674_NARROWING_RULE_KEYS = {
675 "row_filter": "to every row, not only the rows the filter was meant to pick",
676 "collection": "to every collection",
677 "object_id": "to every object",
678 "fields": "to every field of a row",
679 "denied_fields": "without hiding any field",
680 "valid_from": "from now on, not from the date given",
681 "expires_at": "for ever, not until the date given",
682}
683_PROBE_RULE = {"effect": "allow", "principal": "public", "actions": ["read"]}
684_NAMES_ARE = "letters, digits and underscores"
685
686
687class PolicyDeclarationError(ValueError):
688 """A policy an operator is saving that DRON refuses. `problems` holds one
689 dict per mistake: index (the rule's position, None for the policy's own
690 keys), package (the rule's tag or None), key and message."""
691
692 def __init__(self, problems: list[dict[str, Any]]):
693 self.problems = problems
694 shown = "; ".join(_problem_text(problem) for problem in problems[:5])
695 more = f"; and {len(problems) - 5} more" if len(problems) > 5 else ""
696 super().__init__(
697 f"Permission policy refused, nothing was saved: {shown}{more}. "
698 "A saved policy is held to DRON (dron/dron-policy.schema.json, docs/dron.md)."
699 )
700
701
702def _problem_text(problem: Mapping[str, Any]) -> str:
703 return f"{_where(problem)}: {problem['message']}"
704
705
706def _where(problem: Mapping[str, Any]) -> str:
707 if problem.get("index") is None:
708 return "policy" if not problem.get("key") else f"policy key {problem['key']!r}"
709 package = f" (package {problem['package']})" if problem.get("package") else ""
710 return f"rule {problem['index']}{package}"
711
712
713def rule_declaration_problems(payload: Any) -> list[tuple[str, str]]:
714 """(key, message) for every key of one rule that check_rule_declaration
715 refuses; empty exactly when check_rule_declaration accepts the rule.
716
717 Each key is checked alone (on an otherwise minimal rule) by the very
718 same check, so a rule with several mistakes reports each of them rather
719 than the first."""
720 if not isinstance(payload, Mapping):
721 return [("", "a rule must be an object")]
722 problems: list[tuple[str, str]] = []
723 for key in ("effect", "principal", "actions"):
724 if key not in payload:
725 problems.append((key, f"'{key}' is required"))
726 for key, value in payload.items():
727 probe = {**_PROBE_RULE, key: value}
728 try:
729 check_rule_declaration(probe)
730 except ValueError as exc:
731 problems.append((str(key), str(exc)))
732 if not problems:
733 try:
734 check_rule_declaration(payload)
735 except ValueError as exc: # a check across keys, if one is ever added
736 problems.append(("", str(exc)))
737 return problems
738
739
740def _policy_key_problems(payload: Mapping[str, Any]) -> list[tuple[str, str]]:
741 """(key, message) for the policy's own keys (everything but the rules)."""
742 problems: list[tuple[str, str]] = []
743 for key in payload:
744 if key not in POLICY_KEYS:
745 problems.append((str(key), f"unknown key {key!r}{did_you_mean(str(key), POLICY_KEYS)}"))
746 if "$schema" in payload and not isinstance(payload["$schema"], str):
747 problems.append(("$schema", "'$schema' must be text"))
748 if "access_mode" in payload and payload["access_mode"] not in ACCESS_MODES:
749 mode = payload["access_mode"]
750 hint = did_you_mean(mode, ACCESS_MODES) if isinstance(mode, str) and mode else ""
751 problems.append(("access_mode", f"access_mode {mode!r} is not one of "
752 f"{', '.join(sorted(ACCESS_MODES))}{hint}"))
753 roles = payload.get("roles", {})
754 if not isinstance(roles, Mapping) or not all(
755 isinstance(name, str) and name and isinstance(meta, Mapping) for name, meta in roles.items()
756 ):
757 problems.append(("roles", "'roles' must be an object of role name: {display metadata}"))
758 user_roles = payload.get("user_roles", {})
759 if not isinstance(user_roles, Mapping):
760 problems.append(("user_roles", "'user_roles' must be an object of user id: [role names]"))
761 else:
762 bad = sum(1 for user, held in user_roles.items() if not (
763 isinstance(user, str) and user and _is_name_list(held)))
764 if bad:
765 problems.append(("user_roles", f"{bad} user(s) have roles that are not a list of "
766 "role names, each written once as text"))
767 if "admin_roles" in payload and not _is_name_list(payload["admin_roles"]):
768 problems.append(("admin_roles", "'admin_roles' must be a list of role names, each written once as text"))
769 rules = payload.get("rules", [])
770 if not isinstance(rules, list):
771 problems.append(("rules", "'rules' must be a list"))
772 return problems
773
774
775def _is_name_list(value: Any) -> bool:
776 return (isinstance(value, list) and all(isinstance(item, str) and item for item in value)
777 and len(set(value)) == len(value))
778
779
780def canonical_rule_key(payload: Any) -> str | None:
781 """The rule as the engine reads it, as one comparable string, or None
782 when the engine cannot read it. Two rules with the same key decide the
783 same things."""
784 try:
785 rule = rule_from_dict(payload)
786 except (ValueError, TypeError):
787 return None
788 return json.dumps(rule_to_dict(rule), sort_keys=True, separators=(",", ":"), default=str)
789
790
791def policy_declaration_problems(
792 payload: Any,
793 *,
794 stored_rules: Iterable[Any] = (),
795) -> list[dict[str, Any]]:
796 """Every mistake in a policy an operator is saving that DRON refuses.
797
798 `stored_rules` are the rules of the policy being replaced, as stored. A
799 rule the engine reads exactly as it reads one of them (same canonical_
800 rule_key) is not judged again: it is not something the operator just
801 wrote, and the save must not fail over it -- GET /permissions/policy then
802 PUT back unchanged passes this check, on a box carrying package rules
803 from an older release as much as on a new one (a serious finding kept
804 widened is refused separately: widened_findings_kept). Such a rule is reported at
805 read instead (stored_policy_findings). A rule carrying a key the engine
806 does not know is always judged: saving it would drop the key silently,
807 which is the mistake this check exists for.
808 """
809 if not isinstance(payload, Mapping):
810 return [{"index": None, "package": None, "key": "", "message": "a policy must be an object"}]
811 problems = [
812 {"index": None, "package": None, "key": key, "message": message}
813 for key, message in _policy_key_problems(payload)
814 ]
815 rules = payload.get("rules", [])
816 if not isinstance(rules, list):
817 return problems
818 kept = {key for key in (canonical_rule_key(rule) for rule in stored_rules) if key is not None}
819 for index, rule in enumerate(rules):
820 if (isinstance(rule, Mapping) and set(rule) <= RULE_KEYS
821 and canonical_rule_key(rule) in kept):
822 continue
823 package = rule.get("package") if isinstance(rule, Mapping) else None
824 for key, message in rule_declaration_problems(rule):
825 problems.append({
826 "index": index,
827 "package": package if isinstance(package, str) else None,
828 "key": key,
829 "message": message,
830 })
831 return problems
832
833
834def check_policy_declaration(payload: Any, *, stored_rules: Iterable[Any] = ()) -> None:
835 """Raise PolicyDeclarationError (a ValueError) for a policy an operator
836 may not save; see policy_declaration_problems."""
837 problems = policy_declaration_problems(payload, stored_rules=stored_rules)
838 if problems:
839 raise PolicyDeclarationError(problems)
840
841
842class WidenedRuleKeptError(PolicyDeclarationError):
843 """A save that would write a serious stored finding back in its widened
844 form. `problems` holds the findings (index, package, key, message,
845 today, fix, serious), indexes as in the STORED policy."""
846
847 def __init__(self, findings: list[dict[str, Any]]):
848 self.problems = findings
849 shown = "; ".join(f"{finding_text(f)}" for f in findings[:5])
850 more = f"; and {len(findings) - 5} more" if len(findings) > 5 else ""
851 ValueError.__init__(
852 self,
853 "Permission policy refused, nothing was saved: the stored policy has a mistake that "
854 f"lets it allow more than written, and this save would write it back as meant: {shown}{more}. "
855 "Fix or remove that rule in the same save (GET /permissions/status lists it); "
856 "nothing else in the save is refused for it.",
857 )
858
859
860def widened_findings_kept(stored_payload: Any, incoming_payload: Any) -> list[dict[str, Any]]:
861 """The serious findings of the stored policy that a save of
862 `incoming_payload` would write back in the form the engine reads them
863 today -- which would turn "a typo nobody decided" into "written", and
864 erase the report.
865
866 - a rule finding is kept when an incoming rule reads (canonical_rule_
867 key) exactly as the stored rule reads now: the widened form;
868 - a finding about an ignored policy key (`rulez`, `admin_role`) is kept
869 when the incoming key it was meant as holds what the engine reads
870 today (no rules from it; the default admin roles).
871
872 Fixing or removing the rule, or saving a policy whose stored file has no
873 serious finding, returns []. Non-serious findings never count.
874 """
875 serious = [f for f in stored_policy_findings(stored_payload) if f["serious"]]
876 if not serious or not isinstance(incoming_payload, Mapping):
877 return []
878 incoming_rules = incoming_payload.get("rules", [])
879 incoming_keys = {canonical_rule_key(rule) for rule in incoming_rules} if isinstance(incoming_rules, list) else set()
880 stored_policy = policy_from_dict(stored_payload)
881 kept = []
882 for finding in serious:
883 if finding["index"] is not None:
884 if canonical_rule_key(stored_payload["rules"][finding["index"]]) in incoming_keys:
885 kept.append(finding)
886 continue
887 meant = difflib.get_close_matches(finding["key"], sorted(POLICY_KEYS), n=1, cutoff=0.6)
888 if meant == ["rules"]:
889 today = sorted(json.dumps(rule_to_dict(rule), sort_keys=True) for rule in stored_policy.rules)
890 try:
891 incoming = sorted(json.dumps(rule_to_dict(rule_from_dict(rule)), sort_keys=True)
892 for rule in incoming_rules)
893 except (ValueError, TypeError):
894 continue
895 if incoming == today:
896 kept.append(finding)
897 elif meant == ["admin_roles"]:
898 admin = incoming_payload.get("admin_roles", ("admin", "superuser"))
899 if isinstance(admin, list) and sorted(admin) == sorted(stored_policy.admin_roles):
900 kept.append(finding)
901 return kept
902
903
904FAIL_CLOSED_WIDENED_ALLOWS_ENV = "DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS"
905_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
906_NOT_APPLIED = "this rule is not applied"
907_APPLIED_WIDELY = (
908 "this rule applies more widely than written; set "
909 f"{FAIL_CLOSED_WIDENED_ALLOWS_ENV} to stop applying it"
910)
911
912
913def fail_closed_widened_allows(env: Mapping[str, str] | None = None) -> bool:
914 """Is DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS on? Off unless set to 1,
915 true, yes or on. When on, a stored allow rule with a serious finding
916 grants nothing (apply_fail_closed); deny rules are never touched."""
917 source = os.environ if env is None else env
918 return str(source.get(FAIL_CLOSED_WIDENED_ALLOWS_ENV, "") or "").strip().lower() in _TRUE_VALUES
919
920
921def widened_allow_indexes(payload: Any, policy: PermissionPolicy | None = None) -> frozenset[int]:
922 """The positions of the stored ALLOW rules that carry a serious finding:
923 the rules the fail-closed setting stops applying. An allow is what the
924 engine reads as one (the parsed rule's effect), so a deny is never in
925 here. Raises what stored_policy_findings' parts raise; a caller deciding
926 from it must fail closed on that (object_permission_store.load_policy)."""
927 parsed = policy_from_dict(payload) if policy is None else policy
928 found = set()
929 for problem in policy_declaration_problems(payload):
930 index = problem["index"]
931 if index is None or parsed.rules[index].effect != "allow":
932 continue
933 if _explain_problem(problem, payload["rules"][index])[0]:
934 found.add(index)
935 return frozenset(found)
936
937
938def apply_fail_closed(policy: PermissionPolicy, payload: Any) -> PermissionPolicy:
939 """`policy` (policy_from_dict(payload)) with every stored allow rule that
940 has a serious finding marked not_applied, so no decision is made from
941 it. The rules stay in place and serialise as before: GET /permissions/
942 policy still shows them and a save still has to fix them. Deny rules and
943 rules without a serious finding are returned as they are; a policy with
944 none is returned as the same object."""
945 indexes = widened_allow_indexes(payload, policy)
946 if not indexes:
947 return policy
948 return replace(policy, rules=tuple(
949 replace(rule, not_applied=True) if index in indexes else rule
950 for index, rule in enumerate(policy.rules)))
951
952
953def stored_policy_findings(payload: Any, *, fail_closed: bool | None = None) -> list[dict[str, Any]]:
954 """What the engine does today with each DRON mistake in a STORED policy.
955
956 A serious finding on an ALLOW rule says which of two things holds
957 (`fail_closed`, read from DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS when
958 None): with the setting on the rule is not applied and `applied` is
959 False; with it off the rule applies more widely than written. Nothing
960 else here depends on the setting, and a deny is applied either way.
961
962 Changes nothing itself: the file is read exactly as before
963 (policy_from_dict). Each finding names the rule (index, package tag),
964 the key, the check's message, `today` (what the engine does with it, in
965 plain words), `fix`, and `serious` -- True when the mistake makes the
966 policy allow MORE than written: a key that narrows an allow is ignored,
967 a deny can never apply, or the rules list itself is ignored. Never
968 carries a rule's `reason` text or a user id. Empty for a policy the
969 engine refuses outright (the policy-invalid alert covers that).
970 """
971 try:
972 policy = policy_from_dict(payload)
973 except (ValueError, TypeError):
974 return []
975 if fail_closed is None:
976 fail_closed = fail_closed_widened_allows()
977 findings = []
978 for problem in policy_declaration_problems(payload):
979 rule = None
980 if problem["index"] is not None:
981 rule = payload["rules"][problem["index"]]
982 serious, today, fix = _explain_problem(problem, rule)
983 finding = {**problem, "serious": serious, "today": today, "fix": fix}
984 if serious and rule is not None and policy.rules[problem["index"]].effect == "allow":
985 if fail_closed:
986 finding["today"] = (today.replace("so this allow applies", "so this allow would apply")
987 + f"; {_NOT_APPLIED}")
988 else:
989 finding["today"] = f"{today}; {_APPLIED_WIDELY}"
990 finding["applied"] = not fail_closed
991 findings.append(finding)
992 findings.sort(key=lambda finding: not finding["serious"])
993 return findings
994
995
996def finding_text(finding: Mapping[str, Any]) -> str:
997 """One line for a log or an alert: where, which key, what happens, how
998 to fix it. Built from the finding's own fields only."""
999 key = f" key {finding['key']!r}" if finding.get("key") and finding.get("index") is not None else ""
1000 return f"{_where(finding)}{key}: {finding['today']}; {finding['fix']}"
1001
1002
1003def _explain_problem(problem: Mapping[str, Any], rule: Any) -> tuple[bool, str, str]:
1004 """(serious, today, fix) for one problem of a policy the engine reads."""
1005 key = problem["key"]
1006 message = problem["message"]
1007 if rule is None:
1008 return _explain_policy_key(key, message)
1009 effect = str(rule.get("effect", "")).lower()
1010 deny = effect == "deny"
1011 value = rule.get(key)
1012 if key not in RULE_KEYS:
1013 match = difflib.get_close_matches(key, sorted(RULE_KEYS), n=1, cutoff=0.6)
1014 closest = match[0] if match else None
1015 fix = (f"rename it to {closest!r}" if closest else f"remove {key!r}") + " and save the policy"
1016 if closest in _NARROWING_RULE_KEYS and not deny:
1017 return (True, f"the engine ignores this key, so this allow applies "
1018 f"{_NARROWING_RULE_KEYS[closest]}", fix)
1019 if closest in _NARROWING_RULE_KEYS:
1020 return (False, "the engine ignores this key, so this deny applies more widely than written", fix)
1021 return (False, "the engine ignores this key", fix)
1022 if value is None and key in _NARROWING_RULE_KEYS:
1023 fix = f"remove {key!r}, or give it a value, and save the policy"
1024 if deny:
1025 return (False, f"the engine reads null as no {key}, so this deny applies more widely than written", fix)
1026 return (True, f"the engine reads null as no {key}, so this allow applies "
1027 f"{_NARROWING_RULE_KEYS[key]}", fix)
1028 if key == "effect":
1029 return (False, f"read as {effect!r}", f"write it as {effect!r}")
1030 if key == "principal":
1031 fix = ("write the principal as public, registered, owner, role:<name>, user:<id>, "
1032 "account:<id> or subscription:<plan>")
1033 if deny:
1034 return (True, "this principal matches nobody, so this deny never applies", fix)
1035 return (False, "this principal matches nobody, so this allow grants nothing", fix)
1036 if key in ("valid_from", "expires_at"):
1037 fix = f"write {key} as an ISO-8601 date or timestamp, such as 2027-01-31T00:00:00Z"
1038 if deny:
1039 return (True, f"the engine cannot read this {key}, so this deny never applies", fix)
1040 return (False, f"the engine cannot read this {key}, so this allow never applies", fix)
1041 if key == "actions":
1042 actions = value if isinstance(value, list) else []
1043 real = [action for action in actions if isinstance(action, str) and action in RULE_ACTIONS]
1044 fix = "list each action once, from: " + ", ".join(sorted(RULE_ACTIONS))
1045 if deny and not real:
1046 return (True, "this deny names no real action, so it never applies", fix)
1047 if len(real) != len(actions):
1048 return (False, "an action that is not one matches no request", fix)
1049 return (False, "an action listed twice is read once", fix)
1050 if key == "row_filter":
1051 return _explain_row_filter(message, deny)
1052 if key in ("collection", "object_id"):
1053 return (False, f"read as the text {str(value)!r}, matched exactly as written",
1054 f"write {key} as a name made of {_NAMES_ARE}")
1055 if key in ("fields", "denied_fields"):
1056 return (False, "each entry is read as text, matched exactly as written",
1057 f"write {key} as a list of field names made of {_NAMES_ARE}")
1058 if key in ("reason", "package"):
1059 return (False, "read as text", f"write {key} as text")
1060 return (False, "the engine reads this more loosely than DRON", "correct it as the message says")
1061
1062
1063def _explain_row_filter(message: str, deny: bool) -> tuple[bool, str, str]:
1064 fix = ('write the filter as field: value, a $-variable such as "$user_id", or '
1065 '{"op": ..., "value": ...} (docs/permissions-model.md)')
1066 if ": unknown key " in message:
1067 return (False, "the engine ignores the extra key in the condition", fix)
1068 if " is not one of " in message:
1069 op = message.split("op ", 1)[1].split(" is not", 1)[0].strip("'\"")
1070 if op.strip().lower() in FILTER_OPERATORS:
1071 return (False, f"read as op {op.strip().lower()!r}", f"write the op as {op.strip().lower()!r}")
1072 return (False, "the engine does not know this op, so a request that reaches this rule "
1073 "fails with an error instead of a decision", fix)
1074 if deny:
1075 return (True, "as the engine reads it this filter matches no row, so this deny never applies", fix)
1076 return (False, "as the engine reads it this filter matches no row, so this allow grants nothing", fix)
1077
1078
1079def _explain_policy_key(key: str, message: str) -> tuple[bool, str, str]:
1080 if key in POLICY_KEYS:
1081 if key == "access_mode":
1082 return (False, "read as role_based", 'write "access_mode": "role_based"')
1083 if key in ("user_roles", "admin_roles"):
1084 return (False, "each role is read as text, and a role listed twice is read once",
1085 f"write {key} with each role name once, as text")
1086 return (False, "the engine reads this more loosely than DRON", "correct it as the message says")
1087 match = difflib.get_close_matches(key, sorted(POLICY_KEYS), n=1, cutoff=0.6)
1088 closest = match[0] if match else None
1089 fix = (f"rename it to {closest!r}" if closest else f"remove {key!r}") + " and save the policy"
1090 if closest == "rules":
1091 return (True, "the engine ignores this key, so none of the rules under it apply, "
1092 "their denies included", fix)
1093 if closest == "admin_roles":
1094 return (True, "the engine ignores this key, so the default admin roles (admin, superuser) "
1095 "bypass every rule", fix)
1096 return (False, "the engine ignores this key", fix)
1097
1098
1099ON_BEHALF_PRINCIPAL_PREFIXES = ("role:", "user:")
1100
1101
1102def _check_on_behalf_rule(rule: "PermissionRule") -> None:
1103 """Refuse an `on_behalf` rule that would grant more than staff entry.
1104
1105 On-behalf creation hands somebody else a row: the owner fallback then
1106 lets that person read, update and delete it, and every owner-scoped rule
1107 counts it as theirs. So the grant is held to the narrowest shape that
1108 still serves "a treasurer records a donation for a donor": an allow, on
1109 one named collection, covering create, for a role or one named user.
1110 `registered`, `public`, `account:` and `subscription:` are refused because
1111 each is a population, not staff -- "any signed-in user may create rows
1112 owned by anyone" is exactly the forgery the create path refuses. A rule
1113 outside this shape is an invalid policy (fail closed), not a rule that
1114 quietly grants nothing.
1115 """
1116 if rule.on_behalf is not True:
1117 raise ValueError("Permission rule on_behalf must be true or false")
1118 if rule.effect != "allow":
1119 raise ValueError("Permission rule on_behalf is only valid on an allow rule")
1120 if "create" not in rule.actions and "*" not in rule.actions:
1121 raise ValueError("Permission rule on_behalf needs create among its actions")
1122 if not rule.collection:
1123 raise ValueError("Permission rule on_behalf must name a collection")
1124 if not rule.principal.startswith(ON_BEHALF_PRINCIPAL_PREFIXES):
1125 raise ValueError(
1126 "Permission rule on_behalf is only valid for a role:<name> or user:<id> "
1127 f"principal, not {rule.principal!r}: on-behalf creation is a staff grant"
1128 )
1129
1130
1131def check_create_on_behalf(
1132 subject: PermissionSubject | None,
1133 *,
1134 policy: PermissionPolicy | None,
1135 collection: str,
1136 record: Mapping[str, Any],
1137 now: datetime | None = None,
1138) -> PermissionDecision:
1139 """May this subject create `record`, whose owner_id names somebody else?
1140
1141 Asked by the record API after the ordinary create check has passed and
1142 only when owner_id is not the caller. Allowed for an admin role, or when
1143 an active allow rule with `on_behalf: true` covers create on this
1144 collection for this subject and its row filter matches the record as
1145 sent; an explicit deny that matches still refuses. Anything else is a
1146 refusal: without a policy there is nobody to grant it (fail closed).
1147 """
1148 actor = subject or PermissionSubject.anonymous()
1149 if policy is None:
1150 return PermissionDecision.deny("no permission policy grants on-behalf creation")
1151 roles = _subject_roles(actor, policy)
1152 if _has_admin_role(roles, policy):
1153 return PermissionDecision.allow("admin role")
1154 checked_at = now or datetime.now(timezone.utc)
1155 explicit_deny = _matching_rule(
1156 policy.rules, actor, roles, CREATE,
1157 collection=collection, object_id=None, record=record, effect="deny", now=checked_at,
1158 )
1159 if explicit_deny is not None:
1160 return PermissionDecision.deny(explicit_deny.reason or "explicit deny")
1161 grant = _matching_rule(
1162 (rule for rule in policy.rules if rule.on_behalf), actor, roles, CREATE,
1163 collection=collection, object_id=None, record=record, effect="allow", now=checked_at,
1164 )
1165 if grant is None:
1166 return PermissionDecision.deny("no rule lets you create a record owned by someone else")
1167 return PermissionDecision.allow(grant.reason or f"{grant.principal} on_behalf rule")
1168
1169
1170def policy_from_dict(payload: Mapping[str, Any]) -> PermissionPolicy:
1171 """Build a policy from JSON-compatible data."""
1172 if not isinstance(payload, Mapping):
1173 raise ValueError("Permission policy must be an object")
1174
1175 access_mode = _optional_string(payload.get("access_mode")) or "role_based"
1176 if access_mode not in ACCESS_MODES:
1177 raise ValueError(f"Permission access_mode must be one of: {', '.join(sorted(ACCESS_MODES))}")
1178
1179 roles_payload = payload.get("roles", {})
1180 if not isinstance(roles_payload, Mapping):
1181 raise ValueError("Permission policy roles must be an object")
1182 roles: dict[str, dict[str, Any]] = {}
1183 for role, metadata in roles_payload.items():
1184 role_name = _string_value(role)
1185 if not role_name:
1186 raise ValueError("Permission role names must be strings")
1187 if not isinstance(metadata, Mapping):
1188 raise ValueError(f"Permission role metadata must be an object: {role_name}")
1189 roles[role_name] = dict(metadata)
1190
1191 user_roles_payload = payload.get("user_roles", {})
1192 if not isinstance(user_roles_payload, Mapping):
1193 raise ValueError("Permission policy user_roles must be an object")
1194 user_roles: dict[str, tuple[str, ...]] = {}
1195 for user_id, role_names in user_roles_payload.items():
1196 normalized_user_id = _string_value(user_id)
1197 if not normalized_user_id:
1198 raise ValueError("Permission user_roles keys must be strings")
1199 user_roles[normalized_user_id] = _string_tuple(
1200 role_names,
1201 f"user_roles.{normalized_user_id}",
1202 )
1203
1204 rules_payload = payload.get("rules", ())
1205 if not isinstance(rules_payload, (list, tuple)):
1206 raise ValueError("Permission policy rules must be a list")
1207 rules = tuple(rule_from_dict(rule) for rule in rules_payload)
1208
1209 return PermissionPolicy(
1210 access_mode=access_mode,
1211 roles=roles,
1212 user_roles=user_roles,
1213 rules=rules,
1214 admin_roles=_string_tuple(payload.get("admin_roles", ("admin", "superuser")), "admin_roles"),
1215 )
1216
1217
1218def rule_to_dict(rule: PermissionRule) -> dict[str, Any]:
1219 """Return a JSON-compatible rule."""
1220 payload: dict[str, Any] = {
1221 "effect": rule.effect,
1222 "actions": sorted(rule.actions),
1223 "principal": rule.principal,
1224 "row_filter": dict(rule.row_filter),
1225 "denied_fields": sorted(rule.denied_fields),
1226 "reason": rule.reason,
1227 }
1228
1229 if rule.collection is not None:
1230 payload["collection"] = rule.collection
1231 if rule.object_id is not None:
1232 payload["object_id"] = rule.object_id
1233 if rule.fields is not None:
1234 payload["fields"] = sorted(rule.fields)
1235 if rule.valid_from is not None:
1236 payload["valid_from"] = rule.valid_from
1237 if rule.expires_at is not None:
1238 payload["expires_at"] = rule.expires_at
1239 if rule.package is not None:
1240 payload["package"] = rule.package
1241 if rule.on_behalf:
1242 # Only when set, so every rule written before the key existed keeps
1243 # its exact dict -- and so its merge key (object_packages).
1244 payload["on_behalf"] = True
1245
1246 return payload
1247
1248
1249WIDE_PRINCIPALS = ("registered", "public")
1250
1251
1252def wide_rule_reason(rule: PermissionRule) -> str | None:
1253 """One line saying why an allow rule is "wide", or None when it is not.
1254
1255 Wide: an allow for everyone signed in (`registered`) or everyone at all
1256 (`public`) that names neither a collection nor an object. A rule that
1257 names no resource matches every resource (`_resource_matches`), so it
1258 grants its actions on every object and every collection at once, and the
1259 engine returns the first allow rule that matches without comparing it
1260 with the narrower ones: a package's row filter or object grant after it
1261 decides nothing it already covered. The starter policy used to ship one
1262 ("signed-in users can read and run objects"); a box that started from it
1263 still has it, and nothing removes it (it carries no `package` tag).
1264 """
1265 if rule.effect != "allow" or rule.principal not in WIDE_PRINCIPALS:
1266 return None
1267 if rule.collection or rule.object_id:
1268 return None
1269 who = "every signed-in user" if rule.principal == "registered" else "everyone, signed in or not"
1270 actions = ", ".join(sorted(rule.actions)) or "nothing"
1271 return (f"gives {who} {actions} on EVERY object and collection, whatever the packages "
1272 f"grant or filter; remove it or give it a collection or object_id")
1273
1274
1275def policy_to_dict(policy: PermissionPolicy) -> dict[str, Any]:
1276 """Return a JSON-compatible policy."""
1277 return {
1278 "access_mode": policy.access_mode,
1279 "roles": {role: dict(metadata) for role, metadata in sorted(policy.roles.items())},
1280 "user_roles": {
1281 user_id: list(role_names)
1282 for user_id, role_names in sorted(policy.user_roles.items())
1283 },
1284 "rules": [rule_to_dict(rule) for rule in policy.rules],
1285 "admin_roles": list(policy.admin_roles),
1286 }
1287
1288
1289def decision_to_dict(decision: PermissionDecision) -> dict[str, Any]:
1290 """Return a JSON-compatible permission decision."""
1291 return {
1292 "allowed": decision.allowed,
1293 "reason": decision.reason,
1294 "code": decision.code,
1295 "http_status": decision.http_status,
1296 "row_filter": dict(decision.row_filter),
1297 "fields": sorted(decision.fields) if decision.fields is not None else None,
1298 "denied_fields": sorted(decision.denied_fields),
1299 }
1300
1301
1302def subject_roles(subject: PermissionSubject, policy: PermissionPolicy) -> frozenset[str]:
1303 """Return roles assigned directly and through the active policy."""
1304 return _subject_roles(subject, policy)
1305
1306
1307def subject_has_admin_role(subject: PermissionSubject, policy: PermissionPolicy) -> bool:
1308 """Return True when the subject has one of the policy admin roles."""
1309 return _has_admin_role(_subject_roles(subject, policy), policy)
1310
1311
1312def subject_reads_every_row(
1313 subject: PermissionSubject | None,
1314 collection: str,
1315 *,
1316 policy: PermissionPolicy | None,
1317 now: datetime | None = None,
1318) -> bool:
1319 """True only when ``subject`` may read EVERY row ``collection`` holds or
1320 could hold, whole -- the test for being shown a number computed over all
1321 of them (object_attention: a code provider's count is folded with no
1322 viewer, so it may only reach someone the rows themselves could reach).
1323
1324 Fail closed: anything this cannot prove is False. Concretely, in the
1325 engine's own order: yes for an admin role; no when any deny that applies
1326 to the subject could refuse a row (unfiltered, filtered, or for the
1327 `owner` principal -- the collection-level question skips the last two,
1328 see _matching_rule, so they are looked for here); yes when the access
1329 mode allows the read with no rule; yes when some active allow rule that
1330 applies grants the read with no row filter and no field restriction --
1331 ANY such rule, not the first matching one, since a manager usually also
1332 matches the `registered` own-rows rule listed before theirs; else no
1333 (owner-fallback reads are per row by definition).
1334 """
1335 if policy is None:
1336 return False
1337 actor = subject or PermissionSubject.anonymous()
1338 roles = _subject_roles(actor, policy)
1339 if _has_admin_role(roles, policy):
1340 return True
1341 checked_at = _normalize_datetime(now or datetime.now(timezone.utc))
1342
1343 def applies(rule: PermissionRule) -> bool:
1344 return (_rule_is_active(rule, checked_at) and _action_matches(rule, READ)
1345 and _resource_matches(rule, collection=collection, object_id=None))
1346
1347 for rule in policy.rules:
1348 if rule.effect == "deny" and applies(rule) and (
1349 rule.principal == "owner"
1350 or _principal_matches(rule.principal, actor, roles, record=None)):
1351 return False
1352 if _access_mode_decision(actor, policy.access_mode, READ,
1353 collection=collection, object_id=None).allowed:
1354 return True
1355 return any(
1356 rule.effect == "allow" and not rule.not_applied and applies(rule) and not rule.row_filter
1357 and rule.fields is None and not rule.denied_fields
1358 and rule.principal != "owner"
1359 and _principal_matches(rule.principal, actor, roles, record=None)
1360 for rule in policy.rules)
1361
1362
1363def record_matches_filter(
1364 record: Mapping[str, Any],
1365 row_filter: Mapping[str, Any],
1366 subject: PermissionSubject,
1367) -> bool:
1368 """Return True when a record's stored values satisfy a filter/guard.
1369
1370 Shared by row filters, schema transition guards, and 58's query/filter
1371 layer -- the one flat-condition evaluator in the codebase. Each key's
1372 value is one of:
1373
1374 - a literal string, or a $-variable (see ``_resolve_filter_value``):
1375 the pre-existing row-filter/transition-guard shape, an implicit
1376 ``eq``. An empty stored field never matches a $-variable, and a
1377 field the record does not have at all (or holds as None) never
1378 matches ``eq`` against anything -- not a $-variable that resolved to
1379 nothing, not a literal null (see ``_condition_matches``).
1380 - a single condition, ``{"op": <FILTER_OPERATORS>, "value": ...}``
1381 (see ``filter_condition``).
1382 - a list of such conditions, ANDed -- lets one field carry more than
1383 one clause (a date range: ``created_at.gte=X&created_at.lte=Y``).
1384
1385 ``in``'s value (and a $-variable that resolves to a tuple, e.g.
1386 ``$accessible_projects``) is treated as a membership set. ``gte``/
1387 ``lte``/``gt``/``lt`` compare numerically when both sides parse as a
1388 number, then as ISO dates/datetimes read in UTC (no offset is UTC, a
1389 date alone is UTC midnight), else as text when the bound is plain text.
1390 Against a number or date bound, a missing, blank or other value cannot
1391 be compared and does not match here; a deny rule reads that the other
1392 way (see ``_record_matches_filter``). Callers that need a
1393 guaranteed-correct ordered compare (58's HTTP/MCP surfaces) type-validate the value against the field's
1394 schema type before it ever reaches this matcher.
1395 """
1396 return _record_matches_filter(record, row_filter, subject)
1397
1398
1399def filter_condition(op: str, value: Any) -> dict[str, Any]:
1400 """Build one ``{"op": op, "value": value}`` condition for a row_filter/
1401 query-filter value passed to ``record_matches_filter``."""
1402 return {"op": op, "value": value}
1403
1404
1405def principal_matches(
1406 principal: str,
1407 subject: PermissionSubject,
1408 policy: PermissionPolicy,
1409 *,
1410 record: Mapping[str, Any] | None = None,
1411) -> bool:
1412 """Return True when a portable principal matches the subject."""
1413 return _principal_matches(
1414 principal,
1415 subject,
1416 _subject_roles(subject, policy),
1417 record=record,
1418 )
1419
1420
1421def _access_mode_decision(
1422 subject: PermissionSubject,
1423 access_mode: str,
1424 action: str,
1425 *,
1426 collection: str | None,
1427 object_id: str | None,
1428) -> PermissionDecision:
1429 mode = access_mode.lower()
1430
1431 if mode == "public":
1432 if action in PUBLIC_READ_ACTIONS:
1433 return PermissionDecision.allow("public access")
1434 return PermissionDecision.deny("public access is read-only")
1435
1436 if mode == "registered":
1437 if subject.is_authenticated and action in PUBLIC_READ_ACTIONS:
1438 return PermissionDecision.allow("registered access")
1439 return PermissionDecision.deny(
1440 "registered user required",
1441 code="authentication_required",
1442 http_status=401,
1443 )
1444
1445 if mode == "subscription":
1446 if subject.subscriptions and action in PUBLIC_READ_ACTIONS:
1447 return PermissionDecision.allow("subscription access")
1448 if subject.subscriptions:
1449 return PermissionDecision.deny("subscription access is read-only")
1450 return PermissionDecision.deny(
1451 "subscription required",
1452 code="payment_required",
1453 http_status=402,
1454 )
1455
1456 if mode == "password":
1457 return PermissionDecision.deny(
1458 "password gate must authenticate before policy check",
1459 code="authentication_required",
1460 http_status=401,
1461 )
1462
1463 if mode == "role_based":
1464 return PermissionDecision.deny("no matching role rule")
1465
1466 if mode == "private":
1467 return _owner_fallback(
1468 subject,
1469 action,
1470 object_id=object_id,
1471 record=None,
1472 allow_system_public=False,
1473 )
1474
1475 return PermissionDecision.deny(f"unknown access mode: {access_mode}")
1476
1477
1478def _matching_rule(
1479 rules: Iterable[PermissionRule],
1480 subject: PermissionSubject,
1481 roles: frozenset[str],
1482 action: str,
1483 *,
1484 collection: str | None,
1485 object_id: str | None,
1486 record: Mapping[str, Any] | None,
1487 effect: str,
1488 now: datetime,
1489) -> PermissionRule | None:
1490 for rule in rules:
1491 if rule.effect != effect:
1492 continue
1493 if rule.not_applied and effect == "allow":
1494 continue # fail closed: a widened allow grants nothing
1495 if not _rule_is_active(rule, now):
1496 continue
1497 if not _action_matches(rule, action):
1498 continue
1499 if not _resource_matches(rule, collection=collection, object_id=object_id):
1500 continue
1501 if not _principal_matches(rule.principal, subject, roles, record=record):
1502 continue
1503 if effect == "deny" and record is None and rule.row_filter:
1504 # A filtered deny is about SOME rows, and the collection-level
1505 # question (a list, a search, a /ws subscribe: record=None) is
1506 # not about any row. Matching it there refused the whole list
1507 # with 403 while the same rule, asked per record, correctly hid
1508 # only the rows its filter names -- for every principal except
1509 # `owner`, which already cannot match without a record
1510 # (bug-reports/2026-11-28-06-14-55). Every collection-level
1511 # caller re-asks per row before returning one (lists, search,
1512 # realtime delivery, the pre-lookup write gate), which is where
1513 # this rule now applies. An allow's filter is handed back on the
1514 # decision for the same reason; a deny's needs no handing back,
1515 # because the per-row check re-runs this loop with the record.
1516 continue
1517 if (
1518 record is not None
1519 and rule.row_filter
1520 and not _record_matches_filter(
1521 record, rule.row_filter, subject, collection=collection, unknown=(effect == "deny"))
1522 ):
1523 continue
1524 return rule
1525 return None
1526
1527
1528def _rule_is_active(rule: PermissionRule, now: datetime) -> bool:
1529 checked_at = _normalize_datetime(now)
1530
1531 if rule.valid_from is not None:
1532 valid_from = _parse_timestamp(rule.valid_from)
1533 if valid_from is None or checked_at < valid_from:
1534 return False
1535
1536 if rule.expires_at is not None:
1537 expires_at = _parse_timestamp(rule.expires_at)
1538 if expires_at is None or checked_at >= expires_at:
1539 return False
1540
1541 return True
1542
1543
1544def _action_matches(rule: PermissionRule, action: str) -> bool:
1545 return "*" in rule.actions or action in rule.actions
1546
1547
1548def _resource_matches(
1549 rule: PermissionRule,
1550 *,
1551 collection: str | None,
1552 object_id: str | None,
1553) -> bool:
1554 if rule.collection is not None and rule.collection != collection:
1555 return False
1556 if rule.object_id is not None and rule.object_id != object_id:
1557 return False
1558 return True
1559
1560
1561# ---------------------------------------------------------------------------
1562# Row-filter pushdown: which rows does a permission-filtered LIST have to
1563# look at?
1564#
1565# THE PROBLEM. A list of a collection calls check_permission once per row of
1566# the WHOLE collection, and each call walks every rule twice (_matching_rule,
1567# a deny pass and an allow pass). Measured at 1,000 users / 10,000 notes in a
1568# full install (246 rules): 10,044 calls, ~94% of a 375 ms request, for a
1569# user who can see forty rows. /api/search does it across every collection.
1570#
1571# THE ANSWER. Before the loop, derive from the policy and the subject ALONE
1572# a set of equality lookups -- "owner_id is u7", "project_id is one of
1573# p1, p2", "is_public is true" -- whose rows are a SUPERSET of everything
1574# the engine would allow. A per-field index (object_records) turns the
1575# lookups into row positions; the caller then runs the real, unmodified
1576# check_permission on those candidates only. The engine stays the final
1577# authority on every row that is returned, so a bug here can never SHOW a
1578# row. It can HIDE one, silently, which is what tests/
1579# test_row_filter_pushdown.py exists to catch: random policies, every
1580# shipped rule, and a set of deliberately broken planners that the
1581# differential must notice.
1582#
1583# WHY IT LIVES HERE and not beside the index or in the server: it has to
1584# agree with _matching_rule about five things -- which rules apply to a
1585# subject, the order admin -> deny -> access mode -> allow -> owner
1586# fallback, the owner keys, which operators are equality-shaped, and what
1587# `eq` / `in` match. A planner in another module mirrors those; a mirror
1588# drifts (the prototype's own tripwire did not notice the engine's
1589# fail-closed fix to scalar `eq`). So this calls the engine's functions
1590# (_rule_is_active, _action_matches, _resource_matches, _principal_matches,
1591# _access_mode_decision, _iter_conditions, _condition_op_value,
1592# _resolve_filter_value, _equality_match_values) and reads its constants
1593# (OWNER_KEYS, OWNER_ACTIONS, FILTER_OPERATORS, _EQUALITY_FILTER_OPERATORS)
1594# instead of restating them. It does no IO and knows nothing about the
1595# index: it only describes lookups.
1596#
1597# WHAT WAS REJECTED.
1598# - Narrowing on deny rules. Ignoring a deny is always a superset, and a
1599# deny's filter says which rows to drop, which an equality index cannot
1600# subtract from an unknown set. The one exact case kept: an unfiltered,
1601# non-owner deny that matches the subject denies every row.
1602# - A "rows lacking the field" bucket. The engine once matched `eq`
1603# against an unresolved variable to every such row; it no longer does
1604# (see _condition_matches), so no lookup needs one.
1605# - Treating `ne` or a range as indexable. `ne` is a complement and is
1606# NOT `not eq` (tests/test_permission_missing_column.py); a rule with
1607# nothing but those falls back to all rows.
1608# - Guessing. Every case this does not recognise returns "all rows",
1609# which is exactly today's behaviour and cost.
1610# ---------------------------------------------------------------------------
1611
1612
1613@dataclass(frozen=True)
1614class RowFilterPlan:
1615 """Which rows a permission-filtered list has to run the engine on.
1616
1617 ``groups is None`` means EVERY row (the fallback: today's behaviour).
1618 Otherwise the candidates are the union, over the groups, of one option
1619 from each group:
1620
1621 - a GROUP is one way a row can come to be allowed: the owner fallback,
1622 or one allow rule that applies to the subject;
1623 - an OPTION is a tuple of ``(field, values)`` lookups, a row being a
1624 candidate when ``str(row[field])`` is in ``values`` for ANY of them.
1625 Each option of a group is, on its own, a superset of the rows that
1626 group can allow (any one of a rule's ANDed conditions is), so the
1627 reader picks whichever option it can index most cheaply and falls
1628 back to every row if it can index none of a group's options.
1629
1630 ``groups == ()`` is zero candidates: nothing can be allowed.
1631
1632 A plan is only a superset for the (subject, action, policy, collection)
1633 it was made for, and -- when rules carry time windows -- for the ``now``
1634 it was given: see ``plan_row_filter``.
1635 """
1636
1637 groups: tuple[tuple[tuple[tuple[str, frozenset[str]], ...], ...], ...] | None
1638 reason: str = ""
1639
1640 @property
1641 def all_rows(self) -> bool:
1642 return self.groups is None
1643
1644 def fields(self) -> frozenset[str]:
1645 """Every field some option looks up (what an index may be asked for)."""
1646 return frozenset(
1647 name
1648 for group in self.groups or ()
1649 for option in group
1650 for name, _values in option
1651 )
1652
1653
1654def plan_row_filter(
1655 subject: PermissionSubject | None,
1656 action: str,
1657 *,
1658 policy: PermissionPolicy | None,
1659 collection: str | None,
1660 now: datetime | None = None,
1661) -> RowFilterPlan:
1662 """Describe a superset of the rows ``check_permission(record=row)`` allows.
1663
1664 For a LIST only: no object id, and the per-row checks must be made with
1665 the same subject, action, policy and collection.
1666
1667 ``now``: pass the SAME datetime the per-row checks will be given and
1668 time-windowed rules are planned exactly. Pass None and they are planned
1669 conservatively -- an allow rule that could be active at some instant
1670 widens the plan, and a deny rule with a window never short-circuits --
1671 which stays a superset whatever time the checks run at.
1672
1673 Falls back to all rows (``groups is None``) when:
1674 1. there is no explicit policy; the subject has an admin role; or the
1675 access mode allows the action with no rule at all (public /
1676 registered / subscription reads);
1677 2. an allow rule that applies has no row filter and a non-owner
1678 principal (the subject sees everything);
1679 3. an allow rule that applies has only `ne` / range conditions;
1680 4. ANY filter in the policy uses an unknown operator: the engine
1681 raises ValueError when a row reaches it, and the same rows must
1682 reach it;
1683 5. the subject or policy is not shaped like something
1684 subject_from_dict / policy_from_dict / a session produces;
1685 6. anything at all goes wrong while planning. This never raises.
1686 (The index adds two more, which are its business: a collection too big
1687 to cache, and a field it cannot index -- object_records.)
1688 """
1689 try:
1690 return _plan_row_filter(subject, action, policy=policy, collection=collection, now=now)
1691 except Exception as exc: # noqa: BLE001 - never be the reason a request differs
1692 return RowFilterPlan(None, f"planner error: {type(exc).__name__}: {exc}")
1693
1694
1695def _plan_row_filter(
1696 subject: PermissionSubject | None,
1697 action: str,
1698 *,
1699 policy: PermissionPolicy | None,
1700 collection: str | None,
1701 now: datetime | None,
1702) -> RowFilterPlan:
1703 if policy is None:
1704 return RowFilterPlan(None, "no explicit policy")
1705 actor = subject or PermissionSubject.anonymous()
1706 problem = _plan_shape_problem(actor, action, policy, collection, now)
1707 if problem:
1708 return RowFilterPlan(None, f"unrecognised shape: {problem}")
1709 if _plan_policy_has_unknown_operator(policy):
1710 return RowFilterPlan(None, "policy contains an unknown filter operator")
1711
1712 normalized_action = action.lower()
1713 roles = _subject_roles(actor, policy)
1714 if _has_admin_role(roles, policy):
1715 return RowFilterPlan(None, "admin role")
1716
1717 # Deny runs before the access mode and before any allow rule, so an
1718 # unfiltered deny that matches the subject denies every row. Only that
1719 # shape: a deny with a row filter, or for the `owner` principal, depends
1720 # on the row.
1721 for rule in policy.rules:
1722 if rule.effect != "deny" or rule.row_filter or rule.principal == "owner":
1723 continue
1724 if (
1725 _plan_rule_certainly_active(rule, now)
1726 and _plan_static_match(rule, normalized_action, collection)
1727 and _principal_matches(rule.principal, actor, roles, record=None)
1728 ):
1729 return RowFilterPlan((), "an unfiltered deny rule matches the subject")
1730
1731 if _plan_mode_allows_without_rules(actor, policy, normalized_action, collection):
1732 return RowFilterPlan(None, f"access mode {policy.access_mode} allows {normalized_action} without a rule")
1733
1734 groups: list[tuple[tuple[tuple[str, frozenset[str]], ...], ...]] = []
1735 fallback_group = _plan_owner_fallback_group(actor, normalized_action)
1736 if fallback_group is not None:
1737 groups.append(fallback_group)
1738
1739 for number, rule in enumerate(policy.rules):
1740 if (
1741 rule.effect != "allow"
1742 or rule.not_applied
1743 or not _plan_rule_possibly_active(rule, now)
1744 or not _plan_static_match(rule, normalized_action, collection)
1745 ):
1746 continue
1747 options: list[tuple[tuple[str, frozenset[str]], ...]] = []
1748 if rule.principal == "owner":
1749 if actor.user_id is None:
1750 continue # _subject_owns is False for every row
1751 options.append(_plan_owner_option(actor.user_id))
1752 elif not _principal_matches(rule.principal, actor, roles, record=None):
1753 continue
1754 for field_name, expected in rule.row_filter.items():
1755 for condition in _iter_conditions(expected):
1756 operator, raw_value = _condition_op_value(condition)
1757 resolved = _resolve_filter_value(raw_value, actor, collection=collection)
1758 values = _plan_condition_values(operator, resolved)
1759 if values is not None:
1760 # Any ONE of a rule's ANDed conditions is a superset of
1761 # the rule; the engine checks the rest.
1762 options.append(((field_name, values),))
1763 if not options:
1764 return RowFilterPlan(
1765 None, f"allow rule #{number} ({rule.principal}) has no equality condition to index"
1766 )
1767 groups.append(tuple(options))
1768
1769 return RowFilterPlan(tuple(groups), "indexed")
1770
1771
1772def _plan_owner_option(user_id: str) -> tuple[tuple[str, frozenset[str]], ...]:
1773 """The rows `_subject_owns` is True for: any owner key holding the user id."""
1774 owner = frozenset((user_id,))
1775 return tuple((key, owner) for key in OWNER_KEYS)
1776
1777
1778def _plan_owner_fallback_group(
1779 actor: PermissionSubject, action: str
1780) -> tuple[tuple[tuple[str, frozenset[str]], ...], ...] | None:
1781 """`_owner_fallback` allows an owned row with no rule at all."""
1782 if actor.user_id is None or action not in OWNER_ACTIONS:
1783 return None
1784 return (_plan_owner_option(actor.user_id),)
1785
1786
1787def _plan_condition_values(op: str, resolved: Any) -> frozenset[str] | None:
1788 """The values an index lookup needs for one condition, or None when the
1789 condition is not equality-shaped (`ne`, a range) and cannot be indexed."""
1790 if op not in _EQUALITY_FILTER_OPERATORS:
1791 return None
1792 return frozenset(_equality_match_values(op, resolved))
1793
1794
1795def _plan_policy_has_unknown_operator(policy: PermissionPolicy) -> bool:
1796 for rule in policy.rules:
1797 for expected in rule.row_filter.values():
1798 for condition in _iter_conditions(expected):
1799 if _condition_op_value(condition)[0] not in FILTER_OPERATORS:
1800 return True
1801 return False
1802
1803
1804def _plan_mode_allows_without_rules(
1805 actor: PermissionSubject, policy: PermissionPolicy, action: str, collection: str | None
1806) -> bool:
1807 """Would check_permission allow every row no deny rule matches?"""
1808 return _access_mode_decision(
1809 actor, policy.access_mode, action, collection=collection, object_id=None
1810 ).allowed
1811
1812
1813def _plan_static_match(rule: PermissionRule, action: str, collection: str | None) -> bool:
1814 """The parts of _matching_rule that depend on neither the row nor the subject."""
1815 return _action_matches(rule, action) and _resource_matches(
1816 rule, collection=collection, object_id=None
1817 )
1818
1819
1820def _plan_rule_possibly_active(rule: PermissionRule, now: datetime | None) -> bool:
1821 """May this rule be active when the engine evaluates a row?"""
1822 if now is not None:
1823 return _rule_is_active(rule, now) # the caller pins the same `now` for the checks
1824 for stamp in (rule.valid_from, rule.expires_at):
1825 if stamp is not None and _parse_timestamp(stamp) is None:
1826 return False # unparseable: _rule_is_active is False at every instant
1827 return True
1828
1829
1830def _plan_rule_certainly_active(rule: PermissionRule, now: datetime | None) -> bool:
1831 if now is not None:
1832 return _rule_is_active(rule, now)
1833 return rule.valid_from is None and rule.expires_at is None
1834
1835
1836_PLAN_SEQUENCES = (tuple, list)
1837
1838
1839def _plan_shape_problem(
1840 subject: Any, action: Any, policy: Any, collection: Any, now: Any
1841) -> str | None:
1842 """Refuse anything policy_from_dict / subject_from_dict / a session could
1843 not have produced.
1844
1845 With these shapes the engine has exactly one way to raise while it
1846 filters rows -- an unknown operator, handled separately -- so a
1847 narrowed row set cannot swallow an error the full scan would have
1848 raised. (A Python caller can build a policy the JSON loaders never
1849 would; such a policy is simply not planned.)
1850 """
1851 if not isinstance(action, str):
1852 return "action is not a string"
1853 if collection is not None and not isinstance(collection, str):
1854 return "collection is not a string"
1855 if now is not None and not isinstance(now, datetime):
1856 return "now is not a datetime"
1857 if not isinstance(subject, PermissionSubject):
1858 return "subject is not a PermissionSubject"
1859 if subject.user_id is not None and not isinstance(subject.user_id, str):
1860 return "subject.user_id is not a string"
1861 if subject.account_id is not None and not isinstance(subject.account_id, str):
1862 return "subject.account_id is not a string"
1863 for name in ("roles", "subscriptions", "project_ids", "owned_project_ids", "writable_project_ids"):
1864 value = getattr(subject, name)
1865 if not isinstance(value, _PLAN_SEQUENCES) or not all(isinstance(item, str) for item in value):
1866 return f"subject.{name} is not a sequence of strings"
1867 for name in ("shared_records", "writable_shared_records"):
1868 value = getattr(subject, name)
1869 if not isinstance(value, Mapping) or not all(
1870 isinstance(item, _PLAN_SEQUENCES) for item in value.values()
1871 ):
1872 return f"subject.{name} is not a mapping of sequences"
1873 if not isinstance(policy, PermissionPolicy):
1874 return "policy is not a PermissionPolicy"
1875 if not isinstance(policy.access_mode, str):
1876 return "access_mode is not a string"
1877 if not isinstance(policy.admin_roles, _PLAN_SEQUENCES) or not all(
1878 isinstance(role, str) for role in policy.admin_roles
1879 ):
1880 return "admin_roles is not a sequence of strings"
1881 if not isinstance(policy.user_roles, Mapping) or not all(
1882 isinstance(value, _PLAN_SEQUENCES) and all(isinstance(role, str) for role in value)
1883 for value in policy.user_roles.values()
1884 ):
1885 return "user_roles is not a mapping of string sequences"
1886 if not isinstance(policy.rules, _PLAN_SEQUENCES):
1887 return "rules is not a sequence"
1888 for rule in policy.rules:
1889 if not isinstance(rule, PermissionRule):
1890 return "a rule is not a PermissionRule"
1891 if not isinstance(rule.effect, str) or not isinstance(rule.principal, str):
1892 return "rule effect/principal is not a string"
1893 if not isinstance(rule.actions, (frozenset, set, tuple, list)):
1894 return "rule.actions is not a collection"
1895 if rule.collection is not None and not isinstance(rule.collection, str):
1896 return "rule.collection is not a string"
1897 if rule.object_id is not None and not isinstance(rule.object_id, str):
1898 return "rule.object_id is not a string"
1899 if not isinstance(rule.row_filter, Mapping) or not all(
1900 isinstance(key, str) for key in rule.row_filter
1901 ):
1902 return "rule.row_filter is not a mapping with string keys"
1903 for stamp in (rule.valid_from, rule.expires_at):
1904 if stamp is not None and not isinstance(stamp, str):
1905 return "rule time window is not a string"
1906 return None
1907
1908
1909def _principal_matches(
1910 principal: str,
1911 subject: PermissionSubject,
1912 roles: frozenset[str],
1913 *,
1914 record: Mapping[str, Any] | None,
1915) -> bool:
1916 if principal == "public":
1917 return True
1918 if principal == "registered":
1919 return subject.is_authenticated
1920 if principal == "owner":
1921 return _subject_owns(subject, record=record)
1922 if principal == OWNER_FALLBACK:
1923 # Not a subject: see _owner_fallback_opt_out. Said out loud so the
1924 # deny pass visibly skips these rules rather than by falling through.
1925 return False
1926 if principal.startswith("role:"):
1927 return principal.removeprefix("role:") in roles
1928 if principal.startswith("user:"):
1929 return subject.user_id == principal.removeprefix("user:")
1930 if principal.startswith("account:"):
1931 return subject.account_id == principal.removeprefix("account:")
1932 if principal.startswith("subscription:"):
1933 return principal.removeprefix("subscription:") in subject.subscriptions
1934 return False
1935
1936
1937def _owner_fallback(
1938 subject: PermissionSubject,
1939 action: str,
1940 *,
1941 object_id: str | None,
1942 record: Mapping[str, Any] | None,
1943 allow_system_public: bool = True,
1944) -> PermissionDecision:
1945 if object_id:
1946 parsed = parse_user_object_id(object_id)
1947 if parsed is None and allow_system_public and action in PUBLIC_READ_ACTIONS:
1948 return PermissionDecision.allow("system object public read")
1949 if parsed is not None and subject.user_id == str(parsed[0]) and action in OWNER_ACTIONS:
1950 return PermissionDecision.allow("object owner")
1951
1952 if record is not None and _subject_owns(subject, record=record) and action in OWNER_ACTIONS:
1953 return PermissionDecision.allow("record owner")
1954
1955 return PermissionDecision.deny("not owner")
1956
1957
1958def _owner_fallback_opt_out(
1959 rules: Iterable[PermissionRule],
1960 subject: PermissionSubject,
1961 action: str,
1962 *,
1963 collection: str | None,
1964 object_id: str | None,
1965 record: Mapping[str, Any] | None,
1966 now: datetime,
1967) -> PermissionRule | None:
1968 """The rule, if any, that switches the owner fallback off for this check.
1969
1970 THE PROBLEM. The fallback is the engine's last resort: with no rule
1971 matching, whoever a record's owner key names may read, update, delete
1972 (OWNER_ACTIONS). So a package that grants only READ on a collection --
1973 template_runs: "the absence of update is the enforcement of the state
1974 machine"; wallet_entries: "No create/update/delete" -- enforced nothing
1975 by that absence. Asked about the owner's own row, the engine said yes.
1976 The record API usually never got to ask (its pre-lookup, collection-
1977 level question has no record, so no fallback, so a 403); it did as soon
1978 as any other allow rule for the action let the subject past that
1979 question, and object_access -- which every page, action and hook that
1980 reads storage is being moved onto -- always did.
1981
1982 THE ANSWER is a rule a package ships beside its grants::
1983
1984 {"effect": "deny", "principal": "owner_fallback",
1985 "actions": ["update", "delete"], "collection": "template_runs"}
1986
1987 It is consulted HERE and nowhere else: after the allow pass has found
1988 nothing, and only when the fallback would otherwise have allowed. That
1989 placement is the whole design. An explicit grant is found first and
1990 still grants, so "owners may edit their own drafts" beside an opt-out
1991 keeps working and nobody who relies on a grant can be broken by one;
1992 admins were decided before any rule; in-process writers never ask.
1993
1994 WHAT WAS REJECTED.
1995 - Changing the default ("no fallback once a collection has rules").
1996 The fallback is documented (docs/permissions-model.md, the decision
1997 flowchart and Ownership) and tested as applying after rules
1998 (tests/test_object_access.py, test_permission_missing_column.py),
1999 and it is today the only thing granting an owner update or delete
2000 on the collections tests/test_owner_fallback_opt_out.py lists as
2001 UNDECIDED. Changing what every owner may do is the project owner's
2002 call to make, not a side effect of fixing template_runs.
2003 - An ordinary `deny registered update`. Deny runs first and beats
2004 every allow, so it would also silence a role grant an operator adds
2005 later, or an owner grant another package version adds -- the
2006 opposite of "only what the rules say".
2007 - A schema flag. The engine is pure and is handed a policy, not
2008 schemas; every caller would have had to learn to fetch one.
2009
2010 Matching follows `_matching_rule`: time window, action (or `*`),
2011 resource (a rule naming neither a collection nor an object covers the
2012 whole policy), and a row filter, which limits the opt-out to the rows
2013 it names and so never applies to a check that has no record.
2014
2015 Not covered: `private` access mode, where ownership of a `u_<id>_...`
2016 object is the access mode's own decision rather than the fallback.
2017 Records are unaffected by that (the mode never sees the record).
2018
2019 The row-filter planner is deliberately not told. It goes on proposing
2020 the owner's rows, which stays a superset; this function, through
2021 check_permission, still decides each one.
2022 """
2023 for rule in rules:
2024 if rule.effect != "deny" or rule.principal != OWNER_FALLBACK:
2025 continue
2026 if not _rule_is_active(rule, now):
2027 continue
2028 if not _action_matches(rule, action):
2029 continue
2030 if not _resource_matches(rule, collection=collection, object_id=object_id):
2031 continue
2032 if rule.row_filter and (
2033 record is None
2034 or not _record_matches_filter(record, rule.row_filter, subject, collection=collection, unknown=True)
2035 ):
2036 continue
2037 return rule
2038 return None
2039
2040
2041def _subject_owns(
2042 subject: PermissionSubject,
2043 *,
2044 record: Mapping[str, Any] | None,
2045) -> bool:
2046 if record is None or subject.user_id is None:
2047 return False
2048
2049 for key in OWNER_KEYS:
2050 if _string_value(record.get(key)) == subject.user_id:
2051 return True
2052
2053 return False
2054
2055
2056def _record_matches_filter(
2057 record: Mapping[str, Any],
2058 row_filter: Mapping[str, Any],
2059 subject: PermissionSubject,
2060 *,
2061 collection: str | None = None,
2062 unknown: bool = False,
2063) -> bool:
2064 """Every condition holds. ``unknown=True`` is for a filter that REFUSES
2065 when it matches (a deny rule, the owner-fallback opt-out): an ordered
2066 condition that cannot be judged then counts as holding, so the refusal
2067 stands rather than turning into "no match, so allowed". Conditions are
2068 ANDed, so a deny's other conditions still decide: one that is plainly
2069 false (another owner, a status the deny does not name) still spares
2070 the row. Everything else (allow rules, transition guards, attention
2071 counts, list filters) keeps the default: cannot judge, does not match."""
2072 for key, expected in row_filter.items():
2073 actual = _string_value(record.get(key))
2074 for condition in _iter_conditions(expected):
2075 op, raw_value = _condition_op_value(condition)
2076 resolved = _resolve_filter_value(raw_value, subject, collection=collection)
2077 if not _condition_matches(op, actual, resolved, unknown=unknown):
2078 return False
2079 return True
2080
2081
2082def _is_condition(value: Any) -> bool:
2083 return isinstance(value, Mapping) and "op" in value
2084
2085
2086def _iter_conditions(expected: Any) -> list[Any]:
2087 """Split one row_filter value into its ANDed conditions.
2088
2089 A list is only ever treated as multiple conditions when EVERY item is
2090 condition-shaped (``{"op": ...}``) -- anything else (a literal, a
2091 $-variable string, one condition, or a $-variable already resolved to
2092 a tuple by a caller) stays a single condition, so this never changes
2093 behavior for the pre-existing row-filter/transition-guard callers,
2094 none of which ever pass a list.
2095 """
2096 if isinstance(expected, list) and expected and all(_is_condition(item) for item in expected):
2097 return list(expected)
2098 return [expected]
2099
2100
2101def _condition_op_value(condition: Any) -> tuple[str, Any]:
2102 if _is_condition(condition):
2103 op = str(condition.get("op") or "eq").strip().lower() or "eq"
2104 return op, condition.get("value")
2105 return "eq", condition
2106
2107
2108def _equality_match_values(op: str, resolved: Any) -> Collection[str]:
2109 """The stored values that satisfy one equality-shaped condition.
2110
2111 For ``op`` in ``_EQUALITY_FILTER_OPERATORS`` a condition matches exactly
2112 when the field is present (not missing, not None) AND its string value
2113 is in the set returned here. That sentence is the whole equality and
2114 membership contract, and this is its ONE implementation: the evaluator
2115 (``_condition_matches``) decides a row with it, and the row-filter
2116 planner (``plan_row_filter``) asks it which index buckets could hold a
2117 matching row. They cannot disagree about what `eq` means because
2118 neither of them knows.
2119
2120 - ``in``: the non-None members, stringified; a scalar is a set of one.
2121 - ``eq`` against a tuple: the same. A tuple only ever arrives here as a
2122 $-variable that resolved to a membership set ($accessible_projects),
2123 which is the eq-with-tuple behavior row filters have always relied
2124 on. A LIST is not that: a literal list is compared as one string.
2125 - ``eq`` against anything else: that one value, stringified -- and
2126 nothing at all when it is None. See the fail-closed note in
2127 ``_condition_matches``: a value that resolved to nothing matches no
2128 row, so there is deliberately no "rows lacking the field" member.
2129
2130 Returns a container to test membership in (a set, or a tuple of at most
2131 one value for the scalar case: this runs once per condition per row on
2132 the unindexed path, and a one-element tuple costs what the plain `==`
2133 it replaced did).
2134 """
2135 if op == "in":
2136 members = resolved if isinstance(resolved, (tuple, list, set, frozenset)) else (resolved,)
2137 elif isinstance(resolved, tuple):
2138 members = resolved
2139 elif resolved is None:
2140 return ()
2141 else:
2142 return (str(resolved),)
2143 return {str(item) for item in members if item is not None}
2144
2145
2146def _condition_matches(op: str, actual: str | None, resolved: Any, *, unknown: bool = False) -> bool:
2147 """Does one condition hold? ``unknown`` is the answer for an ordered
2148 condition that cannot be judged (``_ordered_condition_matches``): False
2149 where a match grants or selects something, True where it refuses."""
2150 if op == "in":
2151 allowed = _equality_match_values(op, resolved)
2152 return actual is not None and actual in allowed
2153 if op == "eq":
2154 # `actual is not None` is the fail-closed half of this line, and it
2155 # is what every other positive operator here already had (`in`, `eq`
2156 # against a set-valued $-variable, the ordered ops). Without it a
2157 # scalar that resolves to nothing -- $user_id for an anonymous
2158 # visitor, $account_id for a signed-in user with no account -- compared
2159 # None == None against a record that has no such key at all, and
2160 # the rule MATCHED: every row of a collection whose records.tsv
2161 # header lacks the column (a column exists only once some record
2162 # has been written with it) was readable, and updatable/deletable
2163 # where the rule said so. The same column present but empty was
2164 # always refused ("" != None), which is why this survived: the hole
2165 # closed itself the first time anyone wrote the field.
2166 #
2167 # Deliberately NOT "only when the value came from a $-variable": a
2168 # literal null is refused too. That literal was the same trap
2169 # (matches every row until the column first appears, then none), is
2170 # undocumented and untested, and the other filter parsers in the
2171 # repo (object_rollups, object_materialize) reject a null filter
2172 # value outright. One rule with no provenance to track is also the
2173 # only one an index planner can mirror without a "rows lacking the
2174 # field" bucket. `ne` is untouched: see tests/
2175 # test_permission_missing_column.py for the pinned table.
2176 #
2177 # The set itself comes from _equality_match_values (one value for a
2178 # scalar, none for a None, the members for a $-variable that
2179 # resolved to a tuple) so that the index planner asks the same
2180 # function instead of mirroring this line.
2181 return actual is not None and actual in _equality_match_values(op, resolved)
2182 if op == "ne":
2183 if isinstance(resolved, tuple):
2184 return actual is None or actual not in {_string_value(item) for item in resolved}
2185 return actual != _string_value(resolved)
2186 if op in _ORDERED_FILTER_OPERATORS:
2187 verdict = _ordered_condition_matches(op, actual, resolved)
2188 return unknown if verdict is None else verdict
2189 raise ValueError(f"Unknown filter operator: {op}")
2190
2191
2192def _ordered_condition_matches(op: str, actual: str | None, resolved: Any) -> bool | None:
2193 """One ordered condition: True, False, or None when it cannot be judged.
2194
2195 None (UNKNOWN) is returned when there is nothing to compare: a field the
2196 row does not have, a bound that resolved to nothing or to a set, or a
2197 bound that is a number or a date while the stored value is not one of
2198 the same kind (blank, or text). The caller decides what UNKNOWN means,
2199 by what the condition is for (see ``_record_matches_filter``): an allow
2200 does not match, a deny holds. Before, every one of these answered
2201 "no match", which for a deny meant "allowed" -- a deny over dates
2202 refused nothing on a row stamped with a zone, because comparing a naive
2203 and an aware datetime raised TypeError and that was read as no match.
2204 """
2205 if actual is None or resolved is None or isinstance(resolved, (tuple, list, set, frozenset)):
2206 return None
2207 expected = str(resolved)
2208 left, right = _comparable_filter_pair(actual, expected)
2209 if left is None:
2210 return None
2211 try:
2212 if op == "gte":
2213 return left >= right
2214 if op == "lte":
2215 return left <= right
2216 if op == "gt":
2217 return left > right
2218 return left < right
2219 except TypeError: # pragma: no cover - the pair is always one kind
2220 return None
2221
2222
2223def _comparable_filter_pair(actual: str, expected: str) -> tuple[Any, Any]:
2224 """Return both sides coerced to the same comparable type.
2225
2226 Numbers first, then ISO dates and datetimes, both read in UTC (see
2227 ``_filter_datetime``), so any two of those order as instants and never
2228 raise. When neither parse fits both sides: a bound that is itself a
2229 number or a date cannot be compared with the stored value, and
2230 ``(None, None)`` says so; a bound that is plain text is compared with
2231 the stored text as text, which also orders zero-padded ISO text.
2232 """
2233 left_number, right_number = _filter_number(actual), _filter_number(expected)
2234 if left_number is not None and right_number is not None:
2235 return left_number, right_number
2236 left_time, right_time = _filter_datetime(actual), _filter_datetime(expected)
2237 if left_time is not None and right_time is not None:
2238 return left_time, right_time
2239 if right_number is not None or right_time is not None:
2240 return None, None
2241 return actual, expected
2242
2243
2244def _filter_number(value: str) -> float | None:
2245 try:
2246 number = float(value)
2247 except (TypeError, ValueError):
2248 return None
2249 return number if math.isfinite(number) else None
2250
2251
2252def _filter_datetime(value: str) -> datetime | None:
2253 """An ISO date or datetime as an aware UTC instant, else None.
2254
2255 The same reading as a rule's time window (``_parse_timestamp``, S91 of
2256 docs/dron-write-semantics.md) and as the engine's own stamps: a trailing
2257 ``Z`` is UTC, a value with no offset is UTC, and a date alone is UTC
2258 midnight. So a date bound and a ``created_at`` stamped with ``Z`` compare,
2259 which they did not while a date alone was read as a naive datetime.
2260 """
2261 try:
2262 return _normalize_datetime(datetime.fromisoformat(value.replace("Z", "+00:00")))
2263 except (TypeError, ValueError, OverflowError):
2264 return None
2265
2266
2267def _resolve_filter_value(value: Any, subject: PermissionSubject, *, collection: str | None = None) -> Any:
2268 if value == "$user_id":
2269 return subject.user_id
2270 if value == "$account_id":
2271 return subject.account_id
2272 if value == "$accessible_projects":
2273 return tuple(subject.project_ids)
2274 if value == "$owned_projects":
2275 return tuple(subject.owned_project_ids)
2276 if value == "$writable_projects":
2277 return tuple(subject.writable_project_ids)
2278 # Collection-aware sharing: the ids of THIS collection's records shared
2279 # with the subject (any grant, and write grants). Empty tuple when the
2280 # collection is unknown or nothing is shared -- so `{id: $shared_records}`
2281 # simply matches nothing rather than erroring or matching a same-id row in
2282 # a different collection.
2283 if value == "$shared_records":
2284 return tuple(subject.shared_records.get(collection, ())) if collection else ()
2285 if value == "$writable_shared_records":
2286 return tuple(subject.writable_shared_records.get(collection, ())) if collection else ()
2287 return value
2288
2289
2290def _subject_roles(subject: PermissionSubject, policy: PermissionPolicy) -> frozenset[str]:
2291 roles = set(subject.roles)
2292 if subject.user_id is not None:
2293 roles.update(policy.user_roles.get(subject.user_id, ()))
2294 return frozenset(roles)
2295
2296
2297def _has_admin_role(roles: frozenset[str], policy: PermissionPolicy) -> bool:
2298 return any(role in roles for role in policy.admin_roles)
2299
2300
2301def _string_value(value: Any) -> str | None:
2302 if value is None:
2303 return None
2304 return str(value)
2305
2306
2307def _optional_string(value: Any) -> str | None:
2308 if value is None:
2309 return None
2310 if isinstance(value, str):
2311 return value
2312 if isinstance(value, (int, float)) and not isinstance(value, bool):
2313 return str(value)
2314 raise ValueError(f"Expected string-compatible value, got {type(value).__name__}")
2315
2316
2317def _required_string(payload: Mapping[str, Any], key: str) -> str:
2318 if key not in payload:
2319 raise ValueError(f"Permission field '{key}' is required")
2320 value = _optional_string(payload[key])
2321 if value is None or not value:
2322 raise ValueError(f"Permission field '{key}' must be a non-empty string")
2323 return value
2324
2325
2326def _string_tuple(value: Any, field_name: str) -> tuple[str, ...]:
2327 return tuple(sorted(_string_set(value, field_name)))
2328
2329
2330def _string_set(value: Any, field_name: str) -> frozenset[str]:
2331 if not isinstance(value, (list, tuple, set, frozenset)):
2332 raise ValueError(f"Permission field '{field_name}' must be a list of strings")
2333
2334 values: set[str] = set()
2335 for item in value:
2336 string_value = _optional_string(item)
2337 if string_value is None or not string_value:
2338 raise ValueError(f"Permission field '{field_name}' contains an invalid value")
2339 values.add(string_value)
2340 return frozenset(values)
2341
2342
2343def _parse_timestamp(value: str) -> datetime | None:
2344 try:
2345 parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
2346 except ValueError:
2347 return None
2348 return _normalize_datetime(parsed)
2349
2350
2351def _normalize_datetime(value: datetime) -> datetime:
2352 if value.tzinfo is None:
2353 return value.replace(tzinfo=timezone.utc)
2354 return value.astimezone(timezone.utc)