hermes-access-client 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. hermes_access_client-0.1.0/.gitignore +16 -0
  2. hermes_access_client-0.1.0/PKG-INFO +30 -0
  3. hermes_access_client-0.1.0/README.md +13 -0
  4. hermes_access_client-0.1.0/pyproject.toml +33 -0
  5. hermes_access_client-0.1.0/src/hermes_access_client/__init__.py +29 -0
  6. hermes_access_client-0.1.0/src/hermes_access_client/adapters/__init__.py +3 -0
  7. hermes_access_client-0.1.0/src/hermes_access_client/adapters/cedar_engine.py +218 -0
  8. hermes_access_client-0.1.0/src/hermes_access_client/adapters/cf_identity_groups.py +121 -0
  9. hermes_access_client-0.1.0/src/hermes_access_client/adapters/file_source.py +79 -0
  10. hermes_access_client-0.1.0/src/hermes_access_client/adapters/memory.py +117 -0
  11. hermes_access_client-0.1.0/src/hermes_access_client/adapters/schema_files.py +24 -0
  12. hermes_access_client-0.1.0/src/hermes_access_client/adapters/system_clock.py +13 -0
  13. hermes_access_client-0.1.0/src/hermes_access_client/adapters/urllib_fetch.py +38 -0
  14. hermes_access_client-0.1.0/src/hermes_access_client/adapters/yaml_config.py +33 -0
  15. hermes_access_client-0.1.0/src/hermes_access_client/app.py +68 -0
  16. hermes_access_client-0.1.0/src/hermes_access_client/domain/__init__.py +58 -0
  17. hermes_access_client-0.1.0/src/hermes_access_client/domain/decision.py +86 -0
  18. hermes_access_client-0.1.0/src/hermes_access_client/domain/engine.py +18 -0
  19. hermes_access_client-0.1.0/src/hermes_access_client/domain/errors.py +35 -0
  20. hermes_access_client-0.1.0/src/hermes_access_client/domain/hermes_schema.py +47 -0
  21. hermes_access_client-0.1.0/src/hermes_access_client/domain/ids.py +36 -0
  22. hermes_access_client-0.1.0/src/hermes_access_client/domain/json_schema.py +28 -0
  23. hermes_access_client-0.1.0/src/hermes_access_client/domain/manifest.py +48 -0
  24. hermes_access_client-0.1.0/src/hermes_access_client/domain/refs.py +104 -0
  25. hermes_access_client-0.1.0/src/hermes_access_client/domain/resolve.py +68 -0
  26. hermes_access_client-0.1.0/src/hermes_access_client/domain/settings.py +120 -0
  27. hermes_access_client-0.1.0/src/hermes_access_client/domain/snapshot.py +100 -0
  28. hermes_access_client-0.1.0/src/hermes_access_client/domain/versioned.py +46 -0
  29. hermes_access_client-0.1.0/src/hermes_access_client/ports.py +92 -0
  30. hermes_access_client-0.1.0/src/hermes_access_client/py.typed +0 -0
  31. hermes_access_client-0.1.0/src/hermes_access_client/services/__init__.py +3 -0
  32. hermes_access_client-0.1.0/src/hermes_access_client/services/access_client.py +266 -0
  33. hermes_access_client-0.1.0/src/hermes_access_client/services/decision_cache.py +66 -0
  34. hermes_access_client-0.1.0/src/hermes_access_client/services/roles.py +20 -0
  35. hermes_access_client-0.1.0/tests/conftest.py +109 -0
  36. hermes_access_client-0.1.0/tests/perf/test_perf_targets.py +198 -0
  37. hermes_access_client-0.1.0/tests/test_access_client.py +203 -0
  38. hermes_access_client-0.1.0/tests/test_cedar_engine.py +230 -0
  39. hermes_access_client-0.1.0/tests/test_cf_identity_groups.py +214 -0
  40. hermes_access_client-0.1.0/tests/test_client_contract.py +70 -0
  41. hermes_access_client-0.1.0/tests/test_config_and_app.py +90 -0
  42. hermes_access_client-0.1.0/tests/test_file_source.py +121 -0
  43. hermes_access_client-0.1.0/tests/test_hermes_schema.py +86 -0
  44. hermes_access_client-0.1.0/tests/test_json_schemas.py +30 -0
  45. hermes_access_client-0.1.0/tests/test_lru_and_roles.py +34 -0
  46. hermes_access_client-0.1.0/tests/test_models.py +148 -0
  47. hermes_access_client-0.1.0/tests/test_refs.py +49 -0
  48. hermes_access_client-0.1.0/tests/test_resolve.py +68 -0
  49. hermes_access_client-0.1.0/tests/test_smoke_hermes_access_client.py +6 -0
  50. hermes_access_client-0.1.0/tests/test_urllib_fetch.py +68 -0
@@ -0,0 +1,16 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ # real config, stores and snapshots never belong in the repo (examples/ holds the example config)
10
+ hermes-access-control.yaml
11
+ *.db
12
+ *.db-wal
13
+ *.db-shm
14
+ *.snapshot.json
15
+ data/
16
+ .DS_Store
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.5
2
+ Name: hermes-access-client
3
+ Version: 0.1.0
4
+ Summary: Read-only client for hermes-access: fast in-process RBAC/ABAC decisions for Hermes apps.
5
+ Project-URL: Homepage, https://github.com/ejlevin1/hermes-access
6
+ Project-URL: Issues, https://github.com/ejlevin1/hermes-access/issues
7
+ License-Expression: MIT
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.11
12
+ Requires-Dist: cedarpy==4.12.2
13
+ Requires-Dist: pydantic<3,>=2.9
14
+ Requires-Dist: pyyaml<7,>=6
15
+ Requires-Dist: typing-extensions>=4.12
16
+ Description-Content-Type: text/markdown
17
+
18
+ # hermes-access-client
19
+
20
+ Read-only client for hermes-access: fast in-process RBAC/ABAC decisions (Cedar) for Hermes apps over a published
21
+ snapshot. It also owns the models, the bundled `Hermes::` schema and the JSON Schemas.
22
+
23
+ ```python
24
+ from hermes_access_client import from_config
25
+
26
+ access = from_config(app="example-app")
27
+ ```
28
+
29
+ Documentation: see the [root README](../../README.md), [architecture](../../docs/ARCHITECTURE.md) and
30
+ [snapshot format](../../docs/snapshot-v1.md). Part of hermes-access. License: MIT.
@@ -0,0 +1,13 @@
1
+ # hermes-access-client
2
+
3
+ Read-only client for hermes-access: fast in-process RBAC/ABAC decisions (Cedar) for Hermes apps over a published
4
+ snapshot. It also owns the models, the bundled `Hermes::` schema and the JSON Schemas.
5
+
6
+ ```python
7
+ from hermes_access_client import from_config
8
+
9
+ access = from_config(app="example-app")
10
+ ```
11
+
12
+ Documentation: see the [root README](../../README.md), [architecture](../../docs/ARCHITECTURE.md) and
13
+ [snapshot format](../../docs/snapshot-v1.md). Part of hermes-access. License: MIT.
@@ -0,0 +1,33 @@
1
+ [project]
2
+ name = "hermes-access-client"
3
+ dynamic = ["version"]
4
+ description = "Read-only client for hermes-access: fast in-process RBAC/ABAC decisions for Hermes apps."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.11"
8
+ dependencies = ["pydantic>=2.9,<3", "pyyaml>=6,<7", "cedarpy==4.12.2", "typing-extensions>=4.12"]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3 :: Only",
11
+ "License :: OSI Approved :: MIT License",
12
+ "Typing :: Typed",
13
+ ]
14
+
15
+ [project.urls]
16
+ Homepage = "https://github.com/ejlevin1/hermes-access"
17
+ Issues = "https://github.com/ejlevin1/hermes-access/issues"
18
+
19
+ [build-system]
20
+ requires = ["hatchling>=1.26", "hatch-vcs>=0.4"]
21
+ build-backend = "hatchling.build"
22
+
23
+ [tool.hatch.version]
24
+ source = "vcs"
25
+ tag-pattern = "^v(?P<version>.+)$"
26
+
27
+ [tool.hatch.version.raw-options]
28
+ root = "../.."
29
+ git_describe_command = ["git", "describe", "--dirty", "--tags", "--long", "--match", "v*"]
30
+ fallback_version = "0.0.0+unknown"
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/hermes_access_client"]
@@ -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,3 @@
1
+ """Client adapters: all I/O (files, Cedar, identity, clock) behind the ports in ``ports.py``."""
2
+
3
+ __all__: list[str] = []
@@ -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)