Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_permissions.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_permissions.py · 31.8 KB · 936 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 math
10from dataclasses import dataclass, field, replace
11from datetime import datetime, timezone
12from typing import Any, Iterable, Mapping
13
14from object_namespace import parse_user_object_id
15
16PUBLIC_USER_ID = "public"
17
18# Query/filter operator vocabulary (plan/vocabulary/58-query-filter-spec.md).
19# `eq` is the implicit default everywhere a filter condition omits an
20# operator (a bare literal or $-variable, the pre-existing row-filter/
21# transition-guard shape). The others are additive: `record_matches_filter`
22# below is the ONE evaluator for all of it -- row filters, transition
23# guards, and 58's field filters all reuse it rather than each carrying
24# their own condition matcher.
25FILTER_OPERATORS = frozenset({"eq", "ne", "in", "gte", "lte", "gt", "lt"})
26_ORDERED_FILTER_OPERATORS = frozenset({"gte", "lte", "gt", "lt"})
27
28READ = "read"
29CREATE = "create"
30UPDATE = "update"
31DELETE = "delete"
32EXECUTE = "execute"
33SOURCE = "source"
34STATE = "state"
35LOGS = "logs"
36FILES = "files"
37VERSIONS = "versions"
38ADMIN = "admin"
39SHARE = "share"
40
41PUBLIC_READ_ACTIONS = frozenset({READ, EXECUTE})
42OWNER_ACTIONS = frozenset({READ, UPDATE, DELETE, EXECUTE, SOURCE, STATE, LOGS, FILES, VERSIONS, SHARE})
43ADMIN_ACTIONS = frozenset(
44 {READ, CREATE, UPDATE, DELETE, EXECUTE, SOURCE, STATE, LOGS, FILES, VERSIONS, ADMIN, SHARE}
45)
46ACCESS_MODES = frozenset({"public", "password", "registered", "subscription", "role_based", "private"})
47RULE_EFFECTS = frozenset({"allow", "deny"})
48
49
50@dataclass(frozen=True)
51class PermissionSubject:
52 """The authenticated actor being checked.
53
54 ``project_ids`` are the projects shared with this subject and
55 ``writable_project_ids`` narrows that to grants with ``permission ==
56 "write"``; both are resolved by the server from grant records before
57 checks run — the engine itself stays pure and does no IO.
58
59 ``shared_records`` / ``writable_shared_records`` are the generic
60 equivalent for the sharing capability: per-collection sets of record ids
61 granted to this subject via ``record_shares`` (any grant, and write
62 grants). Resolved collection-aware by ``$shared_records`` /
63 ``$writable_shared_records`` in a row filter (the collection being checked
64 is threaded in), so a shared task never leaks a same-id row in another
65 collection.
66 """
67
68 user_id: str | None = None
69 account_id: str | None = None
70 roles: tuple[str, ...] = ()
71 subscriptions: tuple[str, ...] = ()
72 project_ids: tuple[str, ...] = ()
73 owned_project_ids: tuple[str, ...] = ()
74 writable_project_ids: tuple[str, ...] = ()
75 shared_records: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
76 writable_shared_records: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
77
78 @classmethod
79 def anonymous(cls) -> "PermissionSubject":
80 return cls()
81
82 @property
83 def is_authenticated(self) -> bool:
84 return self.user_id is not None
85
86 def with_projects(
87 self,
88 project_ids: Iterable[str],
89 owned_project_ids: Iterable[str] = (),
90 writable_project_ids: Iterable[str] = (),
91 ) -> "PermissionSubject":
92 return replace(
93 self,
94 project_ids=tuple(project_ids),
95 owned_project_ids=tuple(owned_project_ids),
96 writable_project_ids=tuple(writable_project_ids),
97 )
98
99 def with_shares(
100 self,
101 shared_records: Mapping[str, Iterable[str]],
102 writable_shared_records: Mapping[str, Iterable[str]] | None = None,
103 ) -> "PermissionSubject":
104 return replace(
105 self,
106 shared_records={k: tuple(v) for k, v in dict(shared_records).items()},
107 writable_shared_records={
108 k: tuple(v) for k, v in dict(writable_shared_records or {}).items()
109 },
110 )
111
112
113@dataclass(frozen=True)
114class PermissionRule:
115 """One allow/deny rule.
116
117 Principal values intentionally stay stringly and portable:
118 ``public``, ``registered``, ``owner``, ``role:admin``, ``user:42``,
119 ``account:acme``, or ``subscription:pro``.
120 """
121
122 effect: str
123 actions: frozenset[str]
124 principal: str
125 collection: str | None = None
126 object_id: str | None = None
127 row_filter: Mapping[str, Any] = field(default_factory=dict)
128 fields: frozenset[str] | None = None
129 denied_fields: frozenset[str] = field(default_factory=frozenset)
130 valid_from: str | None = None
131 expires_at: str | None = None
132 reason: str = ""
133 package: str | None = None
134
135 @classmethod
136 def allow(
137 cls,
138 principal: str,
139 actions: Iterable[str],
140 *,
141 collection: str | None = None,
142 object_id: str | None = None,
143 row_filter: Mapping[str, Any] | None = None,
144 fields: Iterable[str] | None = None,
145 denied_fields: Iterable[str] = (),
146 valid_from: str | None = None,
147 expires_at: str | None = None,
148 reason: str = "",
149 ) -> "PermissionRule":
150 return cls(
151 effect="allow",
152 principal=principal,
153 actions=frozenset(actions),
154 collection=collection,
155 object_id=object_id,
156 row_filter=dict(row_filter or {}),
157 fields=frozenset(fields) if fields is not None else None,
158 denied_fields=frozenset(denied_fields),
159 valid_from=valid_from,
160 expires_at=expires_at,
161 reason=reason,
162 )
163
164 @classmethod
165 def deny(
166 cls,
167 principal: str,
168 actions: Iterable[str],
169 *,
170 collection: str | None = None,
171 object_id: str | None = None,
172 row_filter: Mapping[str, Any] | None = None,
173 valid_from: str | None = None,
174 expires_at: str | None = None,
175 reason: str = "",
176 ) -> "PermissionRule":
177 return cls(
178 effect="deny",
179 principal=principal,
180 actions=frozenset(actions),
181 collection=collection,
182 object_id=object_id,
183 row_filter=dict(row_filter or {}),
184 valid_from=valid_from,
185 expires_at=expires_at,
186 reason=reason,
187 )
188
189
190@dataclass(frozen=True)
191class PermissionPolicy:
192 """Portable server-side permission state.
193
194 ``roles`` names broad roles such as ``admin`` or ``sales``. ``user_roles``
195 assigns users to roles. ``rules`` contains grants and explicit denies.
196 """
197
198 access_mode: str = "role_based"
199 roles: Mapping[str, Mapping[str, Any]] = field(default_factory=dict)
200 user_roles: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
201 rules: tuple[PermissionRule, ...] = ()
202 admin_roles: tuple[str, ...] = ("admin", "superuser")
203
204
205@dataclass(frozen=True)
206class PermissionDecision:
207 """The result Scroll and the server can explain."""
208
209 allowed: bool
210 reason: str
211 code: str
212 http_status: int
213 row_filter: Mapping[str, Any] = field(default_factory=dict)
214 fields: frozenset[str] | None = None
215 denied_fields: frozenset[str] = field(default_factory=frozenset)
216
217 @classmethod
218 def allow(
219 cls,
220 reason: str,
221 *,
222 row_filter: Mapping[str, Any] | None = None,
223 fields: Iterable[str] | None = None,
224 denied_fields: Iterable[str] = (),
225 ) -> "PermissionDecision":
226 return cls(
227 True,
228 reason,
229 "allowed",
230 200,
231 row_filter=dict(row_filter or {}),
232 fields=frozenset(fields) if fields is not None else None,
233 denied_fields=frozenset(denied_fields),
234 )
235
236 @classmethod
237 def deny(
238 cls,
239 reason: str,
240 *,
241 code: str = "forbidden",
242 http_status: int = 403,
243 ) -> "PermissionDecision":
244 return cls(False, reason, code, http_status)
245
246
247def check_permission(
248 subject: PermissionSubject | None,
249 action: str,
250 *,
251 policy: PermissionPolicy | None = None,
252 collection: str | None = None,
253 object_id: str | None = None,
254 record: Mapping[str, Any] | None = None,
255 now: datetime | None = None,
256) -> PermissionDecision:
257 """Return allow/deny/reason for one action.
258
259 If a matching allow rule has a row filter and no record was supplied, the
260 decision is allowed with the filter attached so list/query code can apply it.
261 """
262
263 actor = subject or PermissionSubject.anonymous()
264 normalized_action = action.lower()
265 explicit_policy = policy is not None
266 active_policy = policy or PermissionPolicy(access_mode="public")
267 roles = _subject_roles(actor, active_policy)
268 checked_at = now or datetime.now(timezone.utc)
269
270 if _has_admin_role(roles, active_policy):
271 return PermissionDecision.allow("admin role")
272
273 explicit_deny = _matching_rule(
274 active_policy.rules,
275 actor,
276 roles,
277 normalized_action,
278 collection=collection,
279 object_id=object_id,
280 record=record,
281 effect="deny",
282 now=checked_at,
283 )
284 if explicit_deny is not None:
285 return PermissionDecision.deny(explicit_deny.reason or "explicit deny")
286
287 mode_decision = _access_mode_decision(
288 actor,
289 active_policy.access_mode,
290 normalized_action,
291 collection=collection,
292 object_id=object_id,
293 )
294 if mode_decision.allowed:
295 return mode_decision
296
297 allow_rule = _matching_rule(
298 active_policy.rules,
299 actor,
300 roles,
301 normalized_action,
302 collection=collection,
303 object_id=object_id,
304 record=record,
305 effect="allow",
306 now=checked_at,
307 )
308 if allow_rule is not None:
309 return PermissionDecision.allow(
310 allow_rule.reason or f"{allow_rule.principal} rule",
311 row_filter=allow_rule.row_filter,
312 fields=allow_rule.fields,
313 denied_fields=allow_rule.denied_fields,
314 )
315
316 fallback = _owner_fallback(
317 actor,
318 normalized_action,
319 object_id=object_id,
320 record=record,
321 allow_system_public=not explicit_policy or active_policy.access_mode == "public",
322 )
323 if fallback.allowed:
324 return fallback
325
326 return mode_decision
327
328
329def subject_from_dict(payload: Mapping[str, Any] | None) -> PermissionSubject:
330 """Build a subject from JSON-compatible data."""
331 if payload is None:
332 return PermissionSubject.anonymous()
333 if not isinstance(payload, Mapping):
334 raise ValueError("Permission subject must be an object")
335
336 return PermissionSubject(
337 user_id=_optional_string(payload.get("user_id")),
338 account_id=_optional_string(payload.get("account_id")),
339 roles=_string_tuple(payload.get("roles", ()), "subject.roles"),
340 subscriptions=_string_tuple(payload.get("subscriptions", ()), "subject.subscriptions"),
341 project_ids=_string_tuple(payload.get("project_ids", ()), "subject.project_ids"),
342 owned_project_ids=_string_tuple(
343 payload.get("owned_project_ids", ()), "subject.owned_project_ids"
344 ),
345 writable_project_ids=_string_tuple(
346 payload.get("writable_project_ids", ()), "subject.writable_project_ids"
347 ),
348 )
349
350
351def rule_from_dict(payload: Mapping[str, Any]) -> PermissionRule:
352 """Build one rule from JSON-compatible data."""
353 if not isinstance(payload, Mapping):
354 raise ValueError("Permission rule must be an object")
355
356 effect = _required_string(payload, "effect").lower()
357 if effect not in RULE_EFFECTS:
358 raise ValueError(f"Permission rule effect must be one of: {', '.join(sorted(RULE_EFFECTS))}")
359
360 actions = _string_set(payload.get("actions"), "rule.actions")
361 if not actions:
362 raise ValueError("Permission rule actions must not be empty")
363
364 principal = _required_string(payload, "principal")
365 row_filter = payload.get("row_filter", {})
366 if not isinstance(row_filter, Mapping):
367 raise ValueError("Permission rule row_filter must be an object")
368
369 fields_payload = payload.get("fields")
370 fields = _string_set(fields_payload, "rule.fields") if fields_payload is not None else None
371 denied_fields = _string_set(payload.get("denied_fields", ()), "rule.denied_fields")
372
373 return PermissionRule(
374 effect=effect,
375 actions=frozenset(actions),
376 principal=principal,
377 collection=_optional_string(payload.get("collection")),
378 object_id=_optional_string(payload.get("object_id")),
379 row_filter=dict(row_filter),
380 fields=frozenset(fields) if fields is not None else None,
381 denied_fields=frozenset(denied_fields),
382 valid_from=_optional_string(payload.get("valid_from")),
383 expires_at=_optional_string(payload.get("expires_at")),
384 reason=_optional_string(payload.get("reason")) or "",
385 package=_optional_string(payload.get("package")),
386 )
387
388
389def policy_from_dict(payload: Mapping[str, Any]) -> PermissionPolicy:
390 """Build a policy from JSON-compatible data."""
391 if not isinstance(payload, Mapping):
392 raise ValueError("Permission policy must be an object")
393
394 access_mode = _optional_string(payload.get("access_mode")) or "role_based"
395 if access_mode not in ACCESS_MODES:
396 raise ValueError(f"Permission access_mode must be one of: {', '.join(sorted(ACCESS_MODES))}")
397
398 roles_payload = payload.get("roles", {})
399 if not isinstance(roles_payload, Mapping):
400 raise ValueError("Permission policy roles must be an object")
401 roles: dict[str, dict[str, Any]] = {}
402 for role, metadata in roles_payload.items():
403 role_name = _string_value(role)
404 if not role_name:
405 raise ValueError("Permission role names must be strings")
406 if not isinstance(metadata, Mapping):
407 raise ValueError(f"Permission role metadata must be an object: {role_name}")
408 roles[role_name] = dict(metadata)
409
410 user_roles_payload = payload.get("user_roles", {})
411 if not isinstance(user_roles_payload, Mapping):
412 raise ValueError("Permission policy user_roles must be an object")
413 user_roles: dict[str, tuple[str, ...]] = {}
414 for user_id, role_names in user_roles_payload.items():
415 normalized_user_id = _string_value(user_id)
416 if not normalized_user_id:
417 raise ValueError("Permission user_roles keys must be strings")
418 user_roles[normalized_user_id] = _string_tuple(
419 role_names,
420 f"user_roles.{normalized_user_id}",
421 )
422
423 rules_payload = payload.get("rules", ())
424 if not isinstance(rules_payload, (list, tuple)):
425 raise ValueError("Permission policy rules must be a list")
426 rules = tuple(rule_from_dict(rule) for rule in rules_payload)
427
428 return PermissionPolicy(
429 access_mode=access_mode,
430 roles=roles,
431 user_roles=user_roles,
432 rules=rules,
433 admin_roles=_string_tuple(payload.get("admin_roles", ("admin", "superuser")), "admin_roles"),
434 )
435
436
437def rule_to_dict(rule: PermissionRule) -> dict[str, Any]:
438 """Return a JSON-compatible rule."""
439 payload: dict[str, Any] = {
440 "effect": rule.effect,
441 "actions": sorted(rule.actions),
442 "principal": rule.principal,
443 "row_filter": dict(rule.row_filter),
444 "denied_fields": sorted(rule.denied_fields),
445 "reason": rule.reason,
446 }
447
448 if rule.collection is not None:
449 payload["collection"] = rule.collection
450 if rule.object_id is not None:
451 payload["object_id"] = rule.object_id
452 if rule.fields is not None:
453 payload["fields"] = sorted(rule.fields)
454 if rule.valid_from is not None:
455 payload["valid_from"] = rule.valid_from
456 if rule.expires_at is not None:
457 payload["expires_at"] = rule.expires_at
458 if rule.package is not None:
459 payload["package"] = rule.package
460
461 return payload
462
463
464def policy_to_dict(policy: PermissionPolicy) -> dict[str, Any]:
465 """Return a JSON-compatible policy."""
466 return {
467 "access_mode": policy.access_mode,
468 "roles": {role: dict(metadata) for role, metadata in sorted(policy.roles.items())},
469 "user_roles": {
470 user_id: list(role_names)
471 for user_id, role_names in sorted(policy.user_roles.items())
472 },
473 "rules": [rule_to_dict(rule) for rule in policy.rules],
474 "admin_roles": list(policy.admin_roles),
475 }
476
477
478def decision_to_dict(decision: PermissionDecision) -> dict[str, Any]:
479 """Return a JSON-compatible permission decision."""
480 return {
481 "allowed": decision.allowed,
482 "reason": decision.reason,
483 "code": decision.code,
484 "http_status": decision.http_status,
485 "row_filter": dict(decision.row_filter),
486 "fields": sorted(decision.fields) if decision.fields is not None else None,
487 "denied_fields": sorted(decision.denied_fields),
488 }
489
490
491def subject_roles(subject: PermissionSubject, policy: PermissionPolicy) -> frozenset[str]:
492 """Return roles assigned directly and through the active policy."""
493 return _subject_roles(subject, policy)
494
495
496def subject_has_admin_role(subject: PermissionSubject, policy: PermissionPolicy) -> bool:
497 """Return True when the subject has one of the policy admin roles."""
498 return _has_admin_role(_subject_roles(subject, policy), policy)
499
500
501def record_matches_filter(
502 record: Mapping[str, Any],
503 row_filter: Mapping[str, Any],
504 subject: PermissionSubject,
505) -> bool:
506 """Return True when a record's stored values satisfy a filter/guard.
507
508 Shared by row filters, schema transition guards, and 58's query/filter
509 layer -- the one flat-condition evaluator in the codebase. Each key's
510 value is one of:
511
512 - a literal string, or a $-variable (see ``_resolve_filter_value``):
513 the pre-existing row-filter/transition-guard shape, an implicit
514 ``eq``. An empty stored field never matches a $-variable.
515 - a single condition, ``{"op": <FILTER_OPERATORS>, "value": ...}``
516 (see ``filter_condition``).
517 - a list of such conditions, ANDed -- lets one field carry more than
518 one clause (a date range: ``created_at.gte=X&created_at.lte=Y``).
519
520 ``in``'s value (and a $-variable that resolves to a tuple, e.g.
521 ``$accessible_projects``) is treated as a membership set. ``gte``/
522 ``lte``/``gt``/``lt`` compare numerically when both sides parse as a
523 number, then as an ISO date/datetime, else fall back to string
524 comparison -- callers that need a guaranteed-correct ordered compare
525 (58's HTTP/MCP surfaces) type-validate the value against the field's
526 schema type before it ever reaches this matcher.
527 """
528 return _record_matches_filter(record, row_filter, subject)
529
530
531def filter_condition(op: str, value: Any) -> dict[str, Any]:
532 """Build one ``{"op": op, "value": value}`` condition for a row_filter/
533 query-filter value passed to ``record_matches_filter``."""
534 return {"op": op, "value": value}
535
536
537def principal_matches(
538 principal: str,
539 subject: PermissionSubject,
540 policy: PermissionPolicy,
541 *,
542 record: Mapping[str, Any] | None = None,
543) -> bool:
544 """Return True when a portable principal matches the subject."""
545 return _principal_matches(
546 principal,
547 subject,
548 _subject_roles(subject, policy),
549 record=record,
550 )
551
552
553def _access_mode_decision(
554 subject: PermissionSubject,
555 access_mode: str,
556 action: str,
557 *,
558 collection: str | None,
559 object_id: str | None,
560) -> PermissionDecision:
561 mode = access_mode.lower()
562
563 if mode == "public":
564 if action in PUBLIC_READ_ACTIONS:
565 return PermissionDecision.allow("public access")
566 return PermissionDecision.deny("public access is read-only")
567
568 if mode == "registered":
569 if subject.is_authenticated and action in PUBLIC_READ_ACTIONS:
570 return PermissionDecision.allow("registered access")
571 return PermissionDecision.deny(
572 "registered user required",
573 code="authentication_required",
574 http_status=401,
575 )
576
577 if mode == "subscription":
578 if subject.subscriptions and action in PUBLIC_READ_ACTIONS:
579 return PermissionDecision.allow("subscription access")
580 if subject.subscriptions:
581 return PermissionDecision.deny("subscription access is read-only")
582 return PermissionDecision.deny(
583 "subscription required",
584 code="payment_required",
585 http_status=402,
586 )
587
588 if mode == "password":
589 return PermissionDecision.deny(
590 "password gate must authenticate before policy check",
591 code="authentication_required",
592 http_status=401,
593 )
594
595 if mode == "role_based":
596 return PermissionDecision.deny("no matching role rule")
597
598 if mode == "private":
599 return _owner_fallback(
600 subject,
601 action,
602 object_id=object_id,
603 record=None,
604 allow_system_public=False,
605 )
606
607 return PermissionDecision.deny(f"unknown access mode: {access_mode}")
608
609
610def _matching_rule(
611 rules: Iterable[PermissionRule],
612 subject: PermissionSubject,
613 roles: frozenset[str],
614 action: str,
615 *,
616 collection: str | None,
617 object_id: str | None,
618 record: Mapping[str, Any] | None,
619 effect: str,
620 now: datetime,
621) -> PermissionRule | None:
622 for rule in rules:
623 if rule.effect != effect:
624 continue
625 if not _rule_is_active(rule, now):
626 continue
627 if not _action_matches(rule, action):
628 continue
629 if not _resource_matches(rule, collection=collection, object_id=object_id):
630 continue
631 if not _principal_matches(rule.principal, subject, roles, record=record):
632 continue
633 if (
634 record is not None
635 and rule.row_filter
636 and not _record_matches_filter(record, rule.row_filter, subject, collection=collection)
637 ):
638 continue
639 return rule
640 return None
641
642
643def _rule_is_active(rule: PermissionRule, now: datetime) -> bool:
644 checked_at = _normalize_datetime(now)
645
646 if rule.valid_from is not None:
647 valid_from = _parse_timestamp(rule.valid_from)
648 if valid_from is None or checked_at < valid_from:
649 return False
650
651 if rule.expires_at is not None:
652 expires_at = _parse_timestamp(rule.expires_at)
653 if expires_at is None or checked_at >= expires_at:
654 return False
655
656 return True
657
658
659def _action_matches(rule: PermissionRule, action: str) -> bool:
660 return "*" in rule.actions or action in rule.actions
661
662
663def _resource_matches(
664 rule: PermissionRule,
665 *,
666 collection: str | None,
667 object_id: str | None,
668) -> bool:
669 if rule.collection is not None and rule.collection != collection:
670 return False
671 if rule.object_id is not None and rule.object_id != object_id:
672 return False
673 return True
674
675
676def _principal_matches(
677 principal: str,
678 subject: PermissionSubject,
679 roles: frozenset[str],
680 *,
681 record: Mapping[str, Any] | None,
682) -> bool:
683 if principal == "public":
684 return True
685 if principal == "registered":
686 return subject.is_authenticated
687 if principal == "owner":
688 return _subject_owns(subject, record=record)
689 if principal.startswith("role:"):
690 return principal.removeprefix("role:") in roles
691 if principal.startswith("user:"):
692 return subject.user_id == principal.removeprefix("user:")
693 if principal.startswith("account:"):
694 return subject.account_id == principal.removeprefix("account:")
695 if principal.startswith("subscription:"):
696 return principal.removeprefix("subscription:") in subject.subscriptions
697 return False
698
699
700def _owner_fallback(
701 subject: PermissionSubject,
702 action: str,
703 *,
704 object_id: str | None,
705 record: Mapping[str, Any] | None,
706 allow_system_public: bool = True,
707) -> PermissionDecision:
708 if object_id:
709 parsed = parse_user_object_id(object_id)
710 if parsed is None and allow_system_public and action in PUBLIC_READ_ACTIONS:
711 return PermissionDecision.allow("system object public read")
712 if parsed is not None and subject.user_id == str(parsed[0]) and action in OWNER_ACTIONS:
713 return PermissionDecision.allow("object owner")
714
715 if record is not None and _subject_owns(subject, record=record) and action in OWNER_ACTIONS:
716 return PermissionDecision.allow("record owner")
717
718 return PermissionDecision.deny("not owner")
719
720
721def _subject_owns(
722 subject: PermissionSubject,
723 *,
724 record: Mapping[str, Any] | None,
725) -> bool:
726 if record is None or subject.user_id is None:
727 return False
728
729 for key in ("owner_id", "user_id", "created_by"):
730 if _string_value(record.get(key)) == subject.user_id:
731 return True
732
733 return False
734
735
736def _record_matches_filter(
737 record: Mapping[str, Any],
738 row_filter: Mapping[str, Any],
739 subject: PermissionSubject,
740 *,
741 collection: str | None = None,
742) -> bool:
743 for key, expected in row_filter.items():
744 actual = _string_value(record.get(key))
745 for condition in _iter_conditions(expected):
746 op, raw_value = _condition_op_value(condition)
747 resolved = _resolve_filter_value(raw_value, subject, collection=collection)
748 if not _condition_matches(op, actual, resolved):
749 return False
750 return True
751
752
753def _is_condition(value: Any) -> bool:
754 return isinstance(value, Mapping) and "op" in value
755
756
757def _iter_conditions(expected: Any) -> list[Any]:
758 """Split one row_filter value into its ANDed conditions.
759
760 A list is only ever treated as multiple conditions when EVERY item is
761 condition-shaped (``{"op": ...}``) -- anything else (a literal, a
762 $-variable string, one condition, or a $-variable already resolved to
763 a tuple by a caller) stays a single condition, so this never changes
764 behavior for the pre-existing row-filter/transition-guard callers,
765 none of which ever pass a list.
766 """
767 if isinstance(expected, list) and expected and all(_is_condition(item) for item in expected):
768 return list(expected)
769 return [expected]
770
771
772def _condition_op_value(condition: Any) -> tuple[str, Any]:
773 if _is_condition(condition):
774 op = str(condition.get("op") or "eq").strip().lower() or "eq"
775 return op, condition.get("value")
776 return "eq", condition
777
778
779def _condition_matches(op: str, actual: str | None, resolved: Any) -> bool:
780 if op == "in":
781 members = resolved if isinstance(resolved, (tuple, list, set, frozenset)) else (resolved,)
782 allowed = {_string_value(item) for item in members}
783 return actual is not None and actual in allowed
784 if op == "eq":
785 if isinstance(resolved, tuple):
786 # A $-variable (e.g. $accessible_projects) resolved to a
787 # membership set: matches the pre-existing eq-with-tuple
788 # behavior row filters have always relied on.
789 return actual is not None and actual in {_string_value(item) for item in resolved}
790 return actual == _string_value(resolved)
791 if op == "ne":
792 if isinstance(resolved, tuple):
793 return actual is None or actual not in {_string_value(item) for item in resolved}
794 return actual != _string_value(resolved)
795 if op in _ORDERED_FILTER_OPERATORS:
796 return _ordered_condition_matches(op, actual, resolved)
797 raise ValueError(f"Unknown filter operator: {op}")
798
799
800def _ordered_condition_matches(op: str, actual: str | None, resolved: Any) -> bool:
801 if actual is None:
802 return False
803 expected = _string_value(resolved)
804 if expected is None:
805 return False
806 left, right = _comparable_filter_pair(actual, expected)
807 try:
808 if op == "gte":
809 return left >= right
810 if op == "lte":
811 return left <= right
812 if op == "gt":
813 return left > right
814 return left < right
815 except TypeError:
816 return False
817
818
819def _comparable_filter_pair(actual: str, expected: str) -> tuple[Any, Any]:
820 """Return both sides coerced to the same comparable type.
821
822 Tries a numeric parse first, then an ISO date/datetime parse (which
823 also accepts a date-only string); falls back to the raw strings, which
824 still compares correctly for zero-padded ISO date/datetime text.
825 """
826 for parse in (_filter_number, _filter_datetime):
827 left = parse(actual)
828 right = parse(expected)
829 if left is not None and right is not None:
830 return left, right
831 return actual, expected
832
833
834def _filter_number(value: str) -> float | None:
835 try:
836 number = float(value)
837 except (TypeError, ValueError):
838 return None
839 return number if math.isfinite(number) else None
840
841
842def _filter_datetime(value: str) -> datetime | None:
843 try:
844 return datetime.fromisoformat(value.replace("Z", "+00:00"))
845 except (TypeError, ValueError):
846 return None
847
848
849def _resolve_filter_value(value: Any, subject: PermissionSubject, *, collection: str | None = None) -> Any:
850 if value == "$user_id":
851 return subject.user_id
852 if value == "$account_id":
853 return subject.account_id
854 if value == "$accessible_projects":
855 return tuple(subject.project_ids)
856 if value == "$owned_projects":
857 return tuple(subject.owned_project_ids)
858 if value == "$writable_projects":
859 return tuple(subject.writable_project_ids)
860 # Collection-aware sharing: the ids of THIS collection's records shared
861 # with the subject (any grant, and write grants). Empty tuple when the
862 # collection is unknown or nothing is shared -- so `{id: $shared_records}`
863 # simply matches nothing rather than erroring or matching a same-id row in
864 # a different collection.
865 if value == "$shared_records":
866 return tuple(subject.shared_records.get(collection, ())) if collection else ()
867 if value == "$writable_shared_records":
868 return tuple(subject.writable_shared_records.get(collection, ())) if collection else ()
869 return value
870
871
872def _subject_roles(subject: PermissionSubject, policy: PermissionPolicy) -> frozenset[str]:
873 roles = set(subject.roles)
874 if subject.user_id is not None:
875 roles.update(policy.user_roles.get(subject.user_id, ()))
876 return frozenset(roles)
877
878
879def _has_admin_role(roles: frozenset[str], policy: PermissionPolicy) -> bool:
880 return any(role in roles for role in policy.admin_roles)
881
882
883def _string_value(value: Any) -> str | None:
884 if value is None:
885 return None
886 return str(value)
887
888
889def _optional_string(value: Any) -> str | None:
890 if value is None:
891 return None
892 if isinstance(value, str):
893 return value
894 if isinstance(value, (int, float)) and not isinstance(value, bool):
895 return str(value)
896 raise ValueError(f"Expected string-compatible value, got {type(value).__name__}")
897
898
899def _required_string(payload: Mapping[str, Any], key: str) -> str:
900 if key not in payload:
901 raise ValueError(f"Permission field '{key}' is required")
902 value = _optional_string(payload[key])
903 if value is None or not value:
904 raise ValueError(f"Permission field '{key}' must be a non-empty string")
905 return value
906
907
908def _string_tuple(value: Any, field_name: str) -> tuple[str, ...]:
909 return tuple(sorted(_string_set(value, field_name)))
910
911
912def _string_set(value: Any, field_name: str) -> frozenset[str]:
913 if not isinstance(value, (list, tuple, set, frozenset)):
914 raise ValueError(f"Permission field '{field_name}' must be a list of strings")
915
916 values: set[str] = set()
917 for item in value:
918 string_value = _optional_string(item)
919 if string_value is None or not string_value:
920 raise ValueError(f"Permission field '{field_name}' contains an invalid value")
921 values.add(string_value)
922 return frozenset(values)
923
924
925def _parse_timestamp(value: str) -> datetime | None:
926 try:
927 parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
928 except ValueError:
929 return None
930 return _normalize_datetime(parsed)
931
932
933def _normalize_datetime(value: datetime) -> datetime:
934 if value.tzinfo is None:
935 return value.replace(tzinfo=timezone.utc)
936 return value.astimezone(timezone.utc)