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.
- resource_engine/__init__.py +96 -0
- resource_engine/application/__init__.py +1 -0
- resource_engine/application/actions.py +48 -0
- resource_engine/application/context.py +111 -0
- resource_engine/application/events.py +54 -0
- resource_engine/application/hooks.py +272 -0
- resource_engine/application/idempotency.py +277 -0
- resource_engine/application/manager.py +1987 -0
- resource_engine/application/query.py +47 -0
- resource_engine/application/registry.py +137 -0
- resource_engine/application/relations.py +470 -0
- resource_engine/application/resource.py +984 -0
- resource_engine/application/searching.py +162 -0
- resource_engine/application/settings.py +169 -0
- resource_engine/application/slots.py +67 -0
- resource_engine/application/state_machines.py +177 -0
- resource_engine/application/timers.py +347 -0
- resource_engine/application/transaction.py +100 -0
- resource_engine/application/views.py +239 -0
- resource_engine/audit/__init__.py +40 -0
- resource_engine/audit/export.py +280 -0
- resource_engine/audit/history.py +165 -0
- resource_engine/audit/janitor.py +257 -0
- resource_engine/audit/model.py +98 -0
- resource_engine/audit/recorder.py +145 -0
- resource_engine/audit/resource.py +68 -0
- resource_engine/audit/seal.py +327 -0
- resource_engine/audit/sink.py +69 -0
- resource_engine/authz/__init__.py +72 -0
- resource_engine/authz/apikeys.py +300 -0
- resource_engine/authz/base.py +143 -0
- resource_engine/authz/catalog.py +291 -0
- resource_engine/authz/conditions.py +416 -0
- resource_engine/authz/config.py +77 -0
- resource_engine/authz/evaluator.py +382 -0
- resource_engine/authz/external.py +249 -0
- resource_engine/authz/fields.py +44 -0
- resource_engine/authz/model.py +145 -0
- resource_engine/authz/resources.py +289 -0
- resource_engine/authz/roles.py +101 -0
- resource_engine/cache.py +144 -0
- resource_engine/calls.py +100 -0
- resource_engine/capabilities.py +145 -0
- resource_engine/composite.py +295 -0
- resource_engine/documents/__init__.py +69 -0
- resource_engine/documents/content.py +57 -0
- resource_engine/documents/events.py +49 -0
- resource_engine/documents/janitor.py +93 -0
- resource_engine/documents/machine.py +38 -0
- resource_engine/documents/manager.py +704 -0
- resource_engine/documents/model.py +91 -0
- resource_engine/documents/pipeline.py +98 -0
- resource_engine/documents/processors.py +320 -0
- resource_engine/documents/resource.py +39 -0
- resource_engine/domain/__init__.py +10 -0
- resource_engine/domain/events.py +50 -0
- resource_engine/domain/exceptions.py +23 -0
- resource_engine/email.py +417 -0
- resource_engine/errors.py +562 -0
- resource_engine/explorer.py +133 -0
- resource_engine/exports.py +687 -0
- resource_engine/generation.py +233 -0
- resource_engine/i18n.py +251 -0
- resource_engine/identity.py +46 -0
- resource_engine/integration.py +80 -0
- resource_engine/jobs.py +390 -0
- resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
- resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
- resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
- resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
- resource_engine/logs.py +201 -0
- resource_engine/messaging/__init__.py +73 -0
- resource_engine/messaging/asyncapi.py +529 -0
- resource_engine/messaging/cloudevents.py +98 -0
- resource_engine/messaging/consumer.py +165 -0
- resource_engine/messaging/delivery.py +115 -0
- resource_engine/messaging/envelope.py +193 -0
- resource_engine/messaging/hub.py +148 -0
- resource_engine/messaging/inbound.py +76 -0
- resource_engine/messaging/inspection.py +113 -0
- resource_engine/messaging/janitor.py +136 -0
- resource_engine/messaging/live.py +179 -0
- resource_engine/messaging/processing.py +357 -0
- resource_engine/messaging/publishing.py +318 -0
- resource_engine/messaging/relay.py +84 -0
- resource_engine/messaging/worker.py +166 -0
- resource_engine/nosql.py +394 -0
- resource_engine/ports/__init__.py +13 -0
- resource_engine/ports/activity.py +171 -0
- resource_engine/ports/audit.py +42 -0
- resource_engine/ports/authz.py +132 -0
- resource_engine/ports/cache.py +41 -0
- resource_engine/ports/email.py +118 -0
- resource_engine/ports/event_publisher.py +34 -0
- resource_engine/ports/idempotency.py +69 -0
- resource_engine/ports/identity.py +112 -0
- resource_engine/ports/locks.py +28 -0
- resource_engine/ports/messaging.py +197 -0
- resource_engine/ports/observability.py +60 -0
- resource_engine/ports/ratelimit.py +59 -0
- resource_engine/ports/repository.py +56 -0
- resource_engine/ports/storage.py +93 -0
- resource_engine/ports/templates.py +54 -0
- resource_engine/ports/tracing.py +61 -0
- resource_engine/ports/unit_of_work.py +46 -0
- resource_engine/processes.py +408 -0
- resource_engine/py.typed +0 -0
- resource_engine/querying.py +319 -0
- resource_engine/ratelimit.py +217 -0
- resource_engine/reporting.py +230 -0
- resource_engine/schema_examples.py +51 -0
- resource_engine/templates.py +143 -0
- resource_engine/tenancy.py +68 -0
- resource_engine/testing/__init__.py +34 -0
- resource_engine/testing/activity.py +123 -0
- resource_engine/testing/contracts.py +1416 -0
- resource_engine/testing/email.py +36 -0
- resource_engine/testing/engine.py +40 -0
- resource_engine/testing/memory.py +603 -0
- resource_engine/testing/storage.py +110 -0
- resource_engine/testing/tracing.py +100 -0
- resource_engine/tracing.py +156 -0
- resource_engine/translatable.py +80 -0
- resource_engine/versions.py +189 -0
- resource_engine-0.1.0.dist-info/METADATA +36 -0
- resource_engine-0.1.0.dist-info/RECORD +128 -0
- resource_engine-0.1.0.dist-info/WHEEL +4 -0
- resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""What policies can talk about: actions and attributes, derived from the registry.
|
|
2
|
+
|
|
3
|
+
Published to front ends (``GET /authz/catalog``) to build policy editors.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import enum
|
|
9
|
+
import types
|
|
10
|
+
import typing
|
|
11
|
+
from collections.abc import Iterable, Mapping
|
|
12
|
+
from dataclasses import asdict, dataclass, field
|
|
13
|
+
from datetime import date, datetime
|
|
14
|
+
from decimal import Decimal
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from pydantic import BaseModel
|
|
18
|
+
|
|
19
|
+
from resource_engine.authz.conditions import OPERATORS
|
|
20
|
+
|
|
21
|
+
if typing.TYPE_CHECKING:
|
|
22
|
+
from resource_engine.application.registry import ResourceRegistry
|
|
23
|
+
from resource_engine.application.resource import ResourceDefinition
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class AttributeInfo:
|
|
28
|
+
"""An attribute policies can test: its path (``resource.amount``), type and allowed values."""
|
|
29
|
+
|
|
30
|
+
path: str
|
|
31
|
+
type: str
|
|
32
|
+
enum: list[Any] | None = None
|
|
33
|
+
description: str | None = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class ActionInfo:
|
|
38
|
+
"""An action policies can grant, with the input attributes it takes."""
|
|
39
|
+
|
|
40
|
+
name: str
|
|
41
|
+
resource: str
|
|
42
|
+
kind: str # crud, transition, action, attach, detach, download, read, write
|
|
43
|
+
qualifier: str | None = None
|
|
44
|
+
description: str | None = None
|
|
45
|
+
wildcards: bool = True # False: only explicit grants match (sensitive resources)
|
|
46
|
+
input: list[AttributeInfo] = field(default_factory=list)
|
|
47
|
+
restricted: bool = False # field actions: restricted in code (needs a grant)
|
|
48
|
+
#: Only a grant naming this action exactly matches: no wildcard, not even
|
|
49
|
+
#: for roles that include sensitive actions (publishing events by hand).
|
|
50
|
+
exact: bool = False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
FIELD_KINDS = ("read", "write")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
SUBJECT_ATTRIBUTES = [
|
|
57
|
+
AttributeInfo("subject.id", "string", description="provider:subject"),
|
|
58
|
+
AttributeInfo("subject.subject", "string"),
|
|
59
|
+
AttributeInfo("subject.provider", "string"),
|
|
60
|
+
AttributeInfo("subject.roles", "list", description="Application roles"),
|
|
61
|
+
AttributeInfo("subject.groups", "list"),
|
|
62
|
+
AttributeInfo("subject.scopes", "list"),
|
|
63
|
+
AttributeInfo("subject.tenant", "string"),
|
|
64
|
+
AttributeInfo("subject.client_id", "string"),
|
|
65
|
+
AttributeInfo("subject.service", "boolean"),
|
|
66
|
+
AttributeInfo("subject.email", "string"),
|
|
67
|
+
]
|
|
68
|
+
CONTEXT_ATTRIBUTES = [
|
|
69
|
+
AttributeInfo("context.operation", "string"),
|
|
70
|
+
AttributeInfo("context.action", "string"),
|
|
71
|
+
AttributeInfo("context.now", "datetime"),
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _type_of(annotation: Any) -> tuple[str, list[Any] | None]:
|
|
76
|
+
origin = typing.get_origin(annotation)
|
|
77
|
+
if origin is typing.Annotated:
|
|
78
|
+
return _type_of(typing.get_args(annotation)[0])
|
|
79
|
+
if origin in (typing.Union, types.UnionType):
|
|
80
|
+
args = [a for a in typing.get_args(annotation) if a is not type(None)]
|
|
81
|
+
return _type_of(args[0]) if len(args) == 1 else ("any", None)
|
|
82
|
+
if origin is typing.Literal:
|
|
83
|
+
return "string", list(typing.get_args(annotation))
|
|
84
|
+
if origin in (list, set, frozenset, tuple):
|
|
85
|
+
return "list", None
|
|
86
|
+
if origin in (dict, Mapping):
|
|
87
|
+
return "object", None
|
|
88
|
+
if isinstance(annotation, type):
|
|
89
|
+
if issubclass(annotation, bool):
|
|
90
|
+
return "boolean", None
|
|
91
|
+
if issubclass(annotation, enum.Enum):
|
|
92
|
+
return "string", [m.value for m in annotation]
|
|
93
|
+
if issubclass(annotation, int | float | Decimal):
|
|
94
|
+
return "number", None
|
|
95
|
+
if issubclass(annotation, datetime):
|
|
96
|
+
return "datetime", None
|
|
97
|
+
if issubclass(annotation, date):
|
|
98
|
+
return "date", None
|
|
99
|
+
if issubclass(annotation, str):
|
|
100
|
+
return "string", None
|
|
101
|
+
if issubclass(annotation, BaseModel | dict):
|
|
102
|
+
return "object", None
|
|
103
|
+
return "any", None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def schema_attributes(prefix: str, schema: type[BaseModel] | None) -> list[AttributeInfo]:
|
|
107
|
+
"""The attributes of a Pydantic schema, under ``prefix``."""
|
|
108
|
+
if schema is None:
|
|
109
|
+
return []
|
|
110
|
+
out = []
|
|
111
|
+
for name, f in schema.model_fields.items():
|
|
112
|
+
kind, values = _type_of(f.annotation)
|
|
113
|
+
out.append(AttributeInfo(f"{prefix}.{name}", kind, values, f.description))
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class Catalog:
|
|
119
|
+
"""Every action and attribute of an application, for policy editors and validation."""
|
|
120
|
+
|
|
121
|
+
actions: dict[str, ActionInfo]
|
|
122
|
+
resource_attributes: dict[str, list[AttributeInfo]]
|
|
123
|
+
|
|
124
|
+
@classmethod
|
|
125
|
+
def from_registry(cls, registry: ResourceRegistry) -> Catalog:
|
|
126
|
+
"""The catalogue of a registry's resources and engine actions."""
|
|
127
|
+
actions: dict[str, ActionInfo] = {}
|
|
128
|
+
attributes: dict[str, list[AttributeInfo]] = {}
|
|
129
|
+
for d in registry:
|
|
130
|
+
attributes[d.name] = cls._resource_attributes(d)
|
|
131
|
+
for action in cls._actions(d):
|
|
132
|
+
actions[action.name] = action
|
|
133
|
+
for action in registry.engine_actions():
|
|
134
|
+
attributes.setdefault(action.resource, [])
|
|
135
|
+
actions[action.name] = action
|
|
136
|
+
return cls(actions, attributes)
|
|
137
|
+
|
|
138
|
+
@staticmethod
|
|
139
|
+
def _resource_attributes(d: ResourceDefinition) -> list[AttributeInfo]:
|
|
140
|
+
attrs = schema_attributes("resource", d.schemas.get("read"))
|
|
141
|
+
for machine in d.machines.values():
|
|
142
|
+
path = f"resource.{machine.state_field}"
|
|
143
|
+
states = [s.id for s in machine.info.states]
|
|
144
|
+
label = "State" if len(d.machines) == 1 else f"State ({machine.name})"
|
|
145
|
+
attrs = [a for a in attrs if a.path != path]
|
|
146
|
+
attrs.append(AttributeInfo(path, "string", states, label))
|
|
147
|
+
return attrs
|
|
148
|
+
|
|
149
|
+
@staticmethod
|
|
150
|
+
def _actions(d: ResourceDefinition) -> Iterable[ActionInfo]:
|
|
151
|
+
wild = d.authz_wildcards
|
|
152
|
+
for op in d.operations:
|
|
153
|
+
schema = d.schemas.get(op) if op in ("create", "update") else None
|
|
154
|
+
yield ActionInfo(
|
|
155
|
+
f"{d.name}:{op}",
|
|
156
|
+
d.name,
|
|
157
|
+
"crud",
|
|
158
|
+
description=d.operation_docs.get(op),
|
|
159
|
+
wildcards=wild,
|
|
160
|
+
input=schema_attributes("input", schema),
|
|
161
|
+
)
|
|
162
|
+
if d.machine is not None:
|
|
163
|
+
for event in d.transitions:
|
|
164
|
+
yield ActionInfo(
|
|
165
|
+
f"{d.name}:transition:{event}",
|
|
166
|
+
d.name,
|
|
167
|
+
"transition",
|
|
168
|
+
event,
|
|
169
|
+
wildcards=wild,
|
|
170
|
+
input=schema_attributes("input", d.transition_schemas.get(event)),
|
|
171
|
+
)
|
|
172
|
+
for a in d.actions.values():
|
|
173
|
+
yield ActionInfo(
|
|
174
|
+
f"{d.name}:action:{a.name}",
|
|
175
|
+
d.name,
|
|
176
|
+
"action",
|
|
177
|
+
a.name,
|
|
178
|
+
description=(a.description or "").split("\n", 1)[0] or None,
|
|
179
|
+
wildcards=wild,
|
|
180
|
+
input=schema_attributes("input", a.input_schema),
|
|
181
|
+
)
|
|
182
|
+
for slot in d.document_slots.values():
|
|
183
|
+
for kind in ("attach", "detach", "download"):
|
|
184
|
+
yield ActionInfo(
|
|
185
|
+
f"{d.name}:{kind}:{slot.name}",
|
|
186
|
+
d.name,
|
|
187
|
+
kind,
|
|
188
|
+
slot.name,
|
|
189
|
+
description=slot.description,
|
|
190
|
+
wildcards=wild,
|
|
191
|
+
)
|
|
192
|
+
restricted = set(d.restricted_fields)
|
|
193
|
+
for kind, names in (("read", _read_fields(d)), ("write", _write_fields(d))):
|
|
194
|
+
for name, description in names.items():
|
|
195
|
+
yield ActionInfo(
|
|
196
|
+
f"{d.name}:{kind}:{name}",
|
|
197
|
+
d.name,
|
|
198
|
+
kind,
|
|
199
|
+
name,
|
|
200
|
+
description=description,
|
|
201
|
+
wildcards=wild,
|
|
202
|
+
restricted=name in restricted,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
# ------------------------------------------------------------- queries
|
|
206
|
+
|
|
207
|
+
def field_actions(self, resource: str, kind: str) -> dict[str, ActionInfo]:
|
|
208
|
+
"""Field actions of ``resource`` (``kind`` ``read`` or ``write``), by field."""
|
|
209
|
+
return {
|
|
210
|
+
a.qualifier: a
|
|
211
|
+
for a in self.actions.values()
|
|
212
|
+
if a.resource == resource and a.kind == kind and a.qualifier
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
def matching(self, pattern: str, *, include_sensitive: bool = False) -> list[str]:
|
|
216
|
+
"""The actions ``pattern`` grants (wildcards allowed); sensitive ones only when
|
|
217
|
+
``include_sensitive``."""
|
|
218
|
+
return [
|
|
219
|
+
name
|
|
220
|
+
for name, info in self.actions.items()
|
|
221
|
+
if action_matches(
|
|
222
|
+
pattern, name, wildcards=info.wildcards or include_sensitive, exact=info.exact
|
|
223
|
+
)
|
|
224
|
+
]
|
|
225
|
+
|
|
226
|
+
def attribute_types(self, actions: Iterable[str]) -> dict[str, str]:
|
|
227
|
+
"""Attributes a condition may use for all of ``actions`` (intersection of
|
|
228
|
+
resource and input attributes; subject and context always)."""
|
|
229
|
+
common: dict[str, str] | None = None
|
|
230
|
+
for name in actions:
|
|
231
|
+
info = self.actions[name]
|
|
232
|
+
attrs = {
|
|
233
|
+
a.path: a.type for a in [*self.resource_attributes[info.resource], *info.input]
|
|
234
|
+
}
|
|
235
|
+
common = attrs if common is None else {k: v for k, v in common.items() if k in attrs}
|
|
236
|
+
out = {a.path: a.type for a in [*SUBJECT_ATTRIBUTES, *CONTEXT_ATTRIBUTES]}
|
|
237
|
+
out.update(common or {})
|
|
238
|
+
return out
|
|
239
|
+
|
|
240
|
+
def to_dict(self) -> dict[str, Any]:
|
|
241
|
+
"""The catalogue as JSON-ready data (``/authz/catalog``)."""
|
|
242
|
+
return {
|
|
243
|
+
"operators": list(OPERATORS),
|
|
244
|
+
"subject": [asdict(a) for a in SUBJECT_ATTRIBUTES],
|
|
245
|
+
"context": [asdict(a) for a in CONTEXT_ATTRIBUTES],
|
|
246
|
+
"resources": {
|
|
247
|
+
name: {
|
|
248
|
+
"attributes": [asdict(a) for a in attrs],
|
|
249
|
+
"actions": [asdict(a) for a in self.actions.values() if a.resource == name],
|
|
250
|
+
}
|
|
251
|
+
for name, attrs in self.resource_attributes.items()
|
|
252
|
+
},
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _read_fields(d: ResourceDefinition) -> dict[str, str | None]:
|
|
257
|
+
schema = d.schemas.get("read")
|
|
258
|
+
if schema is None:
|
|
259
|
+
return {}
|
|
260
|
+
return {n: f.description for n, f in schema.model_fields.items() if n != d.id_field}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _write_fields(d: ResourceDefinition) -> dict[str, str | None]:
|
|
264
|
+
out: dict[str, str | None] = {}
|
|
265
|
+
for role in ("create", "update"):
|
|
266
|
+
schema = d.schemas.get(role) if d.enabled(role) else None
|
|
267
|
+
for n, f in (schema.model_fields if schema else {}).items():
|
|
268
|
+
if n != d.id_field:
|
|
269
|
+
out.setdefault(n, f.description)
|
|
270
|
+
return out
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def action_matches(
|
|
274
|
+
pattern: str, action: str, *, wildcards: bool = True, exact: bool = False
|
|
275
|
+
) -> bool:
|
|
276
|
+
"""``*`` matches one segment; a trailing ``*`` matches the rest.
|
|
277
|
+
|
|
278
|
+
With ``wildcards=False`` (sensitive resources) the resource segment must be
|
|
279
|
+
named explicitly; with ``exact`` only the action itself matches.
|
|
280
|
+
"""
|
|
281
|
+
if exact:
|
|
282
|
+
return pattern == action
|
|
283
|
+
p, a = pattern.split(":"), action.split(":")
|
|
284
|
+
if not wildcards and p[0] != a[0]:
|
|
285
|
+
return False
|
|
286
|
+
for i, part in enumerate(p):
|
|
287
|
+
if part == "*" and i == len(p) - 1:
|
|
288
|
+
return len(a) >= len(p)
|
|
289
|
+
if i >= len(a) or (part != "*" and part != a[i]):
|
|
290
|
+
return False
|
|
291
|
+
return len(a) == len(p)
|
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"""The condition language of policies: JSON, safe to store and to edit from a UI.
|
|
2
|
+
|
|
3
|
+
A condition is a JSON value:
|
|
4
|
+
|
|
5
|
+
- an operator object with one key: ``{"eq": [a, b]}``, ``{"and": [c1, c2]}``,
|
|
6
|
+
``{"not": c}``, ``{"exists": a}``;
|
|
7
|
+
- operands are literals (string, number, boolean, null, list) or attribute
|
|
8
|
+
references ``{"attr": "resource.amount"}``.
|
|
9
|
+
|
|
10
|
+
Operators: ``eq ne lt le gt ge`` (two operands), ``in nin`` (value, list),
|
|
11
|
+
``contains`` (list, value), ``exists`` (one operand), ``and or`` (list of
|
|
12
|
+
conditions), ``not`` (one condition).
|
|
13
|
+
|
|
14
|
+
Attribute namespaces: ``subject`` (the caller), ``resource`` (the record),
|
|
15
|
+
``input`` (validated input of the operation) and ``context`` (operation data).
|
|
16
|
+
|
|
17
|
+
Evaluation is three-valued: an attribute of a namespace that is not known yet
|
|
18
|
+
(the record before it is loaded) makes the result ``UNKNOWN``. ``partial`` keeps
|
|
19
|
+
the unknown parts as a residual condition, which repositories apply as a query
|
|
20
|
+
filter (row-level visibility).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import enum
|
|
26
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from datetime import date, datetime
|
|
29
|
+
from decimal import Decimal, InvalidOperation
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
COMPARISONS = ("eq", "ne", "lt", "le", "gt", "ge")
|
|
33
|
+
MEMBERSHIP = ("in", "nin", "contains")
|
|
34
|
+
#: Text: ``icontains`` is true when the text on the left holds the one on the
|
|
35
|
+
#: right, ignoring case (searches use it).
|
|
36
|
+
TEXT = ("icontains",)
|
|
37
|
+
LOGICAL = ("and", "or", "not")
|
|
38
|
+
OPERATORS = (*COMPARISONS, *MEMBERSHIP, *TEXT, "exists", *LOGICAL)
|
|
39
|
+
NAMESPACES = ("subject", "resource", "input", "context")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _Unknown(enum.Enum):
|
|
43
|
+
UNKNOWN = "unknown"
|
|
44
|
+
|
|
45
|
+
def __bool__(self) -> bool: # pragma: no cover - guard against accidental use
|
|
46
|
+
raise TypeError("UNKNOWN has no truth value; compare with `is UNKNOWN`")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
UNKNOWN = _Unknown.UNKNOWN
|
|
50
|
+
type Tristate = bool | _Unknown
|
|
51
|
+
type Condition = Any # JSON value
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class Problem:
|
|
56
|
+
"""A problem found validating a condition, with where it is."""
|
|
57
|
+
|
|
58
|
+
path: str
|
|
59
|
+
message: str
|
|
60
|
+
|
|
61
|
+
def to_dict(self) -> dict[str, str]:
|
|
62
|
+
"""The problem as JSON-ready data."""
|
|
63
|
+
return {"path": self.path, "message": self.message}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# ---------------------------------------------------------------- structure
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_attr(value: Any) -> bool:
|
|
70
|
+
"""Whether ``value`` is an attribute reference: ``{"attr": "resource.amount"}``."""
|
|
71
|
+
return isinstance(value, Mapping) and set(value) == {"attr"} and isinstance(value["attr"], str)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _op(node: Any) -> tuple[str, Any]:
|
|
75
|
+
if not isinstance(node, Mapping) or len(node) != 1:
|
|
76
|
+
raise ValueError("a condition is an object with exactly one operator key")
|
|
77
|
+
((op, args),) = node.items()
|
|
78
|
+
if op not in OPERATORS:
|
|
79
|
+
raise ValueError(f"unknown operator {op!r}")
|
|
80
|
+
return op, args
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def attributes(node: Condition) -> set[str]:
|
|
84
|
+
"""Attribute paths referenced by a condition."""
|
|
85
|
+
found: set[str] = set()
|
|
86
|
+
|
|
87
|
+
def walk(value: Any) -> None:
|
|
88
|
+
if is_attr(value):
|
|
89
|
+
found.add(value["attr"])
|
|
90
|
+
elif isinstance(value, Mapping):
|
|
91
|
+
for v in value.values():
|
|
92
|
+
walk(v)
|
|
93
|
+
elif isinstance(value, list):
|
|
94
|
+
for v in value:
|
|
95
|
+
walk(v)
|
|
96
|
+
|
|
97
|
+
walk(node)
|
|
98
|
+
return found
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# --------------------------------------------------------------- validation
|
|
102
|
+
|
|
103
|
+
#: Attribute types published by the catalogue.
|
|
104
|
+
TYPES = ("string", "number", "boolean", "datetime", "date", "list", "object", "any")
|
|
105
|
+
_ORDERED = {"number", "datetime", "date", "string", "any"}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _literal_type(value: Any) -> str:
|
|
109
|
+
if value is None:
|
|
110
|
+
return "any"
|
|
111
|
+
if isinstance(value, bool):
|
|
112
|
+
return "boolean"
|
|
113
|
+
if isinstance(value, int | float | Decimal):
|
|
114
|
+
return "number"
|
|
115
|
+
if isinstance(value, str):
|
|
116
|
+
return "string"
|
|
117
|
+
if isinstance(value, list):
|
|
118
|
+
return "list"
|
|
119
|
+
if isinstance(value, Mapping):
|
|
120
|
+
return "object"
|
|
121
|
+
return "any"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _compatible(a: str, b: str) -> bool:
|
|
125
|
+
if "any" in (a, b) or a == b:
|
|
126
|
+
return True
|
|
127
|
+
# dates are written as ISO strings in JSON
|
|
128
|
+
return {a, b} <= {"string", "date", "datetime"}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def validate(
|
|
132
|
+
node: Condition,
|
|
133
|
+
types: Mapping[str, str] | Callable[[str], str | None],
|
|
134
|
+
*,
|
|
135
|
+
path: str = "$",
|
|
136
|
+
) -> list[Problem]:
|
|
137
|
+
"""Structural and type problems of a condition (empty list when valid).
|
|
138
|
+
|
|
139
|
+
``types`` maps attribute paths to catalogue types, or is a function returning
|
|
140
|
+
the type or ``None`` for an unknown attribute.
|
|
141
|
+
"""
|
|
142
|
+
lookup = types if callable(types) else types.get
|
|
143
|
+
problems: list[Problem] = []
|
|
144
|
+
|
|
145
|
+
def operand_type(value: Any, at: str) -> str | None:
|
|
146
|
+
if is_attr(value):
|
|
147
|
+
name = value["attr"]
|
|
148
|
+
if name.split(".", 1)[0] not in NAMESPACES:
|
|
149
|
+
problems.append(Problem(at, f"unknown namespace in {name!r}"))
|
|
150
|
+
return None
|
|
151
|
+
kind = lookup(name)
|
|
152
|
+
if kind is None:
|
|
153
|
+
problems.append(Problem(at, f"unknown attribute {name!r}"))
|
|
154
|
+
return kind
|
|
155
|
+
if isinstance(value, Mapping):
|
|
156
|
+
problems.append(Problem(at, "operands are literals or {'attr': ...} references"))
|
|
157
|
+
return None
|
|
158
|
+
return _literal_type(value)
|
|
159
|
+
|
|
160
|
+
def check(value: Any, at: str) -> None:
|
|
161
|
+
try:
|
|
162
|
+
op, args = _op(value)
|
|
163
|
+
except ValueError as exc:
|
|
164
|
+
problems.append(Problem(at, str(exc)))
|
|
165
|
+
return
|
|
166
|
+
here = f"{at}.{op}"
|
|
167
|
+
if op in ("and", "or"):
|
|
168
|
+
if not isinstance(args, list) or not args:
|
|
169
|
+
problems.append(Problem(here, f"'{op}' takes a non-empty list of conditions"))
|
|
170
|
+
return
|
|
171
|
+
for i, child in enumerate(args):
|
|
172
|
+
check(child, f"{here}[{i}]")
|
|
173
|
+
elif op == "not":
|
|
174
|
+
check(args, here)
|
|
175
|
+
elif op == "exists":
|
|
176
|
+
if not is_attr(args):
|
|
177
|
+
problems.append(Problem(here, "'exists' takes an attribute reference"))
|
|
178
|
+
else:
|
|
179
|
+
operand_type(args, here)
|
|
180
|
+
else:
|
|
181
|
+
if not isinstance(args, list) or len(args) != 2:
|
|
182
|
+
problems.append(Problem(here, f"'{op}' takes two operands"))
|
|
183
|
+
return
|
|
184
|
+
left = operand_type(args[0], f"{here}[0]")
|
|
185
|
+
right = operand_type(args[1], f"{here}[1]")
|
|
186
|
+
if left is None or right is None:
|
|
187
|
+
return
|
|
188
|
+
if op in ("in", "nin") and right not in ("list", "any"):
|
|
189
|
+
problems.append(Problem(f"{here}[1]", f"'{op}' needs a list on the right"))
|
|
190
|
+
elif op == "contains" and left not in ("list", "any"):
|
|
191
|
+
problems.append(Problem(f"{here}[0]", "'contains' needs a list on the left"))
|
|
192
|
+
elif op == "icontains" and not {left, right} <= {"string", "any"}:
|
|
193
|
+
problems.append(Problem(here, "'icontains' needs text on both sides"))
|
|
194
|
+
elif op in COMPARISONS and not _compatible(left, right):
|
|
195
|
+
problems.append(Problem(here, f"cannot compare {left} with {right}"))
|
|
196
|
+
elif op in ("lt", "le", "gt", "ge") and not {left, right} <= _ORDERED:
|
|
197
|
+
problems.append(Problem(here, f"'{op}' needs ordered values, got {left}"))
|
|
198
|
+
|
|
199
|
+
check(node, path)
|
|
200
|
+
return problems
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# --------------------------------------------------------------- evaluation
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class Env:
|
|
207
|
+
"""Attribute values for evaluation. Namespaces missing from ``known`` are
|
|
208
|
+
UNKNOWN; missing attributes of a known namespace are ``None``."""
|
|
209
|
+
|
|
210
|
+
def __init__(self, **namespaces: Any) -> None:
|
|
211
|
+
self.namespaces = namespaces
|
|
212
|
+
|
|
213
|
+
def resolve(self, name: str) -> Any:
|
|
214
|
+
"""The value of an attribute such as ``resource.owner``; ``UNKNOWN`` when its namespace is
|
|
215
|
+
not known yet."""
|
|
216
|
+
namespace, _, rest = name.partition(".")
|
|
217
|
+
if namespace not in self.namespaces:
|
|
218
|
+
return UNKNOWN
|
|
219
|
+
value: Any = self.namespaces[namespace]
|
|
220
|
+
for part in rest.split(".") if rest else ():
|
|
221
|
+
if value is None:
|
|
222
|
+
return None
|
|
223
|
+
value = value.get(part) if isinstance(value, Mapping) else getattr(value, part, None)
|
|
224
|
+
return value
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _normalise(value: Any) -> Any:
|
|
228
|
+
if isinstance(value, enum.Enum):
|
|
229
|
+
value = value.value
|
|
230
|
+
if isinstance(value, frozenset | set | tuple):
|
|
231
|
+
return list(value)
|
|
232
|
+
return value
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _coerce_pair(a: Any, b: Any) -> tuple[Any, Any]:
|
|
236
|
+
a, b = _normalise(a), _normalise(b)
|
|
237
|
+
if isinstance(a, datetime) and isinstance(b, str):
|
|
238
|
+
return a, datetime.fromisoformat(b)
|
|
239
|
+
if isinstance(b, datetime) and isinstance(a, str):
|
|
240
|
+
return datetime.fromisoformat(a), b
|
|
241
|
+
if isinstance(a, date) and isinstance(b, str):
|
|
242
|
+
return a, date.fromisoformat(b)
|
|
243
|
+
if isinstance(b, date) and isinstance(a, str):
|
|
244
|
+
return date.fromisoformat(a), b
|
|
245
|
+
numeric = (int, float, Decimal)
|
|
246
|
+
if (
|
|
247
|
+
isinstance(a, numeric)
|
|
248
|
+
and isinstance(b, numeric)
|
|
249
|
+
and not isinstance(a, bool)
|
|
250
|
+
and not isinstance(b, bool)
|
|
251
|
+
and (isinstance(a, Decimal) or isinstance(b, Decimal))
|
|
252
|
+
):
|
|
253
|
+
try:
|
|
254
|
+
return Decimal(str(a)), Decimal(str(b))
|
|
255
|
+
except InvalidOperation: # pragma: no cover
|
|
256
|
+
return a, b
|
|
257
|
+
return a, b
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _compare(op: str, a: Any, b: Any) -> bool:
|
|
261
|
+
try:
|
|
262
|
+
a, b = _coerce_pair(a, b)
|
|
263
|
+
except ValueError:
|
|
264
|
+
return False
|
|
265
|
+
if op == "eq":
|
|
266
|
+
return bool(a == b)
|
|
267
|
+
if op == "ne":
|
|
268
|
+
return bool(a != b)
|
|
269
|
+
if a is None or b is None:
|
|
270
|
+
return False
|
|
271
|
+
try:
|
|
272
|
+
return bool({"lt": a < b, "le": a <= b, "gt": a > b, "ge": a >= b}[op])
|
|
273
|
+
except TypeError:
|
|
274
|
+
return False
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _member(value: Any, collection: Any) -> bool:
|
|
278
|
+
collection = _normalise(collection)
|
|
279
|
+
if not isinstance(collection, list):
|
|
280
|
+
return False
|
|
281
|
+
return any(_compare("eq", value, item) for item in collection)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _and(values: Iterable[Tristate]) -> Tristate:
|
|
285
|
+
unknown = False
|
|
286
|
+
for v in values:
|
|
287
|
+
if v is False:
|
|
288
|
+
return False
|
|
289
|
+
if v is UNKNOWN:
|
|
290
|
+
unknown = True
|
|
291
|
+
return UNKNOWN if unknown else True
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _or(values: Iterable[Tristate]) -> Tristate:
|
|
295
|
+
unknown = False
|
|
296
|
+
for v in values:
|
|
297
|
+
if v is True:
|
|
298
|
+
return True
|
|
299
|
+
if v is UNKNOWN:
|
|
300
|
+
unknown = True
|
|
301
|
+
return UNKNOWN if unknown else False
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def evaluate(node: Condition, env: Env) -> Tristate:
|
|
305
|
+
"""Evaluate ``node``; ``None`` (no condition) is ``True``."""
|
|
306
|
+
if node is None:
|
|
307
|
+
return True
|
|
308
|
+
op, args = _op(node)
|
|
309
|
+
if op == "and":
|
|
310
|
+
return _and(evaluate(c, env) for c in args)
|
|
311
|
+
if op == "or":
|
|
312
|
+
return _or(evaluate(c, env) for c in args)
|
|
313
|
+
if op == "not":
|
|
314
|
+
inner = evaluate(args, env)
|
|
315
|
+
return inner if inner is UNKNOWN else not inner
|
|
316
|
+
if op == "exists":
|
|
317
|
+
value = env.resolve(args["attr"])
|
|
318
|
+
return UNKNOWN if value is UNKNOWN else value is not None
|
|
319
|
+
|
|
320
|
+
def value_of(operand: Any) -> Any:
|
|
321
|
+
return env.resolve(operand["attr"]) if is_attr(operand) else operand
|
|
322
|
+
|
|
323
|
+
a, b = value_of(args[0]), value_of(args[1])
|
|
324
|
+
if a is UNKNOWN or b is UNKNOWN:
|
|
325
|
+
return _Unknown.UNKNOWN # (mypy reads the narrowed name as Any)
|
|
326
|
+
if op in COMPARISONS:
|
|
327
|
+
return _compare(op, a, b)
|
|
328
|
+
if op == "in":
|
|
329
|
+
return _member(a, b)
|
|
330
|
+
if op == "nin":
|
|
331
|
+
return not _member(a, b)
|
|
332
|
+
if op == "icontains":
|
|
333
|
+
return isinstance(a, str) and isinstance(b, str) and b.casefold() in a.casefold()
|
|
334
|
+
return _member(b, a) # contains
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# ----------------------------------------------------------- partial evaluation
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def partial(node: Condition, env: Env) -> Condition | bool:
|
|
341
|
+
"""Substitute known attributes and simplify.
|
|
342
|
+
|
|
343
|
+
Returns ``True``/``False`` when decided, otherwise a residual condition that
|
|
344
|
+
only references attributes of unknown namespaces (e.g. ``resource.*``).
|
|
345
|
+
"""
|
|
346
|
+
if node is None:
|
|
347
|
+
return True
|
|
348
|
+
op, args = _op(node)
|
|
349
|
+
if op in ("and", "or"):
|
|
350
|
+
parts = [partial(c, env) for c in args]
|
|
351
|
+
absorbing, neutral = (False, True) if op == "and" else (True, False)
|
|
352
|
+
if any(p is absorbing for p in parts):
|
|
353
|
+
return absorbing
|
|
354
|
+
rest = [p for p in parts if p is not neutral]
|
|
355
|
+
if not rest:
|
|
356
|
+
return neutral
|
|
357
|
+
return rest[0] if len(rest) == 1 else {op: rest}
|
|
358
|
+
if op == "not":
|
|
359
|
+
inner = partial(args, env)
|
|
360
|
+
return (not inner) if isinstance(inner, bool) else {"not": inner}
|
|
361
|
+
result = evaluate(node, env)
|
|
362
|
+
if result is not UNKNOWN:
|
|
363
|
+
return bool(result)
|
|
364
|
+
|
|
365
|
+
def substitute(operand: Any) -> Any:
|
|
366
|
+
if is_attr(operand):
|
|
367
|
+
value = env.resolve(operand["attr"])
|
|
368
|
+
return operand if value is UNKNOWN else _normalise(value)
|
|
369
|
+
return operand
|
|
370
|
+
|
|
371
|
+
if op == "exists":
|
|
372
|
+
return node
|
|
373
|
+
return {op: [substitute(args[0]), substitute(args[1])]}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def conjunction(*parts: Condition | bool | None) -> Condition | bool:
|
|
377
|
+
"""AND of conditions, simplified (``None`` and ``True`` are neutral)."""
|
|
378
|
+
rest = []
|
|
379
|
+
for p in parts:
|
|
380
|
+
if p is None or p is True:
|
|
381
|
+
continue
|
|
382
|
+
if p is False:
|
|
383
|
+
return False
|
|
384
|
+
rest.append(p)
|
|
385
|
+
if not rest:
|
|
386
|
+
return True
|
|
387
|
+
return rest[0] if len(rest) == 1 else {"and": rest}
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def disjunction(*parts: Condition | bool) -> Condition | bool:
|
|
391
|
+
"""The OR of the parts, simplified: ``True`` wins, ``False`` and ``None`` drop out."""
|
|
392
|
+
rest = []
|
|
393
|
+
for p in parts:
|
|
394
|
+
if p is True:
|
|
395
|
+
return True
|
|
396
|
+
if p is False or p is None:
|
|
397
|
+
continue
|
|
398
|
+
rest.append(p)
|
|
399
|
+
if not rest:
|
|
400
|
+
return False
|
|
401
|
+
return rest[0] if len(rest) == 1 else {"or": rest}
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def negation(part: Condition | bool) -> Condition | bool:
|
|
405
|
+
"""The NOT of a condition (a boolean is negated directly)."""
|
|
406
|
+
return (not part) if isinstance(part, bool) else {"not": part}
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def matches(condition: Condition | bool | None, entity: Any) -> bool:
|
|
410
|
+
"""Apply a residual (``resource.*``) condition to an entity: the in-memory
|
|
411
|
+
query filter."""
|
|
412
|
+
if condition is None or condition is True:
|
|
413
|
+
return True
|
|
414
|
+
if condition is False:
|
|
415
|
+
return False
|
|
416
|
+
return evaluate(condition, Env(resource=entity)) is True
|