resource-engine 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. resource_engine/__init__.py +96 -0
  2. resource_engine/application/__init__.py +1 -0
  3. resource_engine/application/actions.py +48 -0
  4. resource_engine/application/context.py +111 -0
  5. resource_engine/application/events.py +54 -0
  6. resource_engine/application/hooks.py +272 -0
  7. resource_engine/application/idempotency.py +277 -0
  8. resource_engine/application/manager.py +1987 -0
  9. resource_engine/application/query.py +47 -0
  10. resource_engine/application/registry.py +137 -0
  11. resource_engine/application/relations.py +470 -0
  12. resource_engine/application/resource.py +984 -0
  13. resource_engine/application/searching.py +162 -0
  14. resource_engine/application/settings.py +169 -0
  15. resource_engine/application/slots.py +67 -0
  16. resource_engine/application/state_machines.py +177 -0
  17. resource_engine/application/timers.py +347 -0
  18. resource_engine/application/transaction.py +100 -0
  19. resource_engine/application/views.py +239 -0
  20. resource_engine/audit/__init__.py +40 -0
  21. resource_engine/audit/export.py +280 -0
  22. resource_engine/audit/history.py +165 -0
  23. resource_engine/audit/janitor.py +257 -0
  24. resource_engine/audit/model.py +98 -0
  25. resource_engine/audit/recorder.py +145 -0
  26. resource_engine/audit/resource.py +68 -0
  27. resource_engine/audit/seal.py +327 -0
  28. resource_engine/audit/sink.py +69 -0
  29. resource_engine/authz/__init__.py +72 -0
  30. resource_engine/authz/apikeys.py +300 -0
  31. resource_engine/authz/base.py +143 -0
  32. resource_engine/authz/catalog.py +291 -0
  33. resource_engine/authz/conditions.py +416 -0
  34. resource_engine/authz/config.py +77 -0
  35. resource_engine/authz/evaluator.py +382 -0
  36. resource_engine/authz/external.py +249 -0
  37. resource_engine/authz/fields.py +44 -0
  38. resource_engine/authz/model.py +145 -0
  39. resource_engine/authz/resources.py +289 -0
  40. resource_engine/authz/roles.py +101 -0
  41. resource_engine/cache.py +144 -0
  42. resource_engine/calls.py +100 -0
  43. resource_engine/capabilities.py +145 -0
  44. resource_engine/composite.py +295 -0
  45. resource_engine/documents/__init__.py +69 -0
  46. resource_engine/documents/content.py +57 -0
  47. resource_engine/documents/events.py +49 -0
  48. resource_engine/documents/janitor.py +93 -0
  49. resource_engine/documents/machine.py +38 -0
  50. resource_engine/documents/manager.py +704 -0
  51. resource_engine/documents/model.py +91 -0
  52. resource_engine/documents/pipeline.py +98 -0
  53. resource_engine/documents/processors.py +320 -0
  54. resource_engine/documents/resource.py +39 -0
  55. resource_engine/domain/__init__.py +10 -0
  56. resource_engine/domain/events.py +50 -0
  57. resource_engine/domain/exceptions.py +23 -0
  58. resource_engine/email.py +417 -0
  59. resource_engine/errors.py +562 -0
  60. resource_engine/explorer.py +133 -0
  61. resource_engine/exports.py +687 -0
  62. resource_engine/generation.py +233 -0
  63. resource_engine/i18n.py +251 -0
  64. resource_engine/identity.py +46 -0
  65. resource_engine/integration.py +80 -0
  66. resource_engine/jobs.py +390 -0
  67. resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
  68. resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
  69. resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
  70. resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
  71. resource_engine/logs.py +201 -0
  72. resource_engine/messaging/__init__.py +73 -0
  73. resource_engine/messaging/asyncapi.py +529 -0
  74. resource_engine/messaging/cloudevents.py +98 -0
  75. resource_engine/messaging/consumer.py +165 -0
  76. resource_engine/messaging/delivery.py +115 -0
  77. resource_engine/messaging/envelope.py +193 -0
  78. resource_engine/messaging/hub.py +148 -0
  79. resource_engine/messaging/inbound.py +76 -0
  80. resource_engine/messaging/inspection.py +113 -0
  81. resource_engine/messaging/janitor.py +136 -0
  82. resource_engine/messaging/live.py +179 -0
  83. resource_engine/messaging/processing.py +357 -0
  84. resource_engine/messaging/publishing.py +318 -0
  85. resource_engine/messaging/relay.py +84 -0
  86. resource_engine/messaging/worker.py +166 -0
  87. resource_engine/nosql.py +394 -0
  88. resource_engine/ports/__init__.py +13 -0
  89. resource_engine/ports/activity.py +171 -0
  90. resource_engine/ports/audit.py +42 -0
  91. resource_engine/ports/authz.py +132 -0
  92. resource_engine/ports/cache.py +41 -0
  93. resource_engine/ports/email.py +118 -0
  94. resource_engine/ports/event_publisher.py +34 -0
  95. resource_engine/ports/idempotency.py +69 -0
  96. resource_engine/ports/identity.py +112 -0
  97. resource_engine/ports/locks.py +28 -0
  98. resource_engine/ports/messaging.py +197 -0
  99. resource_engine/ports/observability.py +60 -0
  100. resource_engine/ports/ratelimit.py +59 -0
  101. resource_engine/ports/repository.py +56 -0
  102. resource_engine/ports/storage.py +93 -0
  103. resource_engine/ports/templates.py +54 -0
  104. resource_engine/ports/tracing.py +61 -0
  105. resource_engine/ports/unit_of_work.py +46 -0
  106. resource_engine/processes.py +408 -0
  107. resource_engine/py.typed +0 -0
  108. resource_engine/querying.py +319 -0
  109. resource_engine/ratelimit.py +217 -0
  110. resource_engine/reporting.py +230 -0
  111. resource_engine/schema_examples.py +51 -0
  112. resource_engine/templates.py +143 -0
  113. resource_engine/tenancy.py +68 -0
  114. resource_engine/testing/__init__.py +34 -0
  115. resource_engine/testing/activity.py +123 -0
  116. resource_engine/testing/contracts.py +1416 -0
  117. resource_engine/testing/email.py +36 -0
  118. resource_engine/testing/engine.py +40 -0
  119. resource_engine/testing/memory.py +603 -0
  120. resource_engine/testing/storage.py +110 -0
  121. resource_engine/testing/tracing.py +100 -0
  122. resource_engine/tracing.py +156 -0
  123. resource_engine/translatable.py +80 -0
  124. resource_engine/versions.py +189 -0
  125. resource_engine-0.1.0.dist-info/METADATA +36 -0
  126. resource_engine-0.1.0.dist-info/RECORD +128 -0
  127. resource_engine-0.1.0.dist-info/WHEEL +4 -0
  128. resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,77 @@
1
+ """Code-side configuration: system roles and where roles come from."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from dataclasses import dataclass, field
7
+ from typing import TYPE_CHECKING
8
+
9
+ from resource_engine.errors import ConfigurationError
10
+
11
+ if TYPE_CHECKING:
12
+ from resource_engine.authz.roles import RoleSource
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class SystemRole:
17
+ """A role defined in code: visible and assignable from the front end, never
18
+ editable there, and not restrictable by front-end deny policies.
19
+
20
+ Args:
21
+ name: Role name.
22
+ grants: Action patterns (``*``, ``*:list``, ``invoices:*``...).
23
+ description: Shown to administrators.
24
+ include_sensitive: Wildcards also match resources with
25
+ ``Access(wildcards=False)`` (only for full administrators).
26
+ cross_tenant: Holders act across tenants on tenant-scoped resources.
27
+ """
28
+
29
+ name: str
30
+ grants: Sequence[str]
31
+ description: str | None = None
32
+ include_sensitive: bool = False
33
+ cross_tenant: bool = False
34
+
35
+ @classmethod
36
+ def admin(cls, name: str = "admin") -> SystemRole:
37
+ """A role granted every action."""
38
+ return cls(
39
+ name,
40
+ ["*"],
41
+ "Full access, including permission management, across tenants",
42
+ include_sensitive=True,
43
+ cross_tenant=True,
44
+ )
45
+
46
+ @classmethod
47
+ def viewer(cls, name: str = "viewer") -> SystemRole:
48
+ """A role that reads and downloads everything."""
49
+ return cls(name, ["*:list", "*:get", "*:download:*"], "Read-only access")
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class AuthzConfig:
54
+ """Args:
55
+ system_roles: Roles defined in code.
56
+ role_source: Where principals' roles come from (deployment choice):
57
+ ``IdpRoleSource``, ``StoredRoleSource`` or ``CombinedRoleSource``.
58
+ bootstrap: Identity-provider roles that always grant a role (e.g.
59
+ ``{"platform-admin": "admin"}``), so administrators cannot lock
60
+ themselves out.
61
+ """
62
+
63
+ system_roles: Sequence[SystemRole] = (SystemRole.admin(), SystemRole.viewer())
64
+ role_source: RoleSource | None = None
65
+ bootstrap: Mapping[str, str] = field(default_factory=dict)
66
+
67
+ def __post_init__(self) -> None:
68
+ names = [r.name for r in self.system_roles]
69
+ if len(names) != len(set(names)):
70
+ raise ConfigurationError(f"Duplicate system role names: {names}")
71
+ for target in self.bootstrap.values():
72
+ if target not in names:
73
+ raise ConfigurationError(f"bootstrap grants unknown system role {target!r}")
74
+
75
+ def system_role(self, name: str) -> SystemRole | None:
76
+ """The system role called ``name``, if any."""
77
+ return next((r for r in self.system_roles if r.name == name), None)
@@ -0,0 +1,382 @@
1
+ """``PolicyAuthorizer``: evaluates system roles and stored ABAC policies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from collections.abc import Callable, Iterable
8
+ from datetime import UTC, datetime
9
+ from typing import TYPE_CHECKING, Any, override
10
+
11
+ from resource_engine.application.query import ListQuery
12
+ from resource_engine.authz.base import ( # re-exported: older imports name this module
13
+ RoleBasedAuthorizer as RoleBasedAuthorizer,
14
+ )
15
+ from resource_engine.authz.base import SystemPrincipal as SystemPrincipal
16
+ from resource_engine.authz.base import subject_view as subject_view
17
+ from resource_engine.authz.base import system_principal as system_principal
18
+ from resource_engine.authz.catalog import FIELD_KINDS, ActionInfo, action_matches
19
+ from resource_engine.authz.conditions import (
20
+ UNKNOWN,
21
+ Env,
22
+ conjunction,
23
+ disjunction,
24
+ evaluate,
25
+ negation,
26
+ partial,
27
+ )
28
+ from resource_engine.authz.config import AuthzConfig
29
+ from resource_engine.ports.authz import Decision, FieldAccess, FieldRules
30
+ from resource_engine.ports.identity import Principal
31
+
32
+ if TYPE_CHECKING:
33
+ from resource_engine.authz.model import Policy
34
+ from resource_engine.messaging.consumer import EventRouter
35
+
36
+ log = logging.getLogger("resource_engine.authz")
37
+
38
+
39
+ class PolicyStore:
40
+ """Snapshot of enabled policies, reloaded after changes or every ``ttl`` seconds."""
41
+
42
+ def __init__(
43
+ self, uow_factory: Callable[[], Any], *, resource: str = "authz_policies", ttl: float = 60
44
+ ) -> None:
45
+ self.uow_factory = uow_factory
46
+ self.resource = resource
47
+ self.ttl = ttl
48
+ self._policies: list[Policy] | None = None
49
+ self._loaded = 0.0
50
+
51
+ def invalidate(self) -> None:
52
+ """Reload the policies on next use."""
53
+ self._policies = None
54
+
55
+ async def policies(self) -> list[Policy]:
56
+ """The enabled policies, reloaded when stale."""
57
+ if self._policies is None or time.monotonic() - self._loaded > self.ttl:
58
+ async with self.uow_factory() as uow:
59
+ page = await uow.repository(self.resource).list(ListQuery(limit=100_000))
60
+ # plain copies: ORMs expire instances when the unit of work closes
61
+ self._policies = [_copy(p) for p in page.items if p.enabled]
62
+ self._loaded = time.monotonic()
63
+ return self._policies
64
+
65
+
66
+ def _copy(policy: Any) -> Any:
67
+ import dataclasses
68
+
69
+ return dataclasses.replace(policy)
70
+
71
+
72
+ class PolicyAuthorizer(RoleBasedAuthorizer):
73
+ """``Authorizer`` over system roles (code) and policies (data).
74
+
75
+ Rules: deny by default; a matching system-role grant allows and cannot be
76
+ denied; otherwise any applicable deny policy whose condition holds denies, and
77
+ an applicable allow policy whose condition holds allows.
78
+
79
+ Args:
80
+ config: System roles, role source and bootstrap roles.
81
+ uow_factory: To read policies (and stored role assignments).
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ config: AuthzConfig,
87
+ uow_factory: Callable[[], Any],
88
+ *,
89
+ policies_resource: str = "authz_policies",
90
+ ) -> None:
91
+ super().__init__(config)
92
+ self.store = PolicyStore(uow_factory, resource=policies_resource)
93
+ self._restricted_cache: tuple[int, frozenset[str]] | None = None
94
+
95
+ def invalidate(self) -> None:
96
+ """Reload policies and role assignments on next use."""
97
+ self.store.invalidate()
98
+ invalidate = getattr(self.role_source, "invalidate", None)
99
+ if invalidate:
100
+ invalidate()
101
+
102
+ def register(self, router: EventRouter) -> EventRouter:
103
+ """Refresh caches when another instance changes policies or assignments."""
104
+ router.register("PolicyChanged", lambda envelope: self.invalidate())
105
+ return router
106
+
107
+ # ------------------------------------------------------------------ roles
108
+
109
+ @staticmethod
110
+ def _applies(policy: Policy, principal: Principal, roles: frozenset[str]) -> bool:
111
+ s = policy.subjects or {}
112
+ return bool(
113
+ s.get("everyone")
114
+ or roles & set(s.get("roles") or ())
115
+ or principal.groups & set(s.get("groups") or ())
116
+ or principal.id in (s.get("users") or ())
117
+ )
118
+
119
+ async def _applicable(
120
+ self, principal: Principal, roles: frozenset[str], action: str
121
+ ) -> list[Policy]:
122
+ wild, exact = self._wildcards(action), self._exact(action)
123
+ return [
124
+ p
125
+ for p in await self.store.policies()
126
+ if self._applies(p, principal, roles)
127
+ and any(action_matches(a, action, wildcards=wild, exact=exact) for a in p.actions)
128
+ ]
129
+
130
+ # ----------------------------------------------------------------- checks
131
+
132
+ @override
133
+ async def check(
134
+ self,
135
+ principal: Principal | None,
136
+ action: str,
137
+ *,
138
+ resource: Any = ...,
139
+ input: Any = ...,
140
+ context: dict[str, Any] | None = None,
141
+ ) -> Decision:
142
+ if isinstance(principal, SystemPrincipal):
143
+ return Decision(True, "system principal")
144
+ if not isinstance(principal, Principal):
145
+ return Decision(False, "not authenticated")
146
+ info = self.catalog.actions.get(action) if self.catalog else None
147
+ if info is not None and info.kind in FIELD_KINDS:
148
+ return await self._check_field(principal, info, resource=resource, input=input)
149
+ roles = await self.roles_of(principal)
150
+ system = self._system_grant(roles, action)
151
+ if system:
152
+ return Decision(True, f"system role {system}", system_role=system)
153
+ namespaces: dict[str, Any] = {
154
+ "subject": subject_view(principal, roles),
155
+ "context": {"action": action, "now": datetime.now(UTC), **(context or {})},
156
+ }
157
+ if resource is not ...:
158
+ namespaces["resource"] = resource
159
+ if input is not ...:
160
+ namespaces["input"] = _plain(input)
161
+ env = Env(**namespaces)
162
+ policies = await self._applicable(principal, roles, action)
163
+ allowed, reason, ids = _decide(policies, env, open_=False)
164
+ return Decision(allowed, reason, ids)
165
+
166
+ async def _check_field(
167
+ self, principal: Principal, info: ActionInfo, *, resource: Any, input: Any
168
+ ) -> Decision:
169
+ roles = await self.roles_of(principal)
170
+ policies = await self.store.policies()
171
+ entry = self._field_entry(principal, roles, info, policies, self._restricted(policies))
172
+ if entry is None:
173
+ return Decision(True, "field allowed")
174
+ rules = PolicyFieldRules(
175
+ {info.qualifier or info.name: entry}, subject_view(principal, roles)
176
+ )
177
+ _, ok_policies, restricted = entry
178
+ env = rules.env(info, resource=resource, input=input)
179
+ allowed, reason, ids = _decide(ok_policies, env, open_=not restricted)
180
+ return Decision(allowed, reason, ids)
181
+
182
+ @override
183
+ async def scope(self, principal: Principal | None, action: str) -> Any:
184
+ if isinstance(principal, SystemPrincipal):
185
+ return True
186
+ if not isinstance(principal, Principal):
187
+ return False
188
+ roles = await self.roles_of(principal)
189
+ if self._system_grant(roles, action):
190
+ return True
191
+ env = Env(
192
+ subject=subject_view(principal, roles),
193
+ context={"action": action, "now": datetime.now(UTC)},
194
+ input={},
195
+ )
196
+ policies = await self._applicable(principal, roles, action)
197
+ allows = [partial(p.condition, env) for p in policies if p.effect == "allow"]
198
+ denies = [partial(p.condition, env) for p in policies if p.effect == "deny"]
199
+ return conjunction(disjunction(*allows), negation(disjunction(*denies)))
200
+
201
+ # ----------------------------------------------------------------- fields
202
+
203
+ def _restricted(self, policies: list[Policy]) -> frozenset[str]:
204
+ """Field actions named explicitly by an enabled allow policy."""
205
+ if self._restricted_cache and self._restricted_cache[0] == id(policies):
206
+ return self._restricted_cache[1]
207
+ assert self.catalog is not None
208
+ fields = [a for a in self.catalog.actions.values() if a.kind in FIELD_KINDS]
209
+ found: set[str] = set()
210
+ for policy in policies:
211
+ if policy.effect != "allow":
212
+ continue
213
+ for pattern in policy.actions:
214
+ if not names_field(pattern):
215
+ continue
216
+ found.update(
217
+ a.name for a in fields if action_matches(pattern, a.name, wildcards=a.wildcards)
218
+ )
219
+ result = frozenset(found)
220
+ self._restricted_cache = (id(policies), result)
221
+ return result
222
+
223
+ async def field_rules(
224
+ self, principal: Principal | None, resource: str, mode: str
225
+ ) -> PolicyFieldRules:
226
+ """Field decisions of ``principal`` on ``resource`` for ``mode`` (``read`` or
227
+ ``write``), prepared once and evaluated per record with ``decide``.
228
+
229
+ A field is open unless it is *restricted* (``restricted_fields`` in code,
230
+ or named explicitly by an allow policy): open fields are allowed unless a
231
+ deny applies, restricted ones need a system-role grant or an allow.
232
+ """
233
+ assert self.catalog is not None, "bind() the authorizer to a registry first"
234
+ if isinstance(principal, SystemPrincipal):
235
+ return PolicyFieldRules({}, {})
236
+ actions = self.catalog.field_actions(resource, mode)
237
+ policies = await self.store.policies()
238
+ restricted = self._restricted(policies)
239
+ person = principal if isinstance(principal, Principal) else None
240
+ roles = await self.roles_of(person) if person is not None else frozenset()
241
+ rules: dict[str, tuple[ActionInfo, list[Policy], bool]] = {}
242
+ for name, info in actions.items():
243
+ entry = self._field_entry(principal, roles, info, policies, restricted)
244
+ if entry is not None:
245
+ rules[name] = entry
246
+ subject = subject_view(person, roles) if person is not None else {}
247
+ return PolicyFieldRules(rules, subject)
248
+
249
+ def _field_entry(
250
+ self,
251
+ principal: Principal | None,
252
+ roles: frozenset[str],
253
+ info: ActionInfo,
254
+ policies: list[Policy],
255
+ restricted: frozenset[str],
256
+ ) -> tuple[ActionInfo, list[Policy], bool] | None:
257
+ """Policies that decide one field action, or ``None`` when it is allowed
258
+ outright (system role) or open with no policy about it.
259
+
260
+ Restricted fields are only granted by patterns that name them explicitly:
261
+ broad grants (``invoices:*``) do not reach them, like sensitive resources.
262
+ """
263
+ is_restricted = info.restricted or info.name in restricted
264
+ known = isinstance(principal, Principal)
265
+ if known:
266
+ for role_name in sorted(roles):
267
+ role = self.config.system_role(role_name)
268
+ if role and any(
269
+ action_matches(
270
+ g,
271
+ info.name,
272
+ wildcards=info.wildcards or role.include_sensitive,
273
+ exact=info.exact,
274
+ )
275
+ and (not is_restricted or role.include_sensitive or names_field(g))
276
+ for g in role.grants
277
+ ):
278
+ return None
279
+ applicable: list[Policy] = []
280
+ if isinstance(principal, Principal):
281
+ for p in policies:
282
+ if not self._applies(p, principal, roles):
283
+ continue
284
+ hits = [
285
+ a
286
+ for a in p.actions
287
+ if action_matches(a, info.name, wildcards=info.wildcards, exact=info.exact)
288
+ ]
289
+ if p.effect == "allow" and is_restricted:
290
+ hits = [a for a in hits if names_field(a)]
291
+ if hits:
292
+ applicable.append(p)
293
+ if applicable or is_restricted:
294
+ return info, applicable, is_restricted
295
+ return None
296
+
297
+
298
+ class PolicyFieldRules(FieldRules):
299
+ """Prepared field decisions (see ``PolicyAuthorizer.field_rules``)."""
300
+
301
+ def __init__(
302
+ self,
303
+ rules: dict[str, tuple[ActionInfo, list[Policy], bool]],
304
+ subject: dict[str, Any],
305
+ ) -> None:
306
+ self.rules = rules
307
+ self.subject = subject
308
+
309
+ @property
310
+ def empty(self) -> bool:
311
+ """No field can be blocked: callers can skip per-record evaluation."""
312
+ return not self.rules
313
+
314
+ def env(self, info: ActionInfo, *, resource: Any = ..., input: Any = ...) -> Env:
315
+ """The attributes a field rule of ``info`` is evaluated against."""
316
+ namespaces: dict[str, Any] = {
317
+ "subject": self.subject,
318
+ "context": {"action": info.name, "now": datetime.now(UTC)},
319
+ }
320
+ if resource is not ...:
321
+ namespaces["resource"] = resource
322
+ if input is not ...:
323
+ namespaces["input"] = _plain(input)
324
+ return Env(**namespaces)
325
+
326
+ @override
327
+ def decide(self, *, resource: Any = ..., input: Any = ...) -> FieldAccess:
328
+ if not self.rules:
329
+ return FieldAccess()
330
+ denied: set[str] = set()
331
+ conditional: set[str] = set()
332
+ for name, (info, policies, restricted) in self.rules.items():
333
+ env = self.env(info, resource=resource, input=input)
334
+ allowed, _, _ = _decide(policies, env, open_=not restricted)
335
+ if allowed is False:
336
+ denied.add(name)
337
+ elif allowed is None:
338
+ conditional.add(name)
339
+ return FieldAccess(frozenset(denied), frozenset(conditional))
340
+
341
+
342
+ def names_field(pattern: str) -> bool:
343
+ """Whether ``pattern`` names a field explicitly (``res:read:salary``,
344
+ ``res:*:salary``), as restricted fields require."""
345
+ parts = pattern.split(":")
346
+ return len(parts) == 3 and parts[2] != "*" and parts[1] in (*FIELD_KINDS, "*")
347
+
348
+
349
+ def _decide(
350
+ policies: Iterable[Policy], env: Env, *, open_: bool
351
+ ) -> tuple[bool | None, str, tuple[str, ...]]:
352
+ """Deny overrides allow. ``open_``: allowed when no deny applies (open fields);
353
+ otherwise an allow is needed (actions, restricted fields)."""
354
+ policies = list(policies)
355
+ pending_deny: list[str] = []
356
+ for p in (p for p in policies if p.effect == "deny"):
357
+ result = evaluate(p.condition, env)
358
+ if result is True:
359
+ return False, f"denied by policy {p.name!r}", (p.id,)
360
+ if result is UNKNOWN:
361
+ pending_deny.append(p.id)
362
+ if open_:
363
+ if pending_deny:
364
+ return None, "depends on the record", tuple(pending_deny)
365
+ return True, "open field", ()
366
+ unknown_allow: list[str] = []
367
+ for p in (p for p in policies if p.effect == "allow"):
368
+ result = evaluate(p.condition, env)
369
+ if result is True:
370
+ if pending_deny:
371
+ return None, "depends on the record", (p.id, *pending_deny)
372
+ return True, f"allowed by policy {p.name!r}", (p.id,)
373
+ if result is UNKNOWN:
374
+ unknown_allow.append(p.id)
375
+ if unknown_allow:
376
+ return None, "depends on the record", tuple(unknown_allow)
377
+ return False, "no policy allows it", ()
378
+
379
+
380
+ def _plain(value: Any) -> Any:
381
+ dump = getattr(value, "model_dump", None)
382
+ return dump() if callable(dump) else value