hermes-access-client 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.
- hermes_access_client/__init__.py +29 -0
- hermes_access_client/adapters/__init__.py +3 -0
- hermes_access_client/adapters/cedar_engine.py +218 -0
- hermes_access_client/adapters/cf_identity_groups.py +121 -0
- hermes_access_client/adapters/file_source.py +79 -0
- hermes_access_client/adapters/memory.py +117 -0
- hermes_access_client/adapters/schema_files.py +24 -0
- hermes_access_client/adapters/system_clock.py +13 -0
- hermes_access_client/adapters/urllib_fetch.py +38 -0
- hermes_access_client/adapters/yaml_config.py +33 -0
- hermes_access_client/app.py +68 -0
- hermes_access_client/domain/__init__.py +58 -0
- hermes_access_client/domain/decision.py +86 -0
- hermes_access_client/domain/engine.py +18 -0
- hermes_access_client/domain/errors.py +35 -0
- hermes_access_client/domain/hermes_schema.py +47 -0
- hermes_access_client/domain/ids.py +36 -0
- hermes_access_client/domain/json_schema.py +28 -0
- hermes_access_client/domain/manifest.py +48 -0
- hermes_access_client/domain/refs.py +104 -0
- hermes_access_client/domain/resolve.py +68 -0
- hermes_access_client/domain/settings.py +120 -0
- hermes_access_client/domain/snapshot.py +100 -0
- hermes_access_client/domain/versioned.py +46 -0
- hermes_access_client/ports.py +92 -0
- hermes_access_client/py.typed +0 -0
- hermes_access_client/services/__init__.py +3 -0
- hermes_access_client/services/access_client.py +266 -0
- hermes_access_client/services/decision_cache.py +66 -0
- hermes_access_client/services/roles.py +20 -0
- hermes_access_client-0.1.0.dist-info/METADATA +30 -0
- hermes_access_client-0.1.0.dist-info/RECORD +33 -0
- hermes_access_client-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Read-only client for hermes-access: fast in-process RBAC/ABAC decisions for Hermes apps.
|
|
2
|
+
|
|
3
|
+
Entry point: ``from_config(app="example-app")`` -> ``AccessClient``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
7
|
+
|
|
8
|
+
from hermes_access_client.app import from_config
|
|
9
|
+
from hermes_access_client.domain.decision import Decision, Health, Request
|
|
10
|
+
from hermes_access_client.domain.errors import HermesAccessError
|
|
11
|
+
from hermes_access_client.domain.refs import ActionRef, EntityRef
|
|
12
|
+
from hermes_access_client.services.access_client import AccessClient
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
__version__ = version("hermes-access-client")
|
|
16
|
+
except PackageNotFoundError: # pragma: no cover - source tree without install
|
|
17
|
+
__version__ = "0.0.0+unknown"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"AccessClient",
|
|
21
|
+
"ActionRef",
|
|
22
|
+
"Decision",
|
|
23
|
+
"EntityRef",
|
|
24
|
+
"Health",
|
|
25
|
+
"HermesAccessError",
|
|
26
|
+
"Request",
|
|
27
|
+
"__version__",
|
|
28
|
+
"from_config",
|
|
29
|
+
]
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""``CedarEngine``: the real ``PolicyEngine`` over cedarpy (client and admin both decide through it).
|
|
2
|
+
|
|
3
|
+
Per ``load`` the schema, the policy set, the non-user entities and the full entity set are parsed once. When a
|
|
4
|
+
request's groups are already among the principal's stored group parents (and it brings no extra entities) the
|
|
5
|
+
precompiled full set decides. Otherwise the engine adds the smallest slice per request: the ``Hermes::User``
|
|
6
|
+
entity with its stored parents plus the request's verified groups (``groups=None`` = UNKNOWN: no group parents
|
|
7
|
+
at all) and the app's extra entities. Requests that share the same delta are batch-decided together.
|
|
8
|
+
Cedar names policies by position (``policyN``); the engine maps those back to the stored ids, so
|
|
9
|
+
``Decision.reasons`` are stored policy ids.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
# cedarpy annotates some parameters as bare ``dict``; the unknowns stop at this adapter.
|
|
13
|
+
# pyright: reportUnknownMemberType=false
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import cast
|
|
22
|
+
|
|
23
|
+
import cedarpy
|
|
24
|
+
|
|
25
|
+
from hermes_access_client.domain.decision import Decision, Request
|
|
26
|
+
from hermes_access_client.domain.engine import CompiledPolicies
|
|
27
|
+
from hermes_access_client.domain.errors import PolicyCompileError
|
|
28
|
+
from hermes_access_client.domain.ids import user_id
|
|
29
|
+
from hermes_access_client.domain.refs import GROUP_TYPE, USER_TYPE, Entity, EntityRef
|
|
30
|
+
from hermes_access_client.domain.snapshot import CedarEntity, PolicyText
|
|
31
|
+
|
|
32
|
+
log = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
_DeltaKey = tuple[str, frozenset[str] | None, str, bool]
|
|
35
|
+
"""(principal id, groups or None, JSON of the extra entities, precompiled): requests sharing it share one
|
|
36
|
+
batch. ``precompiled`` means the stored entities already hold the request's group parents."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
40
|
+
class _CedarHandle:
|
|
41
|
+
schema: cedarpy.Schema
|
|
42
|
+
policy_set: cedarpy.PolicySet
|
|
43
|
+
base: cedarpy.Entities
|
|
44
|
+
full: cedarpy.Entities
|
|
45
|
+
users: dict[str, CedarEntity]
|
|
46
|
+
user_json: dict[str, dict[str, object]]
|
|
47
|
+
user_groups: dict[str, frozenset[str]]
|
|
48
|
+
id_by_position: dict[str, str]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _uid_json(ref: EntityRef) -> dict[str, str]:
|
|
52
|
+
return {"type": ref.type, "id": ref.id}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _entity_json(entity: Entity) -> dict[str, object]:
|
|
56
|
+
return {
|
|
57
|
+
"uid": _uid_json(entity.ref),
|
|
58
|
+
"attrs": dict(entity.attrs),
|
|
59
|
+
"parents": [_uid_json(p) for p in entity.parents],
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _check_single_statements(policies: Sequence[PolicyText]) -> None:
|
|
64
|
+
seen: set[str] = set()
|
|
65
|
+
for policy in policies:
|
|
66
|
+
if policy.id in seen:
|
|
67
|
+
raise PolicyCompileError(f"duplicate policy id {policy.id!r}")
|
|
68
|
+
seen.add(policy.id)
|
|
69
|
+
try:
|
|
70
|
+
count = len(cedarpy.PolicySet.from_str(policy.text))
|
|
71
|
+
except ValueError as exc:
|
|
72
|
+
raise PolicyCompileError(f"policy {policy.id!r} does not parse: {exc}") from exc
|
|
73
|
+
if count != 1:
|
|
74
|
+
raise PolicyCompileError(f"policy {policy.id!r} must hold exactly one statement, found {count}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _user_json(handle: _CedarHandle, principal: str, groups: frozenset[str] | None) -> dict[str, object]:
|
|
78
|
+
"""The user entity for one request: stored facts, parents = non-group parents + the allowed groups."""
|
|
79
|
+
stored: dict[str, object] | None = handle.user_json.get(principal)
|
|
80
|
+
if stored is None:
|
|
81
|
+
uid = {"type": USER_TYPE, "id": principal}
|
|
82
|
+
stored = {"uid": uid, "attrs": {"email": principal, "attrs": []}, "parents": []}
|
|
83
|
+
parents = [p for p in cast("list[dict[str, str]]", stored["parents"]) if p["type"] != GROUP_TYPE]
|
|
84
|
+
if groups is not None:
|
|
85
|
+
stored_groups = handle.user_groups.get(principal, frozenset())
|
|
86
|
+
wanted = sorted(stored_groups | groups)
|
|
87
|
+
parents.extend({"type": GROUP_TYPE, "id": g} for g in wanted)
|
|
88
|
+
return {**stored, "parents": parents}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _extras_key(req: Request) -> str:
|
|
92
|
+
if not req.extra_entities: # the common case: no JSON work at all
|
|
93
|
+
return "[]"
|
|
94
|
+
return json.dumps([_entity_json(e) for e in req.extra_entities], sort_keys=True)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _deny_all(count: int, error: str, generation: int) -> list[Decision]:
|
|
98
|
+
return [Decision(allow=False, errors=(error,), generation=generation) for _ in range(count)]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class CedarEngine:
|
|
102
|
+
"""``PolicyEngine`` backed by cedarpy 4.12 (precompiled ``PolicySet``/``Entities``/``Schema``)."""
|
|
103
|
+
|
|
104
|
+
def load(
|
|
105
|
+
self,
|
|
106
|
+
policies: Sequence[PolicyText],
|
|
107
|
+
schema: str,
|
|
108
|
+
entities: Sequence[CedarEntity],
|
|
109
|
+
*,
|
|
110
|
+
generation: int = 0,
|
|
111
|
+
) -> CompiledPolicies:
|
|
112
|
+
"""Compile one generation; raises ``PolicyCompileError`` on any parse or entity-validation error."""
|
|
113
|
+
_check_single_statements(policies)
|
|
114
|
+
users = {e.uid.id: e for e in entities if e.uid.type == USER_TYPE}
|
|
115
|
+
others = [e.model_dump(mode="json") for e in entities if e.uid.type != USER_TYPE]
|
|
116
|
+
try:
|
|
117
|
+
parsed_schema = cedarpy.Schema.from_str(schema)
|
|
118
|
+
policy_set = cedarpy.PolicySet.from_str("\n".join(p.text for p in policies))
|
|
119
|
+
base = cedarpy.Entities.from_json_str(json.dumps(others), parsed_schema)
|
|
120
|
+
everything = [e.model_dump(mode="json") for e in entities]
|
|
121
|
+
full = cedarpy.Entities.from_json_str(json.dumps(everything), parsed_schema)
|
|
122
|
+
except ValueError as exc:
|
|
123
|
+
raise PolicyCompileError(f"generation {generation} does not compile: {exc}") from exc
|
|
124
|
+
handle = _CedarHandle(
|
|
125
|
+
schema=parsed_schema,
|
|
126
|
+
policy_set=policy_set,
|
|
127
|
+
base=base,
|
|
128
|
+
full=full,
|
|
129
|
+
users=users,
|
|
130
|
+
user_json={uid: e.model_dump(mode="json") for uid, e in users.items()},
|
|
131
|
+
user_groups={
|
|
132
|
+
uid: frozenset(p.id for p in e.parents if p.type == GROUP_TYPE) for uid, e in users.items()
|
|
133
|
+
},
|
|
134
|
+
id_by_position={f"policy{i}": p.id for i, p in enumerate(policies)},
|
|
135
|
+
)
|
|
136
|
+
ids = tuple(p.id for p in policies)
|
|
137
|
+
log.debug("compiled generation %s: %d policies, %d entities", generation, len(ids), len(entities))
|
|
138
|
+
return CompiledPolicies(generation=generation, policy_ids=ids, handle=handle)
|
|
139
|
+
|
|
140
|
+
def decide(self, compiled: CompiledPolicies, requests: Sequence[Request]) -> list[Decision]:
|
|
141
|
+
"""Decide in request order; requests sharing principal, groups and extras go in one batch call."""
|
|
142
|
+
handle = compiled.handle
|
|
143
|
+
if not isinstance(handle, _CedarHandle):
|
|
144
|
+
raise PolicyCompileError("compiled policies were not built by CedarEngine")
|
|
145
|
+
batches: dict[_DeltaKey, list[int]] = {}
|
|
146
|
+
for index, req in enumerate(requests):
|
|
147
|
+
extras = _extras_key(req)
|
|
148
|
+
principal = user_id(req.principal)
|
|
149
|
+
stored = handle.user_groups.get(principal)
|
|
150
|
+
precompiled = (
|
|
151
|
+
stored is not None and req.groups is not None and extras == "[]" and req.groups <= stored
|
|
152
|
+
)
|
|
153
|
+
key = (principal, None if precompiled else req.groups, extras, precompiled)
|
|
154
|
+
batches.setdefault(key, []).append(index)
|
|
155
|
+
results: list[Decision | None] = [None] * len(requests)
|
|
156
|
+
for key, indices in batches.items():
|
|
157
|
+
batch = [requests[i] for i in indices]
|
|
158
|
+
for index, decision in zip(
|
|
159
|
+
indices, self._decide_batch(handle, compiled.generation, key, batch), strict=True
|
|
160
|
+
):
|
|
161
|
+
results[index] = decision
|
|
162
|
+
return [d for d in results if d is not None]
|
|
163
|
+
|
|
164
|
+
def _decide_batch(
|
|
165
|
+
self, handle: _CedarHandle, generation: int, key: _DeltaKey, batch: list[Request]
|
|
166
|
+
) -> list[Decision]:
|
|
167
|
+
principal, groups, extras, precompiled = key
|
|
168
|
+
if precompiled:
|
|
169
|
+
entities = handle.full
|
|
170
|
+
else:
|
|
171
|
+
base = handle.base
|
|
172
|
+
delta: list[object] = [_user_json(handle, principal, groups)]
|
|
173
|
+
if extras != "[]":
|
|
174
|
+
delta.extend(json.loads(extras))
|
|
175
|
+
# stored facts were validated at load; only app-supplied extras still need the schema
|
|
176
|
+
check = handle.schema if extras != "[]" else None
|
|
177
|
+
try:
|
|
178
|
+
entities = base.with_added_json_str(json.dumps(delta), check)
|
|
179
|
+
except ValueError as exc:
|
|
180
|
+
return _deny_all(len(batch), f"request entities invalid: {exc}", generation)
|
|
181
|
+
cedar_requests = [
|
|
182
|
+
{
|
|
183
|
+
"principal": {"type": USER_TYPE, "id": principal},
|
|
184
|
+
"action": _uid_json(req.action.uid),
|
|
185
|
+
"resource": _uid_json(req.resource),
|
|
186
|
+
"context": dict(req.context),
|
|
187
|
+
}
|
|
188
|
+
for req in batch
|
|
189
|
+
]
|
|
190
|
+
try:
|
|
191
|
+
answers = cedarpy.is_authorized_batch(cedar_requests, handle.policy_set, entities, handle.schema)
|
|
192
|
+
except ValueError as exc:
|
|
193
|
+
return _deny_all(len(batch), f"evaluation failed: {exc}", generation)
|
|
194
|
+
return [
|
|
195
|
+
Decision(
|
|
196
|
+
allow=answer.allowed,
|
|
197
|
+
reasons=tuple(handle.id_by_position.get(r, r) for r in answer.diagnostics.reasons),
|
|
198
|
+
errors=tuple(str(e) for e in answer.diagnostics.errors),
|
|
199
|
+
generation=generation,
|
|
200
|
+
)
|
|
201
|
+
for answer in answers
|
|
202
|
+
]
|
|
203
|
+
|
|
204
|
+
def validate(self, policies: Sequence[PolicyText], schema: str) -> tuple[str, ...]:
|
|
205
|
+
"""Type-check each policy against ``schema``; messages are prefixed with the stored policy id."""
|
|
206
|
+
try:
|
|
207
|
+
parsed_schema = cedarpy.Schema.from_str(schema)
|
|
208
|
+
except ValueError as exc:
|
|
209
|
+
return (f"schema: {exc}",)
|
|
210
|
+
problems: list[str] = []
|
|
211
|
+
for policy in policies:
|
|
212
|
+
try:
|
|
213
|
+
result = cedarpy.validate_policies(policy.text, parsed_schema)
|
|
214
|
+
except ValueError as exc:
|
|
215
|
+
problems.append(f"{policy.id}: {exc}")
|
|
216
|
+
continue
|
|
217
|
+
problems.extend(f"{policy.id}: {err.error}" for err in result.errors)
|
|
218
|
+
return tuple(problems)
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""``CfAccessIdentityGroups``: verified Entra group GUIDs from the Cloudflare Access identity endpoint.
|
|
2
|
+
|
|
3
|
+
GET ``<team domain>/cdn-cgi/access/get-identity`` with the ``CF_Authorization`` cookie;
|
|
4
|
+
keep only ``groups[].id`` values that are GUIDs (lower-cased, deduplicated, at most 200). Answers are
|
|
5
|
+
cached per token hash (the token itself is never stored or logged): success for
|
|
6
|
+
``min(600 s, token exp)``, failure for 30 s, at most 256 entries. Any failure is ``GroupLookup.unknown``
|
|
7
|
+
with a reason (never an exception);
|
|
8
|
+
"unknown" is distinct from "known, no groups".
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
import re
|
|
17
|
+
import threading
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
from hermes_access_client.domain.decision import GroupLookup
|
|
21
|
+
from hermes_access_client.domain.errors import ConfigError
|
|
22
|
+
from hermes_access_client.ports import Clock, IdentityFetch, IdentityFetchError
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
TEAM_DOMAIN_RE = re.compile(r"^https://[a-z0-9-]+\.cloudflareaccess\.com$")
|
|
27
|
+
IDENTITY_PATH = "/cdn-cgi/access/get-identity"
|
|
28
|
+
TIMEOUT_S = 5.0
|
|
29
|
+
MAX_BODY_BYTES = 256 * 1024
|
|
30
|
+
SUCCESS_TTL_S = 600.0
|
|
31
|
+
FAILURE_TTL_S = 30.0
|
|
32
|
+
MAX_ENTRIES = 256
|
|
33
|
+
MAX_GROUPS = 200
|
|
34
|
+
|
|
35
|
+
_JWT_RE = re.compile(r"^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$")
|
|
36
|
+
_GUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
40
|
+
class _Entry:
|
|
41
|
+
expires_at: float
|
|
42
|
+
lookup: GroupLookup
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _parse_groups(body: bytes) -> GroupLookup:
|
|
46
|
+
"""GUID group ids of an identity document, or unknown when it is not one."""
|
|
47
|
+
try:
|
|
48
|
+
doc: object = json.loads(body)
|
|
49
|
+
except ValueError:
|
|
50
|
+
return GroupLookup.unknown("identity response is not JSON")
|
|
51
|
+
if not isinstance(doc, dict):
|
|
52
|
+
return GroupLookup.unknown("identity response is not an object")
|
|
53
|
+
if "err" in doc:
|
|
54
|
+
return GroupLookup.unknown("identity response reports an error")
|
|
55
|
+
raw: object = doc.get("groups", []) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
|
|
56
|
+
if not isinstance(raw, list):
|
|
57
|
+
return GroupLookup.unknown("identity groups is not a list")
|
|
58
|
+
found: dict[str, None] = {}
|
|
59
|
+
for item in raw: # pyright: ignore[reportUnknownVariableType]
|
|
60
|
+
if not isinstance(item, dict):
|
|
61
|
+
continue
|
|
62
|
+
gid: object = item.get("id") # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
|
|
63
|
+
if isinstance(gid, str) and _GUID_RE.fullmatch(gid):
|
|
64
|
+
found[gid.lower()] = None
|
|
65
|
+
if len(found) >= MAX_GROUPS:
|
|
66
|
+
break
|
|
67
|
+
return GroupLookup.known(frozenset(found))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class CfAccessIdentityGroups:
|
|
71
|
+
"""``GroupSource`` over the Cloudflare Access identity endpoint of one team domain."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, *, team_domain: str, fetch: IdentityFetch, clock: Clock) -> None:
|
|
74
|
+
if not TEAM_DOMAIN_RE.fullmatch(team_domain):
|
|
75
|
+
raise ConfigError("team domain must be an https://<team> Cloudflare Access domain")
|
|
76
|
+
self._url = team_domain + IDENTITY_PATH
|
|
77
|
+
self._fetch = fetch
|
|
78
|
+
self._clock = clock
|
|
79
|
+
self._cache: dict[str, _Entry] = {}
|
|
80
|
+
self._lock = threading.Lock()
|
|
81
|
+
|
|
82
|
+
def groups_for(self, token: str, exp: float) -> GroupLookup:
|
|
83
|
+
"""Groups of the token's user; unknown (never an exception) on any failure."""
|
|
84
|
+
try:
|
|
85
|
+
return self._groups_for(token, exp)
|
|
86
|
+
except Exception as exc:
|
|
87
|
+
log.warning("identity lookup failed unexpectedly: %s", type(exc).__name__)
|
|
88
|
+
return GroupLookup.unknown(f"identity lookup failed: {type(exc).__name__}")
|
|
89
|
+
|
|
90
|
+
def _groups_for(self, token: str, exp: float) -> GroupLookup:
|
|
91
|
+
if not _JWT_RE.fullmatch(token):
|
|
92
|
+
return GroupLookup.unknown("token is not a JWT")
|
|
93
|
+
now = self._clock.now()
|
|
94
|
+
if exp <= now:
|
|
95
|
+
return GroupLookup.unknown("token expired")
|
|
96
|
+
key = hashlib.sha256(token.encode()).hexdigest()
|
|
97
|
+
with self._lock:
|
|
98
|
+
entry = self._cache.get(key)
|
|
99
|
+
if entry is not None and entry.expires_at > now:
|
|
100
|
+
return entry.lookup
|
|
101
|
+
lookup = self._fetch_groups(token)
|
|
102
|
+
ttl = min(SUCCESS_TTL_S if lookup.ok else FAILURE_TTL_S, exp - now)
|
|
103
|
+
self._store(key, _Entry(expires_at=now + ttl, lookup=lookup), now)
|
|
104
|
+
return lookup
|
|
105
|
+
|
|
106
|
+
def _fetch_groups(self, token: str) -> GroupLookup:
|
|
107
|
+
headers = {"Cookie": f"CF_Authorization={token}", "Accept": "application/json"}
|
|
108
|
+
try:
|
|
109
|
+
body = self._fetch.get(self._url, headers=headers, timeout_s=TIMEOUT_S, max_bytes=MAX_BODY_BYTES)
|
|
110
|
+
except IdentityFetchError as exc:
|
|
111
|
+
return GroupLookup.unknown(f"identity fetch failed: {exc}")
|
|
112
|
+
return _parse_groups(body)
|
|
113
|
+
|
|
114
|
+
def _store(self, key: str, entry: _Entry, now: float) -> None:
|
|
115
|
+
with self._lock:
|
|
116
|
+
if key not in self._cache and len(self._cache) >= MAX_ENTRIES:
|
|
117
|
+
self._cache = {k: e for k, e in self._cache.items() if e.expires_at > now}
|
|
118
|
+
if len(self._cache) >= MAX_ENTRIES:
|
|
119
|
+
soonest = min(self._cache, key=lambda k: self._cache[k].expires_at)
|
|
120
|
+
del self._cache[soonest]
|
|
121
|
+
self._cache[key] = entry
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""``FileSnapshotSource``: reads the published snapshot file, reloading only when it changed.
|
|
2
|
+
|
|
3
|
+
``current()`` does one ``os.stat`` per call and re-reads only when (mtime_ns, inode, size) changed. A corrupt,
|
|
4
|
+
newer-version or vanished file keeps the last good snapshot (``health().last_error`` says why; each distinct
|
|
5
|
+
error is logged once); a file that was never valid yields ``None`` (the client denies everything).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from hermes_access_client.domain.decision import Health
|
|
15
|
+
from hermes_access_client.domain.errors import SnapshotError
|
|
16
|
+
from hermes_access_client.domain.snapshot import LoadedSnapshot, parse_snapshot_json
|
|
17
|
+
from hermes_access_client.ports import Clock
|
|
18
|
+
|
|
19
|
+
log = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
SOURCE_KIND = "file"
|
|
22
|
+
|
|
23
|
+
_StatKey = tuple[int, int, int]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class FileSnapshotSource:
|
|
27
|
+
"""``SnapshotSource`` over a JSON file written atomically by the admin's file sink."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, path: Path, *, clock: Clock) -> None:
|
|
30
|
+
self._path = path
|
|
31
|
+
self._clock = clock
|
|
32
|
+
self._loaded: LoadedSnapshot | None = None
|
|
33
|
+
self._seen: _StatKey | None = None
|
|
34
|
+
self._last_error: str | None = None
|
|
35
|
+
self._logged: str | None = None
|
|
36
|
+
|
|
37
|
+
def current(self) -> LoadedSnapshot | None:
|
|
38
|
+
"""The newest valid snapshot (the last good one on error, None before any)."""
|
|
39
|
+
try:
|
|
40
|
+
info = os.stat(self._path) # noqa: PTH116 - one raw stat per call is the hot path
|
|
41
|
+
except OSError as exc:
|
|
42
|
+
self._seen = None
|
|
43
|
+
self._fail(f"snapshot file unreadable: {exc.strerror or type(exc).__name__}")
|
|
44
|
+
return self._loaded
|
|
45
|
+
key = (info.st_mtime_ns, info.st_ino, info.st_size)
|
|
46
|
+
if key != self._seen:
|
|
47
|
+
self._seen = key
|
|
48
|
+
self._reload()
|
|
49
|
+
return self._loaded
|
|
50
|
+
|
|
51
|
+
def health(self) -> Health:
|
|
52
|
+
"""Generation, age since publish, last reload error, ``file``."""
|
|
53
|
+
loaded = self._loaded
|
|
54
|
+
if loaded is None:
|
|
55
|
+
return Health(generation=None, age_s=None, last_error=self._last_error, source_kind=SOURCE_KIND)
|
|
56
|
+
age = max(0.0, self._clock.now() - loaded.snapshot.published_at.timestamp())
|
|
57
|
+
return Health(
|
|
58
|
+
generation=loaded.snapshot.generation,
|
|
59
|
+
age_s=age,
|
|
60
|
+
last_error=self._last_error,
|
|
61
|
+
source_kind=SOURCE_KIND,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def _reload(self) -> None:
|
|
65
|
+
try:
|
|
66
|
+
snapshot = parse_snapshot_json(self._path.read_bytes())
|
|
67
|
+
except (OSError, SnapshotError) as exc:
|
|
68
|
+
self._fail(str(exc))
|
|
69
|
+
return
|
|
70
|
+
self._loaded = LoadedSnapshot(snapshot=snapshot, loaded_at=self._clock.now(), source_kind=SOURCE_KIND)
|
|
71
|
+
self._last_error = None
|
|
72
|
+
self._logged = None
|
|
73
|
+
log.info("loaded snapshot generation %s", snapshot.generation)
|
|
74
|
+
|
|
75
|
+
def _fail(self, message: str) -> None:
|
|
76
|
+
self._last_error = message
|
|
77
|
+
if message != self._logged:
|
|
78
|
+
self._logged = message
|
|
79
|
+
log.warning("%s (keeping %s)", message, "last good snapshot" if self._loaded else "no snapshot")
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""In-memory adapters for tests and embedding: fakes of every client port.
|
|
2
|
+
|
|
3
|
+
``MemorySnapshotSource``, ``FakePolicyEngine``, ``StaticGroupSource`` and ``FakeClock``. A real source adapter
|
|
4
|
+
must pass the same contract tests as ``MemorySnapshotSource``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Collection, Sequence
|
|
10
|
+
|
|
11
|
+
from hermes_access_client.domain.decision import Decision, GroupLookup, Health, Request
|
|
12
|
+
from hermes_access_client.domain.engine import CompiledPolicies
|
|
13
|
+
from hermes_access_client.domain.snapshot import CedarEntity, LoadedSnapshot, PolicyText, Snapshot
|
|
14
|
+
from hermes_access_client.ports import Clock
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class FakeClock:
|
|
18
|
+
"""``Clock`` that only moves when told."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, start: float = 0.0) -> None:
|
|
21
|
+
self._now = start
|
|
22
|
+
|
|
23
|
+
def now(self) -> float:
|
|
24
|
+
"""The current fake time."""
|
|
25
|
+
return self._now
|
|
26
|
+
|
|
27
|
+
def advance(self, seconds: float) -> None:
|
|
28
|
+
"""Move time forward."""
|
|
29
|
+
self._now += seconds
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MemorySnapshotSource:
|
|
33
|
+
"""``SnapshotSource`` holding a snapshot set by the test (``publish``)."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, clock: Clock | None = None) -> None:
|
|
36
|
+
self._clock: Clock = clock if clock is not None else FakeClock()
|
|
37
|
+
self._loaded: LoadedSnapshot | None = None
|
|
38
|
+
self.last_error: str | None = None
|
|
39
|
+
|
|
40
|
+
def publish(self, snapshot: Snapshot) -> None:
|
|
41
|
+
"""Make ``snapshot`` current."""
|
|
42
|
+
self._loaded = LoadedSnapshot(snapshot=snapshot, loaded_at=self._clock.now(), source_kind="memory")
|
|
43
|
+
|
|
44
|
+
def current(self) -> LoadedSnapshot | None:
|
|
45
|
+
"""The last published snapshot."""
|
|
46
|
+
return self._loaded
|
|
47
|
+
|
|
48
|
+
def health(self) -> Health:
|
|
49
|
+
"""Generation, age since publish, ``memory``."""
|
|
50
|
+
loaded = self._loaded
|
|
51
|
+
if loaded is None:
|
|
52
|
+
return Health(generation=None, age_s=None, last_error=self.last_error, source_kind="memory")
|
|
53
|
+
age = max(0.0, self._clock.now() - loaded.snapshot.published_at.timestamp())
|
|
54
|
+
return Health(
|
|
55
|
+
generation=loaded.snapshot.generation,
|
|
56
|
+
age_s=age,
|
|
57
|
+
last_error=self.last_error,
|
|
58
|
+
source_kind="memory",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class FakePolicyEngine:
|
|
63
|
+
"""``PolicyEngine`` allowing exactly the (principal, action name, resource id) triples it was given.
|
|
64
|
+
|
|
65
|
+
Counts ``load`` and ``decide`` calls so tests can prove per-generation compilation and cache hits.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __init__(self, allow: Collection[tuple[str, str, str]] = ()) -> None:
|
|
69
|
+
self.allow = set(allow)
|
|
70
|
+
self.load_calls = 0
|
|
71
|
+
self.decide_calls = 0
|
|
72
|
+
|
|
73
|
+
def load(
|
|
74
|
+
self,
|
|
75
|
+
policies: Sequence[PolicyText],
|
|
76
|
+
schema: str,
|
|
77
|
+
entities: Sequence[CedarEntity],
|
|
78
|
+
*,
|
|
79
|
+
generation: int = 0,
|
|
80
|
+
) -> CompiledPolicies:
|
|
81
|
+
"""Record the call; the handle is the generation."""
|
|
82
|
+
del schema, entities
|
|
83
|
+
self.load_calls += 1
|
|
84
|
+
return CompiledPolicies(
|
|
85
|
+
generation=generation, policy_ids=tuple(p.id for p in policies), handle=generation
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def decide(self, compiled: CompiledPolicies, requests: Sequence[Request]) -> list[Decision]:
|
|
89
|
+
"""Allow the configured triples, deny the rest."""
|
|
90
|
+
self.decide_calls += 1
|
|
91
|
+
return [
|
|
92
|
+
Decision(
|
|
93
|
+
allow=(r.principal, r.action.name, r.resource.id) in self.allow,
|
|
94
|
+
generation=compiled.generation,
|
|
95
|
+
)
|
|
96
|
+
for r in requests
|
|
97
|
+
]
|
|
98
|
+
|
|
99
|
+
def validate(self, policies: Sequence[PolicyText], schema: str) -> tuple[str, ...]:
|
|
100
|
+
"""Every policy is valid."""
|
|
101
|
+
del policies, schema
|
|
102
|
+
return ()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class StaticGroupSource:
|
|
106
|
+
"""``GroupSource`` answering from a fixed token -> groups map."""
|
|
107
|
+
|
|
108
|
+
def __init__(self, groups_by_token: dict[str, frozenset[str]]) -> None:
|
|
109
|
+
self._groups_by_token = groups_by_token
|
|
110
|
+
|
|
111
|
+
def groups_for(self, token: str, exp: float) -> GroupLookup:
|
|
112
|
+
"""Known groups for a mapped token, unknown otherwise."""
|
|
113
|
+
del exp
|
|
114
|
+
groups = self._groups_by_token.get(token)
|
|
115
|
+
if groups is None:
|
|
116
|
+
return GroupLookup.unknown("unknown token")
|
|
117
|
+
return GroupLookup.known(groups)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Writes the generated JSON Schemas to a directory (``uv run python -m
|
|
2
|
+
hermes_access_client.adapters.schema_files schemas``)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from hermes_access_client.domain.json_schema import DOCUMENT_MODELS, render_json_schema
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def write_json_schemas(directory: Path) -> tuple[Path, ...]:
|
|
13
|
+
"""Write every document schema into ``directory``; returns the paths written."""
|
|
14
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
15
|
+
written: list[Path] = []
|
|
16
|
+
for name in DOCUMENT_MODELS:
|
|
17
|
+
target = directory / name
|
|
18
|
+
target.write_text(render_json_schema(name), encoding="utf-8")
|
|
19
|
+
written.append(target)
|
|
20
|
+
return tuple(written)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
if __name__ == "__main__": # pragma: no cover - maintainer entry point
|
|
24
|
+
write_json_schemas(Path(sys.argv[1] if len(sys.argv) > 1 else "schemas"))
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""``UrllibIdentityFetch``: the real ``IdentityFetch`` (stdlib ``urllib``; no redirects, bounded body)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.request
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
|
|
9
|
+
from hermes_access_client.ports import IdentityFetchError
|
|
10
|
+
|
|
11
|
+
_OK = 200
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
15
|
+
def redirect_request(self, *_args: object, **_kwargs: object) -> None: # pyright: ignore[reportIncompatibleMethodOverride]
|
|
16
|
+
return None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class UrllibIdentityFetch:
|
|
20
|
+
"""One GET with a hard timeout and body cap; redirects and non-200 answers are errors."""
|
|
21
|
+
|
|
22
|
+
def __init__(self) -> None:
|
|
23
|
+
self._opener = urllib.request.build_opener(_NoRedirect)
|
|
24
|
+
|
|
25
|
+
def get(self, url: str, *, headers: Mapping[str, str], timeout_s: float, max_bytes: int) -> bytes:
|
|
26
|
+
"""The body, or ``IdentityFetchError`` (the message never carries request headers)."""
|
|
27
|
+
request = urllib.request.Request(url, headers=dict(headers), method="GET")
|
|
28
|
+
try:
|
|
29
|
+
with self._opener.open(request, timeout=timeout_s) as response:
|
|
30
|
+
status = int(response.status)
|
|
31
|
+
body: bytes = response.read(max_bytes + 1)
|
|
32
|
+
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
33
|
+
raise IdentityFetchError(f"request failed: {type(exc).__name__}") from exc
|
|
34
|
+
if status != _OK:
|
|
35
|
+
raise IdentityFetchError(f"unexpected status {status}")
|
|
36
|
+
if len(body) > max_bytes:
|
|
37
|
+
raise IdentityFetchError("response too large")
|
|
38
|
+
return body
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""``YamlConfigSource``: reads the access-control YAML file into ``AccessSettings`` with paths resolved."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
|
|
10
|
+
from hermes_access_client.domain.errors import ConfigError
|
|
11
|
+
from hermes_access_client.domain.settings import AccessSettings, parse_settings
|
|
12
|
+
|
|
13
|
+
log = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class YamlConfigSource:
|
|
17
|
+
"""``ConfigSource`` for YAML files. ``home`` is what ``~`` means (``HERMES_REAL_HOME`` or the pwd
|
|
18
|
+
home)."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, *, home: Path) -> None:
|
|
21
|
+
self._home = home
|
|
22
|
+
|
|
23
|
+
def load(self, path: Path) -> AccessSettings:
|
|
24
|
+
"""Parse ``path``; relative paths resolve against its directory. Raises ``ConfigError``."""
|
|
25
|
+
try:
|
|
26
|
+
raw: object = yaml.safe_load(path.read_text(encoding="utf-8"))
|
|
27
|
+
except OSError as exc:
|
|
28
|
+
raise ConfigError(f"cannot read config {path}: {exc.strerror}") from exc
|
|
29
|
+
except yaml.YAMLError as exc:
|
|
30
|
+
raise ConfigError(f"config {path} is not valid YAML: {exc}") from exc
|
|
31
|
+
settings = parse_settings(raw).resolved(base_dir=path.parent, home=self._home)
|
|
32
|
+
log.debug("loaded settings from %s", path)
|
|
33
|
+
return settings
|