AccessGate 0.2.0a1__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.
@@ -0,0 +1,113 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/Tunet-xyz/access_gate/schema/abac-policy-v1.json",
4
+ "title": "AccessGate ABAC Policy v1",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": [
8
+ "schema_version",
9
+ "type",
10
+ "name",
11
+ "actions",
12
+ "match_effect",
13
+ "on_no_match",
14
+ "on_indeterminate",
15
+ "condition"
16
+ ],
17
+ "properties": {
18
+ "schema_version": {"const": "access_gate.policy.v1"},
19
+ "type": {"const": "attribute_policy"},
20
+ "name": {"type": "string", "minLength": 1},
21
+ "actions": {
22
+ "oneOf": [
23
+ {"type": "null"},
24
+ {
25
+ "type": "array",
26
+ "minItems": 1,
27
+ "items": {"type": "string", "minLength": 1},
28
+ "uniqueItems": true,
29
+ "maxItems": 4096
30
+ }
31
+ ]
32
+ },
33
+ "match_effect": {"enum": ["allow", "deny"]},
34
+ "on_no_match": {"enum": ["deny", "abstain"]},
35
+ "on_indeterminate": {"enum": ["deny", "abstain"]},
36
+ "condition": {"$ref": "#/$defs/condition"}
37
+ },
38
+ "$defs": {
39
+ "attributeReference": {
40
+ "type": "object",
41
+ "additionalProperties": false,
42
+ "required": ["source", "path"],
43
+ "properties": {
44
+ "source": {"enum": ["subject", "resource", "action", "context"]},
45
+ "path": {
46
+ "type": "string",
47
+ "minLength": 1,
48
+ "pattern": "^[^.]+(?:\\.[^.]+)*$"
49
+ }
50
+ }
51
+ },
52
+ "literal": {
53
+ "type": "object",
54
+ "additionalProperties": false,
55
+ "required": ["value"],
56
+ "properties": {"value": {}}
57
+ },
58
+ "operand": {
59
+ "oneOf": [
60
+ {"$ref": "#/$defs/attributeReference"},
61
+ {"$ref": "#/$defs/literal"}
62
+ ]
63
+ },
64
+ "comparison": {
65
+ "type": "object",
66
+ "additionalProperties": false,
67
+ "required": ["type", "operator", "left"],
68
+ "properties": {
69
+ "type": {"const": "comparison"},
70
+ "operator": {"type": "string", "pattern": "^[a-z][a-z0-9_]*$"},
71
+ "left": {"$ref": "#/$defs/operand"},
72
+ "right": {"$ref": "#/$defs/operand"}
73
+ },
74
+ "allOf": [
75
+ {
76
+ "if": {"properties": {"operator": {"enum": ["exists", "not_exists"]}}},
77
+ "then": {"not": {"required": ["right"]}},
78
+ "else": {"required": ["right"]}
79
+ }
80
+ ]
81
+ },
82
+ "conditionList": {
83
+ "type": "object",
84
+ "additionalProperties": false,
85
+ "required": ["type", "conditions"],
86
+ "properties": {
87
+ "type": {"enum": ["all_of", "any_of"]},
88
+ "conditions": {
89
+ "type": "array",
90
+ "minItems": 1,
91
+ "maxItems": 4096,
92
+ "items": {"$ref": "#/$defs/condition"}
93
+ }
94
+ }
95
+ },
96
+ "negation": {
97
+ "type": "object",
98
+ "additionalProperties": false,
99
+ "required": ["type", "condition"],
100
+ "properties": {
101
+ "type": {"const": "not"},
102
+ "condition": {"$ref": "#/$defs/condition"}
103
+ }
104
+ },
105
+ "condition": {
106
+ "oneOf": [
107
+ {"$ref": "#/$defs/comparison"},
108
+ {"$ref": "#/$defs/conditionList"},
109
+ {"$ref": "#/$defs/negation"}
110
+ ]
111
+ }
112
+ }
113
+ }
@@ -0,0 +1,28 @@
1
+ """Built-in policy decision strategies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ from .types import AuthorizationRequest, Decision, Effect
8
+
9
+
10
+ class DenyOverrides:
11
+ """Deny on any explicit denial; otherwise allow on any explicit allowance."""
12
+
13
+ def combine(
14
+ self,
15
+ request: AuthorizationRequest,
16
+ decisions: Sequence[Decision],
17
+ ) -> Decision:
18
+ del request
19
+ for decision in decisions:
20
+ if decision.effect is Effect.DENY:
21
+ return decision
22
+ for decision in decisions:
23
+ if decision.effect is Effect.ALLOW:
24
+ return decision
25
+ return Decision.deny(
26
+ "No policy allowed the request.",
27
+ policy="access_gate.default_deny",
28
+ )
access_gate/types.py ADDED
@@ -0,0 +1,315 @@
1
+ """Framework-neutral authorization value objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Mapping
6
+ from dataclasses import dataclass, field
7
+ from enum import Enum
8
+ from typing import cast
9
+
10
+ _MAX_VALUE_DEPTH = 64
11
+ _MAX_VALUE_ITEMS = 100_000
12
+ _MAX_SUBJECT_ROLES = 10_000
13
+
14
+
15
+ class _FrozenMapping(Mapping[object, object]):
16
+ """An internally owned immutable mapping that can be safely reused."""
17
+
18
+ __slots__ = ("__values",)
19
+
20
+ def __init__(self, values: dict[object, object]) -> None:
21
+ self.__values = values
22
+
23
+ def __getitem__(self, key: object) -> object:
24
+ return self.__values[key]
25
+
26
+ def __iter__(self) -> Iterator[object]:
27
+ return iter(self.__values)
28
+
29
+ def __len__(self) -> int:
30
+ return len(self.__values)
31
+
32
+ def __repr__(self) -> str:
33
+ return f"_FrozenMapping({self.__values!r})"
34
+
35
+
36
+ def _freeze_value(
37
+ value: object,
38
+ *,
39
+ field_name: str,
40
+ depth: int = 0,
41
+ seen: set[int] | None = None,
42
+ item_count: list[int] | None = None,
43
+ ) -> object:
44
+ """Create a bounded immutable snapshot of authorization input data."""
45
+
46
+ if depth > _MAX_VALUE_DEPTH:
47
+ raise ValueError(f"{field_name} exceeds the maximum nesting depth.")
48
+ if seen is None:
49
+ seen = set()
50
+ if item_count is None:
51
+ item_count = [0]
52
+
53
+ if isinstance(value, _FrozenMapping):
54
+ return value
55
+
56
+ if isinstance(value, Mapping):
57
+ identity = id(value)
58
+ if identity in seen:
59
+ raise ValueError(f"{field_name} must not contain reference cycles.")
60
+ seen.add(identity)
61
+ try:
62
+ frozen: dict[object, object] = {}
63
+ for key, child in value.items():
64
+ item_count[0] += 1
65
+ if item_count[0] > _MAX_VALUE_ITEMS:
66
+ raise ValueError(f"{field_name} contains too many values.")
67
+ frozen[key] = _freeze_value(
68
+ child,
69
+ field_name=field_name,
70
+ depth=depth + 1,
71
+ seen=seen,
72
+ item_count=item_count,
73
+ )
74
+ return _FrozenMapping(frozen)
75
+ finally:
76
+ seen.remove(identity)
77
+
78
+ if isinstance(value, list | tuple):
79
+ identity = id(value)
80
+ if identity in seen:
81
+ raise ValueError(f"{field_name} must not contain reference cycles.")
82
+ seen.add(identity)
83
+ try:
84
+ frozen_items: list[object] = []
85
+ for child in value:
86
+ item_count[0] += 1
87
+ if item_count[0] > _MAX_VALUE_ITEMS:
88
+ raise ValueError(f"{field_name} contains too many values.")
89
+ frozen_items.append(
90
+ _freeze_value(
91
+ child,
92
+ field_name=field_name,
93
+ depth=depth + 1,
94
+ seen=seen,
95
+ item_count=item_count,
96
+ )
97
+ )
98
+ return tuple(frozen_items)
99
+ finally:
100
+ seen.remove(identity)
101
+
102
+ if isinstance(value, set | frozenset):
103
+ identity = id(value)
104
+ if identity in seen:
105
+ raise ValueError(f"{field_name} must not contain reference cycles.")
106
+ seen.add(identity)
107
+ try:
108
+ frozen_items = []
109
+ for child in value:
110
+ item_count[0] += 1
111
+ if item_count[0] > _MAX_VALUE_ITEMS:
112
+ raise ValueError(f"{field_name} contains too many values.")
113
+ frozen_items.append(
114
+ _freeze_value(
115
+ child,
116
+ field_name=field_name,
117
+ depth=depth + 1,
118
+ seen=seen,
119
+ item_count=item_count,
120
+ )
121
+ )
122
+ return frozenset(frozen_items)
123
+ finally:
124
+ seen.remove(identity)
125
+
126
+ return value
127
+
128
+
129
+ def _freeze_mapping(value: Mapping[str, object], *, field_name: str) -> Mapping[str, object]:
130
+ if not isinstance(value, Mapping):
131
+ raise TypeError(f"{field_name} must be a mapping.")
132
+ if not all(isinstance(key, str) for key in value):
133
+ raise TypeError(f"{field_name} keys must be strings.")
134
+ frozen = _freeze_value(value, field_name=field_name)
135
+ if not isinstance(frozen, Mapping): # pragma: no cover - guarded above
136
+ raise TypeError(f"{field_name} could not be snapshotted as a mapping.")
137
+ return cast(Mapping[str, object], frozen)
138
+
139
+
140
+ def _thaw_value(value: object) -> object:
141
+ """Convert immutable snapshots back into JSON-friendly containers."""
142
+
143
+ if isinstance(value, Mapping):
144
+ return {key: _thaw_value(child) for key, child in value.items()}
145
+ if isinstance(value, tuple | list):
146
+ return [_thaw_value(child) for child in value]
147
+ if isinstance(value, frozenset | set):
148
+ return [_thaw_value(child) for child in value]
149
+ return value
150
+
151
+
152
+ class Effect(str, Enum):
153
+ """The outcome of an authorization decision."""
154
+
155
+ ALLOW = "allow"
156
+ DENY = "deny"
157
+
158
+
159
+ @dataclass(frozen=True, slots=True)
160
+ class Subject:
161
+ """The actor attempting an action.
162
+
163
+ Applications decide which claims become roles and attributes. AccessGate
164
+ deliberately does not depend on a particular user, token, or ORM model.
165
+ """
166
+
167
+ identifier: str
168
+ authenticated: bool = True
169
+ roles: frozenset[str] = field(default_factory=frozenset)
170
+ attributes: Mapping[str, object] = field(default_factory=dict)
171
+
172
+ def __post_init__(self) -> None:
173
+ if not isinstance(self.identifier, str):
174
+ raise TypeError("subject.identifier must be a string.")
175
+ if not isinstance(self.authenticated, bool):
176
+ raise TypeError("subject.authenticated must be a boolean.")
177
+ if self.authenticated and not self.identifier:
178
+ raise ValueError("an authenticated subject must have a non-empty identifier.")
179
+ if isinstance(self.roles, str):
180
+ raise TypeError("subject.roles must be a collection of role names, not a string.")
181
+ roles = frozenset(self.roles)
182
+ if len(roles) > _MAX_SUBJECT_ROLES:
183
+ raise ValueError("subject.roles exceeds the maximum item count.")
184
+ if not all(isinstance(role, str) and role for role in roles):
185
+ raise TypeError("subject.roles must contain only non-empty strings.")
186
+ object.__setattr__(self, "roles", roles)
187
+ object.__setattr__(
188
+ self,
189
+ "attributes",
190
+ _freeze_mapping(self.attributes, field_name="subject.attributes"),
191
+ )
192
+
193
+ def to_dict(self) -> dict[str, object]:
194
+ return {
195
+ "identifier": self.identifier,
196
+ "authenticated": self.authenticated,
197
+ "roles": sorted(self.roles),
198
+ "attributes": _thaw_value(self.attributes),
199
+ }
200
+
201
+
202
+ @dataclass(frozen=True, slots=True)
203
+ class Resource:
204
+ """A protected object or collection."""
205
+
206
+ kind: str
207
+ identifier: str | None = None
208
+ attributes: Mapping[str, object] = field(default_factory=dict)
209
+
210
+ def __post_init__(self) -> None:
211
+ if not isinstance(self.kind, str) or not self.kind:
212
+ raise TypeError("resource.kind must be a non-empty string.")
213
+ if self.identifier is not None and not isinstance(self.identifier, str):
214
+ raise TypeError("resource.identifier must be a string or None.")
215
+ object.__setattr__(
216
+ self,
217
+ "attributes",
218
+ _freeze_mapping(self.attributes, field_name="resource.attributes"),
219
+ )
220
+
221
+ def to_dict(self) -> dict[str, object]:
222
+ return {
223
+ "kind": self.kind,
224
+ "identifier": self.identifier,
225
+ "attributes": _thaw_value(self.attributes),
226
+ }
227
+
228
+
229
+ @dataclass(frozen=True, slots=True)
230
+ class AuthorizationRequest:
231
+ """The complete input to policy evaluation."""
232
+
233
+ subject: Subject
234
+ action: str
235
+ resource: Resource | None = None
236
+ context: Mapping[str, object] = field(default_factory=dict)
237
+ action_attributes: Mapping[str, object] = field(default_factory=dict)
238
+
239
+ def __post_init__(self) -> None:
240
+ if not isinstance(self.subject, Subject):
241
+ raise TypeError("authorization subject must be a Subject.")
242
+ if self.resource is not None and not isinstance(self.resource, Resource):
243
+ raise TypeError("authorization resource must be a Resource or None.")
244
+ if not isinstance(self.action, str) or not self.action:
245
+ raise TypeError("authorization action must be a non-empty string.")
246
+ object.__setattr__(self, "context", _freeze_mapping(self.context, field_name="context"))
247
+ object.__setattr__(
248
+ self,
249
+ "action_attributes",
250
+ _freeze_mapping(self.action_attributes, field_name="action_attributes"),
251
+ )
252
+
253
+ def to_dict(self) -> dict[str, object]:
254
+ return {
255
+ "subject": self.subject.to_dict(),
256
+ "action": self.action,
257
+ "resource": None if self.resource is None else self.resource.to_dict(),
258
+ "context": _thaw_value(self.context),
259
+ "action_attributes": _thaw_value(self.action_attributes),
260
+ }
261
+
262
+
263
+ @dataclass(frozen=True, slots=True)
264
+ class Decision:
265
+ """A final or intermediate policy decision."""
266
+
267
+ effect: Effect
268
+ reason: str
269
+ policy: str | None = None
270
+ metadata: Mapping[str, object] = field(default_factory=dict)
271
+
272
+ def __post_init__(self) -> None:
273
+ if not isinstance(self.effect, Effect):
274
+ raise TypeError("decision.effect must be an Effect value.")
275
+ if not isinstance(self.reason, str) or not self.reason:
276
+ raise TypeError("decision.reason must be a non-empty string.")
277
+ if self.policy is not None and not isinstance(self.policy, str):
278
+ raise TypeError("decision.policy must be a string or None.")
279
+ object.__setattr__(
280
+ self,
281
+ "metadata",
282
+ _freeze_mapping(self.metadata, field_name="decision.metadata"),
283
+ )
284
+
285
+ def to_dict(self) -> dict[str, object]:
286
+ return {
287
+ "effect": self.effect.value,
288
+ "reason": self.reason,
289
+ "policy": self.policy,
290
+ "metadata": _thaw_value(self.metadata),
291
+ }
292
+
293
+ @property
294
+ def allowed(self) -> bool:
295
+ return self.effect is Effect.ALLOW
296
+
297
+ @classmethod
298
+ def allow(
299
+ cls,
300
+ reason: str,
301
+ *,
302
+ policy: str | None = None,
303
+ metadata: Mapping[str, object] | None = None,
304
+ ) -> Decision:
305
+ return cls(Effect.ALLOW, reason, policy, metadata or {})
306
+
307
+ @classmethod
308
+ def deny(
309
+ cls,
310
+ reason: str,
311
+ *,
312
+ policy: str | None = None,
313
+ metadata: Mapping[str, object] | None = None,
314
+ ) -> Decision:
315
+ return cls(Effect.DENY, reason, policy, metadata or {})