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,300 @@
|
|
|
1
|
+
"""API keys for machine clients that cannot use OAuth (scripts, partners'
|
|
2
|
+
servers, cron jobs). See docs/api-keys.md.
|
|
3
|
+
|
|
4
|
+
```python
|
|
5
|
+
registry.register_api_keys()
|
|
6
|
+
keys = ApiKeyAuthenticator(uow_factory, fallback=oidc) # rek_ tokens here, the rest to OIDC
|
|
7
|
+
mount_resources(app, registry, manager, actor_dependency=bearer_actor(keys))
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
A key is ``rek_<id>_<secret>``, sent as ``Authorization: Bearer <key>`` (or
|
|
11
|
+
``X-API-Key``). Only a SHA-256 hash of the secret is stored, and the full key
|
|
12
|
+
is returned once, by ``create``. Each key acts as a principal
|
|
13
|
+
(``apikey:<id>``) with the roles and tenant it was created with: at most the
|
|
14
|
+
creator's permissions. Keys expire (``expires_at``) and are revoked with the
|
|
15
|
+
``revoke`` transition, both audited like any change.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import hashlib
|
|
21
|
+
import hmac
|
|
22
|
+
import secrets
|
|
23
|
+
import time
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from datetime import UTC, datetime
|
|
26
|
+
from typing import Any, override
|
|
27
|
+
|
|
28
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
29
|
+
from statemachine import State, StateMachine
|
|
30
|
+
|
|
31
|
+
from resource_engine.application.context import OperationContext
|
|
32
|
+
from resource_engine.application.resource import Resource
|
|
33
|
+
from resource_engine.application.settings import Access, Listing
|
|
34
|
+
from resource_engine.errors import AuthenticationFailed, ConfigurationError, InvalidPolicy
|
|
35
|
+
from resource_engine.ports.identity import Authenticator, Principal
|
|
36
|
+
|
|
37
|
+
PREFIX = "rek_"
|
|
38
|
+
PROVIDER = "apikey"
|
|
39
|
+
RESOURCE = "authz_api_keys"
|
|
40
|
+
ISSUER = "resource-engine"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class ApiKey:
|
|
45
|
+
"""A machine client's key. Only the hash of its secret is stored."""
|
|
46
|
+
|
|
47
|
+
id: str
|
|
48
|
+
name: str
|
|
49
|
+
secret_hash: str
|
|
50
|
+
roles: list[str] = field(default_factory=list)
|
|
51
|
+
tenant: str | None = None
|
|
52
|
+
status: str | None = None
|
|
53
|
+
expires_at: datetime | None = None
|
|
54
|
+
last_used_at: datetime | None = None
|
|
55
|
+
created_at: datetime | None = None
|
|
56
|
+
created_by: str | None = None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class ApiKeyStates(StateMachine):
|
|
60
|
+
"""Lifecycle of an API key.
|
|
61
|
+
|
|
62
|
+
States:
|
|
63
|
+
active: The key authenticates requests (until it expires).
|
|
64
|
+
revoked: The key no longer authenticates. Final.
|
|
65
|
+
|
|
66
|
+
Transitions:
|
|
67
|
+
revoke: Withdraw the key at once.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
active = State("Active", initial=True)
|
|
71
|
+
revoked = State("Revoked", final=True)
|
|
72
|
+
revoke = active.to(revoked)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ApiKeyCreate(BaseModel):
|
|
76
|
+
"""A new key for a machine client."""
|
|
77
|
+
|
|
78
|
+
name: str = Field(min_length=1, max_length=200, description="What the key is for")
|
|
79
|
+
roles: list[str] = Field(
|
|
80
|
+
min_length=1, description="Roles the key acts with (at most the creator's)"
|
|
81
|
+
)
|
|
82
|
+
expires_at: datetime | None = Field(default=None, description="When it stops working")
|
|
83
|
+
tenant: str | None = Field(
|
|
84
|
+
default=None, description="Tenant it acts in (default: the creator's)"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ApiKeyUpdate(BaseModel):
|
|
89
|
+
"""Rename a key or move its expiry (roles never change: create another key)."""
|
|
90
|
+
|
|
91
|
+
name: str | None = Field(default=None, min_length=1, max_length=200)
|
|
92
|
+
expires_at: datetime | None = None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class ApiKeyRead(BaseModel):
|
|
96
|
+
"""An API key, without its secret."""
|
|
97
|
+
|
|
98
|
+
model_config = ConfigDict(from_attributes=True)
|
|
99
|
+
|
|
100
|
+
id: str = Field(description="Key id: the key starts with rek_<id>_")
|
|
101
|
+
name: str
|
|
102
|
+
roles: list[str]
|
|
103
|
+
tenant: str | None = None
|
|
104
|
+
status: str = Field(description="active or revoked")
|
|
105
|
+
expires_at: datetime | None = None
|
|
106
|
+
last_used_at: datetime | None = Field(default=None, description="Last request (to a minute)")
|
|
107
|
+
created_at: datetime | None = None
|
|
108
|
+
created_by: str | None = None
|
|
109
|
+
key: str | None = Field(
|
|
110
|
+
default=None,
|
|
111
|
+
description="The full key, only in the create response: store it now, it is not "
|
|
112
|
+
"shown again",
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def hash_secret(secret: str) -> str:
|
|
117
|
+
"""The SHA-256 of an API key's secret, which is all that is stored."""
|
|
118
|
+
return hashlib.sha256(secret.encode()).hexdigest()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def parse(token: str) -> tuple[str, str] | None:
|
|
122
|
+
"""``rek_<id>_<secret>`` → ``(id, secret)``."""
|
|
123
|
+
if not token.startswith(PREFIX):
|
|
124
|
+
return None
|
|
125
|
+
key_id, sep, secret = token[len(PREFIX) :].partition("_")
|
|
126
|
+
return (key_id, secret) if sep and key_id and secret else None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def _check_new_key(ctx: OperationContext) -> None:
|
|
130
|
+
"""The roles exist and grant nothing the creator lacks; the tenant is the
|
|
131
|
+
creator's unless a cross-tenant caller names another."""
|
|
132
|
+
from resource_engine.authz.resources import _actor_id, _require_held
|
|
133
|
+
from resource_engine.tenancy import is_cross_tenant
|
|
134
|
+
|
|
135
|
+
if "authz" not in ctx.services:
|
|
136
|
+
raise ConfigurationError(
|
|
137
|
+
"API keys need an authorizer: pass authorizer= to the ResourceManager",
|
|
138
|
+
doc="docs/api-keys.md",
|
|
139
|
+
)
|
|
140
|
+
authz = ctx.service("authz")
|
|
141
|
+
key: ApiKey = ctx.entity
|
|
142
|
+
actions: set[str] = set()
|
|
143
|
+
store = getattr(authz, "store", None)
|
|
144
|
+
policies = await store.policies() if store is not None else []
|
|
145
|
+
for role in key.roles:
|
|
146
|
+
system = authz.config.system_role(role)
|
|
147
|
+
if system is not None:
|
|
148
|
+
for grant in system.grants:
|
|
149
|
+
actions |= set(
|
|
150
|
+
authz.catalog.matching(grant, include_sensitive=system.include_sensitive)
|
|
151
|
+
)
|
|
152
|
+
continue
|
|
153
|
+
if await ctx.repository("authz_roles").get(role) is None:
|
|
154
|
+
raise InvalidPolicy(
|
|
155
|
+
f"Unknown role {role!r}",
|
|
156
|
+
details={"problems": [{"path": "$.roles", "message": f"no role {role!r}"}]},
|
|
157
|
+
)
|
|
158
|
+
for policy in policies:
|
|
159
|
+
if policy.effect == "allow" and role in (policy.subjects or {}).get("roles", []):
|
|
160
|
+
for pattern in policy.actions:
|
|
161
|
+
actions |= set(authz.catalog.matching(pattern))
|
|
162
|
+
await _require_held(ctx, sorted(actions))
|
|
163
|
+
own = getattr(ctx.actor, "tenant", None)
|
|
164
|
+
if key.tenant is None:
|
|
165
|
+
key.tenant = own
|
|
166
|
+
elif key.tenant != own and not await is_cross_tenant(ctx.actor, authz):
|
|
167
|
+
raise InvalidPolicy(
|
|
168
|
+
f"You cannot create keys for tenant {key.tenant!r}",
|
|
169
|
+
details={"problems": [{"path": "$.tenant", "message": "not your tenant"}]},
|
|
170
|
+
)
|
|
171
|
+
key.created_at = datetime.now(UTC)
|
|
172
|
+
key.created_by = _actor_id(ctx)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class ApiKeyResource(Resource):
|
|
176
|
+
"""API keys for machine clients that cannot use OAuth.
|
|
177
|
+
|
|
178
|
+
Business area:
|
|
179
|
+
Permissions
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
name = RESOURCE
|
|
183
|
+
model = ApiKey
|
|
184
|
+
id_type = str
|
|
185
|
+
schemas = {"create": ApiKeyCreate, "update": ApiKeyUpdate, "read": ApiKeyRead}
|
|
186
|
+
operations = ["list", "get", "create", "update"]
|
|
187
|
+
operation_docs = {
|
|
188
|
+
"list": "Lists the API keys (never their secrets).",
|
|
189
|
+
"get": "Returns an API key (never its secret).",
|
|
190
|
+
"create": "Creates an API key; the response carries the full key, once.",
|
|
191
|
+
"update": "Renames a key or changes its expiry.",
|
|
192
|
+
}
|
|
193
|
+
state_machine = ApiKeyStates
|
|
194
|
+
listing = Listing(
|
|
195
|
+
filterable=["status", "tenant", "created_by"],
|
|
196
|
+
sortable=["name", "created_at", "last_used_at", "expires_at"],
|
|
197
|
+
)
|
|
198
|
+
access = Access(wildcards=False)
|
|
199
|
+
hooks = {"before_create": [_check_new_key]}
|
|
200
|
+
|
|
201
|
+
@classmethod
|
|
202
|
+
@override
|
|
203
|
+
def build_entity(cls, data: Any, ctx: OperationContext) -> ApiKey:
|
|
204
|
+
key_id = secrets.token_hex(8)
|
|
205
|
+
secret = secrets.token_urlsafe(32)
|
|
206
|
+
ctx.extras["api_key"] = f"{PREFIX}{key_id}_{secret}"
|
|
207
|
+
ctx.extras["never_store"] = {"key"} # not in idempotency records either
|
|
208
|
+
return ApiKey(
|
|
209
|
+
id=key_id,
|
|
210
|
+
name=data.name,
|
|
211
|
+
roles=sorted(set(data.roles)),
|
|
212
|
+
tenant=data.tenant,
|
|
213
|
+
expires_at=data.expires_at,
|
|
214
|
+
secret_hash=hash_secret(secret),
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
@classmethod
|
|
218
|
+
@override
|
|
219
|
+
def to_read(cls, entity: Any, ctx: OperationContext) -> Any:
|
|
220
|
+
read = ApiKeyRead.model_validate(entity, from_attributes=True)
|
|
221
|
+
if ctx.operation == "create" and "api_key" in ctx.extras:
|
|
222
|
+
read.key = ctx.extras["api_key"]
|
|
223
|
+
return read
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
class ApiKeyAuthenticator(Authenticator):
|
|
227
|
+
"""An ``Authenticator`` for API keys; other tokens go to ``fallback``.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
uow_factory: To read the keys (``authz_api_keys``).
|
|
231
|
+
fallback: Authenticator for tokens that are not API keys (OIDC);
|
|
232
|
+
without one they are refused.
|
|
233
|
+
touch_every: Seconds between ``last_used_at`` updates of one key.
|
|
234
|
+
"""
|
|
235
|
+
|
|
236
|
+
def __init__(
|
|
237
|
+
self,
|
|
238
|
+
uow_factory: Any,
|
|
239
|
+
*,
|
|
240
|
+
fallback: Any = None,
|
|
241
|
+
resource: str = RESOURCE,
|
|
242
|
+
touch_every: float = 60.0,
|
|
243
|
+
clock: Any = None,
|
|
244
|
+
) -> None:
|
|
245
|
+
self.uow_factory = uow_factory
|
|
246
|
+
self.fallback = fallback
|
|
247
|
+
self.resource = resource
|
|
248
|
+
self.touch_every = touch_every
|
|
249
|
+
self.clock = clock or (lambda: datetime.now(UTC))
|
|
250
|
+
self._touched: dict[str, float] = {}
|
|
251
|
+
|
|
252
|
+
@override
|
|
253
|
+
async def authenticate(self, token: str) -> Principal:
|
|
254
|
+
parsed = parse(token)
|
|
255
|
+
if parsed is None:
|
|
256
|
+
if self.fallback is not None and not token.startswith(PREFIX):
|
|
257
|
+
principal: Principal = await self.fallback.authenticate(token)
|
|
258
|
+
return principal
|
|
259
|
+
raise AuthenticationFailed("Invalid API key", reason="invalid")
|
|
260
|
+
key_id, secret = parsed
|
|
261
|
+
async with self.uow_factory() as uow:
|
|
262
|
+
key = await uow.repository(self.resource).get(key_id)
|
|
263
|
+
if key is None or not hmac.compare_digest(key.secret_hash, hash_secret(secret)):
|
|
264
|
+
raise AuthenticationFailed("Invalid API key", reason="invalid")
|
|
265
|
+
if key.status != "active":
|
|
266
|
+
raise AuthenticationFailed("The API key was revoked", reason="revoked")
|
|
267
|
+
now = self.clock()
|
|
268
|
+
if key.expires_at is not None and _aware(key.expires_at) <= now:
|
|
269
|
+
raise AuthenticationFailed("The API key expired", reason="expired")
|
|
270
|
+
principal = Principal( # before the commit: the record may expire then
|
|
271
|
+
subject=key.id,
|
|
272
|
+
issuer=ISSUER,
|
|
273
|
+
provider=PROVIDER,
|
|
274
|
+
name=key.name,
|
|
275
|
+
roles=frozenset(key.roles),
|
|
276
|
+
tenant=key.tenant,
|
|
277
|
+
client_id=key.id,
|
|
278
|
+
service=True,
|
|
279
|
+
)
|
|
280
|
+
if time.monotonic() - self._touched.get(key.id, -1e9) >= self.touch_every:
|
|
281
|
+
self._touched[key.id] = time.monotonic()
|
|
282
|
+
key.last_used_at = now
|
|
283
|
+
await uow.repository(self.resource).update(key)
|
|
284
|
+
await uow.commit()
|
|
285
|
+
return principal
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _aware(value: datetime) -> datetime:
|
|
289
|
+
return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
__all__ = [
|
|
293
|
+
"ApiKey",
|
|
294
|
+
"ApiKeyAuthenticator",
|
|
295
|
+
"ApiKeyCreate",
|
|
296
|
+
"ApiKeyRead",
|
|
297
|
+
"ApiKeyResource",
|
|
298
|
+
"ApiKeyUpdate",
|
|
299
|
+
"hash_secret",
|
|
300
|
+
]
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""What every role-aware authorizer shares: the catalogue, application roles,
|
|
2
|
+
system-role grants and the permission summaries behind ``/authz/me``."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from typing import TYPE_CHECKING, Any, override
|
|
8
|
+
|
|
9
|
+
from resource_engine.authz.catalog import FIELD_KINDS, Catalog, action_matches
|
|
10
|
+
from resource_engine.authz.config import AuthzConfig
|
|
11
|
+
from resource_engine.authz.roles import IdpRoleSource
|
|
12
|
+
from resource_engine.ports.authz import Authorizer
|
|
13
|
+
from resource_engine.ports.identity import Principal
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from resource_engine.application.registry import ResourceRegistry
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SystemPrincipal(Principal):
|
|
20
|
+
"""The engine itself (consumers, pipelines, jobs). Always allowed; cannot be
|
|
21
|
+
produced from a token."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def system_principal(name: str = "engine") -> SystemPrincipal:
|
|
25
|
+
"""A principal for work the engine does itself (workers, timers, consumers)."""
|
|
26
|
+
return SystemPrincipal(subject=name, issuer="resource-engine", provider="system", service=True)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def subject_view(principal: Principal, roles: Iterable[str]) -> dict[str, Any]:
|
|
30
|
+
"""The caller as policies see it (``subject.*``)."""
|
|
31
|
+
return {
|
|
32
|
+
"id": principal.id,
|
|
33
|
+
"subject": principal.subject,
|
|
34
|
+
"provider": principal.provider,
|
|
35
|
+
"roles": sorted(roles),
|
|
36
|
+
"groups": sorted(principal.groups),
|
|
37
|
+
"scopes": sorted(principal.scopes),
|
|
38
|
+
"tenant": principal.tenant,
|
|
39
|
+
"client_id": principal.client_id,
|
|
40
|
+
"service": principal.service,
|
|
41
|
+
"email": principal.email,
|
|
42
|
+
"name": principal.name,
|
|
43
|
+
"claims": dict(principal.claims),
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class RoleBasedAuthorizer(Authorizer):
|
|
48
|
+
"""Base of ``PolicyAuthorizer`` and ``EngineAuthorizer``.
|
|
49
|
+
|
|
50
|
+
Subclasses implement ``check``, ``scope`` and ``field_rules``.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, config: AuthzConfig) -> None:
|
|
54
|
+
self.config = config
|
|
55
|
+
self.role_source = config.role_source or IdpRoleSource(passthrough=True)
|
|
56
|
+
self.catalog: Catalog | None = None
|
|
57
|
+
|
|
58
|
+
def bind(self, registry: ResourceRegistry) -> None:
|
|
59
|
+
"""Called by ``ResourceManager``: build the catalogue from the registry."""
|
|
60
|
+
self.catalog = Catalog.from_registry(registry)
|
|
61
|
+
|
|
62
|
+
async def roles_of(self, principal: Principal) -> frozenset[str]:
|
|
63
|
+
"""The caller's application roles: from the role source, the API key and the bootstrap
|
|
64
|
+
mapping."""
|
|
65
|
+
roles = set(await self.role_source.roles(principal))
|
|
66
|
+
if principal.provider == "apikey" and principal.issuer == "resource-engine":
|
|
67
|
+
roles |= principal.roles # an API key carries application roles, checked on create
|
|
68
|
+
for provider_role in principal.roles | principal.groups:
|
|
69
|
+
if provider_role in self.config.bootstrap:
|
|
70
|
+
roles.add(self.config.bootstrap[provider_role])
|
|
71
|
+
return frozenset(roles)
|
|
72
|
+
|
|
73
|
+
def _wildcards(self, action: str) -> bool:
|
|
74
|
+
info = self.catalog.actions.get(action) if self.catalog else None
|
|
75
|
+
return info.wildcards if info else True
|
|
76
|
+
|
|
77
|
+
def _exact(self, action: str) -> bool:
|
|
78
|
+
info = self.catalog.actions.get(action) if self.catalog else None
|
|
79
|
+
return info.exact if info else False
|
|
80
|
+
|
|
81
|
+
def _system_grant(self, roles: Iterable[str], action: str) -> str | None:
|
|
82
|
+
wild, exact = self._wildcards(action), self._exact(action)
|
|
83
|
+
for name in sorted(roles):
|
|
84
|
+
role = self.config.system_role(name)
|
|
85
|
+
if role and any(
|
|
86
|
+
action_matches(g, action, wildcards=wild or role.include_sensitive, exact=exact)
|
|
87
|
+
for g in role.grants
|
|
88
|
+
):
|
|
89
|
+
return role.name
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
@override
|
|
93
|
+
async def check( # pragma: no cover
|
|
94
|
+
self,
|
|
95
|
+
principal: Any,
|
|
96
|
+
action: str,
|
|
97
|
+
*,
|
|
98
|
+
resource: Any = ...,
|
|
99
|
+
input: Any = ...,
|
|
100
|
+
context: dict[str, Any] | None = None,
|
|
101
|
+
) -> Any:
|
|
102
|
+
raise NotImplementedError
|
|
103
|
+
|
|
104
|
+
async def field_rules(
|
|
105
|
+
self, principal: Any, resource: str, mode: str
|
|
106
|
+
) -> Any: # pragma: no cover
|
|
107
|
+
"""The field decisions for ``principal`` on ``resource`` in ``mode`` (``read`` or
|
|
108
|
+
``write``)."""
|
|
109
|
+
raise NotImplementedError
|
|
110
|
+
|
|
111
|
+
async def permissions(self, principal: Principal | None) -> dict[str, str]:
|
|
112
|
+
"""Every catalogue action the principal may perform: ``allowed`` or
|
|
113
|
+
``conditional`` (depends on the record or the input)."""
|
|
114
|
+
out: dict[str, str] = {}
|
|
115
|
+
assert self.catalog is not None
|
|
116
|
+
for action, info in self.catalog.actions.items():
|
|
117
|
+
if info.kind in FIELD_KINDS:
|
|
118
|
+
continue
|
|
119
|
+
decision = await self.check(principal, action)
|
|
120
|
+
if decision.allowed is True:
|
|
121
|
+
out[action] = "allowed"
|
|
122
|
+
elif decision.allowed is None:
|
|
123
|
+
out[action] = "conditional"
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
async def field_permissions(
|
|
127
|
+
self, principal: Principal | None
|
|
128
|
+
) -> dict[str, dict[str, list[str]]]:
|
|
129
|
+
"""Per resource: fields ``hidden`` (not readable), ``readonly`` (not
|
|
130
|
+
writable) and ``conditional`` (depends on the record or input)."""
|
|
131
|
+
assert self.catalog is not None
|
|
132
|
+
out: dict[str, dict[str, list[str]]] = {}
|
|
133
|
+
for resource in self.catalog.resource_attributes:
|
|
134
|
+
read = (await self.field_rules(principal, resource, "read")).decide()
|
|
135
|
+
write = (await self.field_rules(principal, resource, "write")).decide()
|
|
136
|
+
entry = {
|
|
137
|
+
"hidden": sorted(read.denied),
|
|
138
|
+
"readonly": sorted(write.denied),
|
|
139
|
+
"conditional": sorted(read.conditional | write.conditional),
|
|
140
|
+
}
|
|
141
|
+
if any(entry.values()):
|
|
142
|
+
out[resource] = entry
|
|
143
|
+
return out
|