zanzipy 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.
zanzipy/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ from .models.tuple import InvalidTupleFormatError, RelationTuple
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ __all__ = [
6
+ "InvalidTupleFormatError",
7
+ "RelationTuple",
8
+ ]
@@ -0,0 +1,27 @@
1
+ from .errors import (
2
+ EntityIdValidationError,
3
+ IdentifierValidationError,
4
+ InvalidTupleFormatError,
5
+ SubjectValidationError,
6
+ )
7
+ from .id import EntityId
8
+ from .identifier import Identifier
9
+ from .namespace import Namespace
10
+ from .object import Obj
11
+ from .relation import Relation
12
+ from .subject import Subject
13
+ from .tuple import RelationTuple
14
+
15
+ __all__ = [
16
+ "EntityId",
17
+ "EntityIdValidationError",
18
+ "Identifier",
19
+ "IdentifierValidationError",
20
+ "InvalidTupleFormatError",
21
+ "Namespace",
22
+ "Obj",
23
+ "Relation",
24
+ "RelationTuple",
25
+ "Subject",
26
+ "SubjectValidationError",
27
+ ]
@@ -0,0 +1,135 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Self
5
+
6
+ from .filter import TupleFilter
7
+ from .id import EntityId
8
+ from .namespace import Namespace
9
+ from .object import Obj
10
+ from .relation import Relation
11
+ from .subject import Subject
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class CheckRequest:
16
+ """Request to check if subject has relation to object"""
17
+
18
+ object_type: str
19
+ object_id: str
20
+ relation: str
21
+ subject_type: str
22
+ subject_id: str
23
+
24
+ def __post_init__(self) -> None:
25
+ # Validate components using existing value objects
26
+ Namespace(self.object_type)
27
+ EntityId(self.object_id)
28
+ Relation(self.relation)
29
+ Namespace(self.subject_type)
30
+ EntityId(self.subject_id)
31
+
32
+ @property
33
+ def object(self) -> str:
34
+ return f"{self.object_type}:{self.object_id}"
35
+
36
+ @property
37
+ def subject(self) -> str:
38
+ return f"{self.subject_type}:{self.subject_id}"
39
+
40
+ def __str__(self) -> str:
41
+ return f"{self.object}#{self.relation}@{self.subject}"
42
+
43
+ def to_dict(self) -> dict:
44
+ return {
45
+ "object_type": self.object_type,
46
+ "object_id": self.object_id,
47
+ "relation": self.relation,
48
+ "subject_type": self.subject_type,
49
+ "subject_id": self.subject_id,
50
+ }
51
+
52
+ @classmethod
53
+ def from_dict(cls, data: dict) -> Self:
54
+ return cls(
55
+ object_type=data["object_type"],
56
+ object_id=data["object_id"],
57
+ relation=data["relation"],
58
+ subject_type=data["subject_type"],
59
+ subject_id=data["subject_id"],
60
+ )
61
+
62
+ @classmethod
63
+ def from_parts(cls, obj: Obj, relation: Relation, subject: Subject) -> Self:
64
+ """Construct from domain objects.
65
+
66
+ Requires a direct subject (no subject relation on the subject set).
67
+ """
68
+ if subject.relation is not None:
69
+ raise ValueError(
70
+ "CheckRequest requires a direct subject (no subject relation)"
71
+ )
72
+ return cls(
73
+ object_type=str(obj.namespace),
74
+ object_id=str(obj.id),
75
+ relation=str(relation),
76
+ subject_type=str(subject.namespace),
77
+ subject_id=str(subject.id),
78
+ )
79
+
80
+ @classmethod
81
+ def from_strings(cls, object_str: str, relation: str, subject_str: str) -> Self:
82
+ """Construct from 'ns:id', relation, and 'ns:id' strings.
83
+
84
+ The subject must be direct (no '#relation' allowed).
85
+ """
86
+ if ":" not in object_str:
87
+ raise ValueError("object must be in 'namespace:id' form")
88
+ obj_ns, obj_id = object_str.split(":", 1)
89
+ # Validate using value objects
90
+ obj_namespace = Namespace(obj_ns)
91
+ obj_entity_id = EntityId(obj_id)
92
+
93
+ # Reuse Subject.parse to leverage validation and detect subject sets
94
+ subject = Subject.parse(subject_str)
95
+ if subject.relation is not None:
96
+ raise ValueError(
97
+ "CheckRequest requires a direct subject (no subject relation)"
98
+ )
99
+
100
+ return cls(
101
+ object_type=str(obj_namespace),
102
+ object_id=str(obj_entity_id),
103
+ relation=str(Relation(relation)),
104
+ subject_type=str(subject.namespace),
105
+ subject_id=str(subject.id),
106
+ )
107
+
108
+ def to_object(self) -> Obj:
109
+ return Obj(Namespace(self.object_type), EntityId(self.object_id))
110
+
111
+ def to_relation(self) -> Relation:
112
+ return Relation(self.relation)
113
+
114
+ def to_subject(self) -> Subject:
115
+ return Subject(Namespace(self.subject_type), EntityId(self.subject_id))
116
+
117
+ def to_filter(self) -> TupleFilter:
118
+ """Convert to a TupleFilter for backing tuple lookups."""
119
+ return TupleFilter(
120
+ object_type=self.object_type,
121
+ object_id=self.object_id,
122
+ relation=self.relation,
123
+ subject_type=self.subject_type,
124
+ subject_id=self.subject_id,
125
+ )
126
+
127
+
128
+ @dataclass(frozen=True, slots=True)
129
+ class CheckResponse:
130
+ """Response with permission decision and optional debug info"""
131
+
132
+ allowed: bool
133
+ debug_trace: list[str] | None = None
134
+ depth_reached: int = 0
135
+ tuples_examined: int = 0
@@ -0,0 +1,14 @@
1
+ class InvalidTupleFormatError(ValueError):
2
+ """Raised when relation tuple components are invalid or malformed."""
3
+
4
+
5
+ class IdentifierValidationError(ValueError):
6
+ """Raised when an identifier value is invalid."""
7
+
8
+
9
+ class EntityIdValidationError(ValueError):
10
+ """Raised when an entity id value is invalid."""
11
+
12
+
13
+ class SubjectValidationError(ValueError):
14
+ """Raised when a subject string or components are invalid."""
@@ -0,0 +1,106 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ from .object import Obj
8
+ from .relation import Relation as Rel
9
+ from .subject import Subject
10
+ from .tuple import RelationTuple
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class TupleFilter:
15
+ """
16
+ Filter criteria for querying relation tuples.
17
+ All fields are optional - only specified fields are used for filtering.
18
+ """
19
+
20
+ object_type: str | None = None
21
+ object_id: str | None = None
22
+ relation: str | None = None
23
+ subject_type: str | None = None
24
+ subject_id: str | None = None
25
+ subject_relation: str | None = None
26
+
27
+ def matches(self, tuple: RelationTuple) -> bool:
28
+ """Check if a tuple matches this filter."""
29
+ return (
30
+ self._matches_object(tuple)
31
+ and self._matches_relation(tuple)
32
+ and self._matches_subject(tuple)
33
+ )
34
+
35
+ def _matches_object(self, tuple: RelationTuple) -> bool:
36
+ if (
37
+ self.object_type is not None
38
+ and str(tuple.object.namespace) != self.object_type
39
+ ):
40
+ return False
41
+ return not (
42
+ self.object_id is not None and str(tuple.object.id) != self.object_id
43
+ )
44
+
45
+ def _matches_relation(self, tuple: RelationTuple) -> bool:
46
+ return not (self.relation is not None and str(tuple.relation) != self.relation)
47
+
48
+ def _matches_subject(self, tuple: RelationTuple) -> bool:
49
+ if (
50
+ self.subject_type is not None
51
+ and str(tuple.subject.namespace) != self.subject_type
52
+ ):
53
+ return False
54
+ if self.subject_id is not None and str(tuple.subject.id) != self.subject_id:
55
+ return False
56
+ if self.subject_relation is not None:
57
+ if tuple.subject.relation is None:
58
+ return False
59
+ if str(tuple.subject.relation) != self.subject_relation:
60
+ return False
61
+ return True
62
+
63
+ @classmethod
64
+ def from_object(cls, obj: Obj) -> TupleFilter:
65
+ """Create a filter matching the given object (type and id)."""
66
+ return cls(
67
+ object_type=str(obj.namespace),
68
+ object_id=str(obj.id),
69
+ )
70
+
71
+ @classmethod
72
+ def from_relation(cls, relation: Rel) -> TupleFilter:
73
+ """Create a filter matching the given relation name."""
74
+ return cls(relation=str(relation))
75
+
76
+ @classmethod
77
+ def from_subject(cls, subject: Subject) -> TupleFilter:
78
+ """Create a filter matching the given subject (type/id and optional rel)."""
79
+ return cls(
80
+ subject_type=str(subject.namespace),
81
+ subject_id=str(subject.id),
82
+ subject_relation=(
83
+ str(subject.relation) if subject.relation is not None else None
84
+ ),
85
+ )
86
+
87
+ @classmethod
88
+ def from_parts(
89
+ cls,
90
+ obj: Obj | None = None,
91
+ relation: Rel | None = None,
92
+ subject: Subject | None = None,
93
+ ) -> TupleFilter:
94
+ """Create a filter from any subset of object, relation, and subject."""
95
+ return cls(
96
+ object_type=str(obj.namespace) if obj is not None else None,
97
+ object_id=str(obj.id) if obj is not None else None,
98
+ relation=str(relation) if relation is not None else None,
99
+ subject_type=str(subject.namespace) if subject is not None else None,
100
+ subject_id=str(subject.id) if subject is not None else None,
101
+ subject_relation=(
102
+ str(subject.relation)
103
+ if subject is not None and subject.relation is not None
104
+ else None
105
+ ),
106
+ )
zanzipy/models/id.py ADDED
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ import re
5
+ from typing import ClassVar
6
+
7
+ from .errors import EntityIdValidationError
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class EntityId:
12
+ """
13
+ Valid entity id for object_id and subject_id.
14
+
15
+ Rules:
16
+ - Cannot contain '#', '@', ':', or whitespace
17
+ - Otherwise may contain any unicode characters
18
+ """
19
+
20
+ _ID_CHARS: ClassVar[re.Pattern] = re.compile(r"^[^#@:\s]+$")
21
+
22
+ value: str
23
+
24
+ def __post_init__(self) -> None:
25
+ if not self.value:
26
+ raise EntityIdValidationError("id cannot be empty")
27
+ if not self._ID_CHARS.match(self.value):
28
+ raise EntityIdValidationError(
29
+ "id cannot contain '#', '@', ':', or whitespace characters"
30
+ )
31
+
32
+ def __str__(self) -> str:
33
+ return self.value
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ import re
5
+ from typing import ClassVar
6
+
7
+ from .errors import IdentifierValidationError
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class Identifier:
12
+ """
13
+ Valid Zanzibar identifier for namespaces and relations.
14
+
15
+ Rules:
16
+ - Start with a letter or underscore
17
+ - Contain letters, digits, underscores, or hyphens
18
+ """
19
+
20
+ _IDENTIFIER: ClassVar[re.Pattern] = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_-]*$")
21
+
22
+ value: str
23
+
24
+ def __post_init__(self) -> None:
25
+ if not self.value:
26
+ raise IdentifierValidationError("identifier cannot be empty")
27
+ if not self._IDENTIFIER.match(self.value):
28
+ raise IdentifierValidationError(
29
+ "identifier must be a valid identifier (letters/digits/_/-, start with "
30
+ "letter/_)"
31
+ )
32
+
33
+ def __str__(self) -> str:
34
+ return self.value
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from .identifier import Identifier
6
+
7
+
8
+ @dataclass(frozen=True, slots=True)
9
+ class Namespace(Identifier):
10
+ """Namespace value object (inherits Identifier validation)."""
@@ -0,0 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ from .id import EntityId
8
+ from .namespace import Namespace
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class Obj:
13
+ """Object value with namespace and id."""
14
+
15
+ namespace: Namespace
16
+ id: EntityId
17
+
18
+ def __str__(self) -> str:
19
+ return f"{self.namespace}:{self.id}"
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from .identifier import Identifier
6
+
7
+
8
+ @dataclass(frozen=True, slots=True)
9
+ class Relation(Identifier):
10
+ """Relation value object (inherits Identifier validation)."""
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Self
5
+
6
+ from .errors import (
7
+ SubjectValidationError,
8
+ )
9
+ from .id import EntityId
10
+ from .namespace import Namespace
11
+ from .relation import Relation
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class Subject:
16
+ """
17
+ Subject value object that can represent a direct subject or a subject set.
18
+
19
+ Forms:
20
+ - namespace:id
21
+ - namespace:id#relation
22
+ """
23
+
24
+ namespace: Namespace
25
+ id: EntityId
26
+ relation: Relation | None = None
27
+
28
+ @classmethod
29
+ def parse(cls, subject_string: str) -> Self:
30
+ # Split only once on '#'
31
+ if "#" in subject_string:
32
+ base, rel = subject_string.split("#", 1)
33
+ if rel == "":
34
+ raise SubjectValidationError("subject_relation cannot be empty string")
35
+ relation = Relation(rel)
36
+ else:
37
+ base = subject_string
38
+ relation = None
39
+
40
+ if ":" not in base:
41
+ raise SubjectValidationError("subject must be in 'namespace:id' form")
42
+ ns_str, id_str = base.split(":", 1)
43
+
44
+ namespace = Namespace(ns_str)
45
+ entity_id = EntityId(id_str)
46
+
47
+ return cls(namespace, entity_id, relation)
48
+
49
+ def __str__(self) -> str:
50
+ base = f"{self.namespace}:{self.id}"
51
+ return f"{base}#{self.relation}" if self.relation is not None else base
@@ -0,0 +1,206 @@
1
+ from dataclasses import dataclass
2
+ import re
3
+ from typing import ClassVar, Self
4
+
5
+ from .errors import InvalidTupleFormatError
6
+ from .id import EntityId
7
+ from .namespace import Namespace
8
+ from .object import Obj
9
+ from .relation import Relation
10
+ from .subject import Subject
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class RelationTuple:
15
+ """
16
+ Represents a Zanzibar relationship tuple.
17
+
18
+ Format:
19
+ `object_namespace:object_id#relation@subject_namespace:subject_id[#subject_relation]`
20
+
21
+ Constraints:
22
+ - Namespaces and relations must be valid identifiers (alphanumeric, underscore,
23
+ or hyphen, starting with letter or underscore)
24
+ - IDs may contain any characters except `#`, `@`, `:`, and whitespace
25
+ - subject_relation follows the same rules as relation
26
+ - No component may be empty
27
+
28
+ Examples:
29
+ - `document:readme#owner@user:alice`
30
+ - `folder:docs#viewer@group:eng#member`
31
+ - `doc:uuid-123-abc#can_read@user:bob`
32
+
33
+ Attributes:
34
+ object: The object being related (contains namespace and id)
35
+ relation: The relation name (e.g., 'owner', 'viewer', 'can_read')
36
+ subject: The subject entity (contains namespace, id, and optional
37
+ relation for subject sets)
38
+
39
+ Note:
40
+ Instances are immutable and hashable, suitable for use in sets and as dict keys.
41
+ """
42
+
43
+ # Complete tuple parsing pattern
44
+ _TUPLE_PATTERN: ClassVar[re.Pattern] = re.compile(
45
+ r"^(?P<object_namespace>[a-zA-Z_][a-zA-Z0-9_-]*)" # object namespace
46
+ r":(?P<object_id>[^#@:\s]+)" # object id
47
+ r"#(?P<relation>[a-zA-Z_][a-zA-Z0-9_-]*)" # relation
48
+ r"@(?P<subject_namespace>[a-zA-Z_][a-zA-Z0-9_-]*)" # subject namespace
49
+ r":(?P<subject_id>[^#@:\s]+)" # subject id
50
+ r"(?:#(?P<subject_relation>[a-zA-Z_][a-zA-Z0-9_-]*))?$" # optional subject rel
51
+ )
52
+
53
+ object: Obj
54
+ relation: Relation
55
+ subject: Subject
56
+
57
+ @classmethod
58
+ def from_string(cls, tuple_string: str) -> "RelationTuple":
59
+ """Parse a Zanzibar relation tuple string.
60
+
61
+ Args:
62
+ tuple_string:
63
+ String in format
64
+ `object_namespace:object_id#relation@subject_namespace:subject_id[#subject_relation]`
65
+
66
+ Returns:
67
+ RelationTuple instance
68
+
69
+ Raises:
70
+ InvalidTupleFormatError: If the string doesn't match the expected format
71
+
72
+ Examples:
73
+ >>> RelationTuple.from_string("document:readme#owner@user:alice")
74
+ >>> RelationTuple.from_string("folder:docs#viewer@group:eng#member")
75
+ """
76
+ match = cls._TUPLE_PATTERN.match(tuple_string)
77
+ if not match:
78
+ raise InvalidTupleFormatError(
79
+ f"Invalid tuple format: '{tuple_string}'. "
80
+ "Expected: 'object_namespace:object_id#relation@subject_namespace:"
81
+ "subject_id[#subject_relation]'. "
82
+ "Namespaces and relations must be valid identifiers "
83
+ "(letters/digits/_/-, start with letter/_). "
84
+ "IDs may contain any characters except '#', '@', ':', and whitespace. "
85
+ "No component may be empty."
86
+ )
87
+
88
+ groups = match.groupdict()
89
+ subject_relation = groups["subject_relation"]
90
+ return cls(
91
+ object=Obj(
92
+ Namespace(groups["object_namespace"]),
93
+ EntityId(groups["object_id"]),
94
+ ),
95
+ relation=Relation(groups["relation"]),
96
+ subject=Subject(
97
+ Namespace(groups["subject_namespace"]),
98
+ EntityId(groups["subject_id"]),
99
+ Relation(subject_relation) if subject_relation is not None else None,
100
+ ),
101
+ )
102
+
103
+ def to_dict(self) -> dict:
104
+ """Return a dictionary representation of the tuple.
105
+
106
+ Returns:
107
+ dict: Dictionary representation of the tuple
108
+
109
+ Examples:
110
+ ```python
111
+ >>> RelationTuple.from_string("document:readme#owner@user:alice").to_dict()
112
+ {
113
+ 'object_namespace': 'document',
114
+ 'object_id': 'readme',
115
+ 'relation': 'owner',
116
+ 'subject_namespace': 'user',
117
+ 'subject_id': 'alice',
118
+ 'subject_relation': None
119
+ }
120
+ ```
121
+ """
122
+ return {
123
+ "object_namespace": str(self.object.namespace),
124
+ "object_id": str(self.object.id),
125
+ "relation": str(self.relation),
126
+ "subject_namespace": str(self.subject.namespace),
127
+ "subject_id": str(self.subject.id),
128
+ "subject_relation": (
129
+ str(self.subject.relation)
130
+ if self.subject.relation is not None
131
+ else None
132
+ ),
133
+ }
134
+
135
+ @classmethod
136
+ def from_dict(cls, data: dict) -> Self:
137
+ """Create a RelationTuple from a dictionary.
138
+
139
+ Args:
140
+ data: Dictionary representation of the tuple
141
+
142
+ Returns:
143
+ RelationTuple: RelationTuple instance
144
+
145
+ Examples:
146
+ ```python
147
+ >>> RelationTuple.from_dict({
148
+ ... "object_namespace": "document",
149
+ ... "object_id": "readme",
150
+ ... "relation": "owner",
151
+ ... "subject_namespace": "user",
152
+ ... "subject_id": "alice",
153
+ ... })
154
+ RelationTuple(
155
+ object_namespace='document',
156
+ object_id='readme',
157
+ relation='owner',
158
+ subject_namespace='user',
159
+ subject_id='alice',
160
+ subject_relation=None
161
+ )
162
+ ```
163
+ """
164
+ # Treat presence of key with empty string as invalid
165
+ if "subject_relation" in data and data["subject_relation"] == "":
166
+ # This will raise IdentifierValidationError
167
+ subject_rel = Relation("")
168
+ else:
169
+ subject_rel = (
170
+ Relation(data["subject_relation"])
171
+ if data.get("subject_relation")
172
+ else None
173
+ )
174
+ return cls(
175
+ object=Obj(
176
+ Namespace(data["object_namespace"]),
177
+ EntityId(data["object_id"]),
178
+ ),
179
+ relation=Relation(data["relation"]),
180
+ subject=Subject(
181
+ Namespace(data["subject_namespace"]),
182
+ EntityId(data["subject_id"]),
183
+ subject_rel,
184
+ ),
185
+ )
186
+
187
+ def __str__(self) -> str:
188
+ """Return canonical string representation of the tuple."""
189
+ object_str = str(self.object)
190
+ subject_str = str(self.subject)
191
+ return f"{object_str}#{self.relation}@{subject_str}"
192
+
193
+ def __repr__(self) -> str:
194
+ """Return detailed representation for debugging."""
195
+ subject_relation_repr = (
196
+ str(self.subject.relation) if self.subject.relation is not None else None
197
+ )
198
+ return (
199
+ f"RelationTuple("
200
+ f"object_namespace={str(self.object.namespace)!r}, "
201
+ f"object_id={str(self.object.id)!r}, "
202
+ f"relation={str(self.relation)!r}, "
203
+ f"subject_namespace={str(self.subject.namespace)!r}, "
204
+ f"subject_id={str(self.subject.id)!r}, "
205
+ f"subject_relation={subject_relation_repr!r})"
206
+ )
@@ -0,0 +1,25 @@
1
+ from dataclasses import dataclass
2
+
3
+ from ..models.relation import Relation as Rel
4
+ from .rules import RewriteRule
5
+
6
+
7
+ @dataclass(frozen=True, slots=True)
8
+ class PermissionDef:
9
+ """Defines a computed permission: rewrite expression only."""
10
+
11
+ name: str
12
+ rewrite: RewriteRule
13
+ description: str | None = None
14
+
15
+ def __post_init__(self) -> None:
16
+ # Validate permission name as a relation identifier
17
+ Rel(self.name)
18
+
19
+ def to_dict(self) -> dict:
20
+ return {
21
+ "type": "permission",
22
+ "name": self.name,
23
+ "rewrite": self.rewrite.to_dict(),
24
+ "description": self.description,
25
+ }
@@ -0,0 +1,56 @@
1
+ from collections.abc import Iterable
2
+ from dataclasses import dataclass
3
+
4
+ from ..models.relation import Relation as Rel
5
+ from .rules import RewriteRule
6
+ from .subjects import SubjectReference
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class RelationDef:
11
+ """Defines a relation: allowed subject types and optional rewrite.
12
+
13
+ Note: Relations must declare at least one allowed subject.
14
+ """
15
+
16
+ name: str
17
+ allowed_subjects: tuple[SubjectReference, ...]
18
+ rewrite: RewriteRule | None = None
19
+ description: str | None = None
20
+
21
+ def __post_init__(self) -> None:
22
+ # Validate relation name
23
+ Rel(self.name)
24
+ if not self.allowed_subjects:
25
+ raise ValueError("Relation must declare at least one allowed subject type")
26
+
27
+ @classmethod
28
+ def with_subjects(
29
+ cls,
30
+ name: str,
31
+ subjects: Iterable[SubjectReference],
32
+ rewrite: RewriteRule | None = None,
33
+ description: str | None = None,
34
+ ) -> "RelationDef":
35
+ return cls(
36
+ name=name,
37
+ allowed_subjects=tuple(subjects),
38
+ rewrite=rewrite,
39
+ description=description,
40
+ )
41
+
42
+ def to_dict(self) -> dict:
43
+ return {
44
+ "type": "relation",
45
+ "name": self.name,
46
+ "allowed_subjects": [
47
+ {
48
+ "namespace": s.namespace.value,
49
+ "relation": (s.relation.value if s.relation else None),
50
+ "wildcard": s.wildcard,
51
+ }
52
+ for s in self.allowed_subjects
53
+ ],
54
+ "rewrite": self.rewrite.to_dict() if self.rewrite else None,
55
+ "description": self.description,
56
+ }
@@ -0,0 +1,211 @@
1
+ """Rewrite rules for Zanzibar-style relation/permission definitions.
2
+
3
+ This module models the minimal set of rewrite rules used to compose
4
+ relations and permissions. Rules are exported to a portable dictionary
5
+ format (for JSON, etc.).
6
+
7
+ What this models
8
+ ----------------
9
+ - A small algebra of rewrite nodes that mirrors Zanzibar:
10
+ - Leaf nodes:
11
+ - ThisRule: refers to direct tuple membership of the relation ("this").
12
+ Only valid in relation rewrites.
13
+ - ComputedUsersetRule: refers to another relation by name within the same
14
+ namespace (e.g., "viewer").
15
+ - TupleToUsersetRule: follows a relation from the object to a relation on
16
+ the subject (e.g., "parent->viewer").
17
+ - Operators:
18
+ - UnionRule: any child grants access ("+").
19
+ - IntersectionRule: all children required ("&").
20
+ - ExclusionRule: base minus subtract ("-").
21
+
22
+ - Permissions are built purely from rewrite nodes; relations can optionally
23
+ include rewrites and may also include ThisRule to incorporate direct tuples.
24
+
25
+ Examples
26
+ --------
27
+ - Direct stored relation (no rewrite):
28
+ relation owner: user
29
+ Represented as:
30
+ DirectRule()
31
+
32
+ - Relation with direct tuples plus a subject-set:
33
+ relation editor: user | group#member = this + group#member
34
+ Represented as:
35
+ UnionRule(
36
+ children=(ThisRule(), ComputedUsersetRule("group#member"))
37
+ )
38
+
39
+ - Permission that any owner or editor may access:
40
+ permission can_view = owner + editor
41
+ Represented as:
42
+ UnionRule(
43
+ children=(
44
+ ComputedUsersetRule("owner"),
45
+ ComputedUsersetRule("editor"),
46
+ )
47
+ )
48
+
49
+ - Permission that requires both member and not banned:
50
+ permission can_comment = member - banned
51
+ Represented as:
52
+ ExclusionRule(
53
+ base=ComputedUsersetRule("member"),
54
+ subtract=ComputedUsersetRule("banned"),
55
+ )
56
+
57
+ - Permission that requires both viewer and member:
58
+ permission can_download = viewer & member
59
+ Represented as:
60
+ IntersectionRule(
61
+ children=(
62
+ ComputedUsersetRule("viewer"),
63
+ ComputedUsersetRule("member"),
64
+ )
65
+ )
66
+ """
67
+
68
+ from abc import ABC, abstractmethod
69
+ from dataclasses import dataclass, field
70
+ from typing import Literal
71
+
72
+ # Type aliases for readability
73
+ RelationName = str
74
+
75
+
76
+ class RewriteRule(ABC):
77
+ """Base class for relation rewrite rules"""
78
+
79
+ @abstractmethod
80
+ def to_dict(self) -> dict:
81
+ """Serialize to portable JSON format"""
82
+ pass
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class ThisRule(RewriteRule):
87
+ """Leaf that references the direct (stored) membership of the relation."""
88
+
89
+ type: Literal["this"] = field(default="this", init=False)
90
+
91
+ def to_dict(self) -> dict:
92
+ return {"type": self.type}
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class ComputedUsersetRule(RewriteRule):
97
+ """Leaf that references another relation by name."""
98
+
99
+ relation: RelationName
100
+
101
+ type: Literal["computed_userset"] = field(default="computed_userset", init=False)
102
+
103
+ def to_dict(self) -> dict:
104
+ return {"type": self.type, "relation": self.relation}
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class TupleToUsersetRule(RewriteRule):
109
+ """Tuple-to-userset: follow a relation on the object
110
+ to a relation on the subject."""
111
+
112
+ tuple_relation: RelationName
113
+ computed_relation: RelationName
114
+
115
+ def to_dict(self) -> dict:
116
+ return {
117
+ "type": self.type,
118
+ "tuple_relation": self.tuple_relation,
119
+ "computed_relation": self.computed_relation,
120
+ }
121
+
122
+ type: Literal["tuple_to_userset"] = field(default="tuple_to_userset", init=False)
123
+
124
+
125
+ @dataclass(frozen=True)
126
+ class DirectRule(RewriteRule):
127
+ """Direct relation assignment (stored tuples).
128
+
129
+ Direct rules indicate that the relation is backed only by stored tuples
130
+ (no rewrite).
131
+
132
+ Example:
133
+ relation owner: user -> DirectRule()
134
+ """
135
+
136
+ type: Literal["direct"] = field(default="direct", init=False)
137
+
138
+ def to_dict(self) -> dict:
139
+ return {"type": self.type}
140
+
141
+
142
+ @dataclass(frozen=True)
143
+ class UnionRule(RewriteRule):
144
+ """Union: access is granted if any of the children relations grant it.
145
+
146
+
147
+ Example:
148
+ permission can_view = owner + editor
149
+ -> UnionRule(children=(
150
+ ComputedUsersetRule("owner"),
151
+ ComputedUsersetRule("editor"),
152
+ ))
153
+ """
154
+
155
+ # Children are nested rewrite rules; operands must be typed nodes
156
+ children: tuple[RewriteRule, ...]
157
+
158
+ def to_dict(self) -> dict:
159
+ return {"type": self.type, "children": [c.to_dict() for c in self.children]}
160
+
161
+ type: Literal["union"] = field(default="union", init=False)
162
+
163
+
164
+ @dataclass(frozen=True)
165
+ class IntersectionRule(RewriteRule):
166
+ """Intersection: access requires all children relations to grant it.
167
+
168
+
169
+ Example:
170
+ permission can_download = viewer & member
171
+ -> IntersectionRule(children=(
172
+ ComputedUsersetRule("viewer"),
173
+ ComputedUsersetRule("member"),
174
+ ))
175
+ """
176
+
177
+ # Children are nested rewrite rules; operands must be typed nodes
178
+ children: tuple[RewriteRule, ...]
179
+
180
+ def to_dict(self) -> dict:
181
+ return {"type": self.type, "children": [c.to_dict() for c in self.children]}
182
+
183
+ type: Literal["intersection"] = field(default="intersection", init=False)
184
+
185
+
186
+ @dataclass(frozen=True)
187
+ class ExclusionRule(RewriteRule):
188
+ """Exclusion: grant from base but not from subtract.
189
+
190
+ The expression is ``base - subtract``.
191
+
192
+ Example:
193
+ permission can_comment = member - banned
194
+ -> ExclusionRule(
195
+ base=ComputedUsersetRule("member"),
196
+ subtract=ComputedUsersetRule("banned"),
197
+ )
198
+ """
199
+
200
+ # Operands are nested rewrite rules; operands must be typed nodes
201
+ base: RewriteRule
202
+ subtract: RewriteRule
203
+
204
+ def to_dict(self) -> dict:
205
+ return {
206
+ "type": self.type,
207
+ "base": self.base.to_dict(),
208
+ "subtract": self.subtract.to_dict(),
209
+ }
210
+
211
+ type: Literal["exclusion"] = field(default="exclusion", init=False)
@@ -0,0 +1,24 @@
1
+ from dataclasses import dataclass
2
+
3
+ from ..models.namespace import Namespace
4
+ from ..models.relation import Relation as Rel
5
+
6
+
7
+ @dataclass(frozen=True, slots=True)
8
+ class SubjectReference:
9
+ """Represents an allowed subject type for a relation.
10
+
11
+ Forms supported (SpiceDB compatible):
12
+ - "ns" (e.g., user)
13
+ - "ns#rel" (e.g., group#member)
14
+ - "ns:*" (namespace wildcard)
15
+ """
16
+
17
+ namespace: Namespace
18
+ relation: Rel | None = None
19
+ wildcard: bool = False
20
+
21
+ def __post_init__(self) -> None:
22
+ # Validate invariant combinations
23
+ if self.wildcard and self.relation is not None:
24
+ raise ValueError("wildcard and relation are mutually exclusive")
@@ -0,0 +1,222 @@
1
+ Metadata-Version: 2.3
2
+ Name: zanzipy
3
+ Version: 0.1.0
4
+ Summary: Building blocks for zanzibar style ReBAC
5
+ Keywords: rebac,zanzibar,authorization,acl,relations
6
+ Author: Tyler Chambers
7
+ License: Apache License
8
+ Version 2.0, January 2004
9
+ http://www.apache.org/licenses/
10
+
11
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
12
+
13
+ 1. Definitions.
14
+
15
+ "License" shall mean the terms and conditions for use, reproduction,
16
+ and distribution as defined by Sections 1 through 9 of this document.
17
+
18
+ "Licensor" shall mean the copyright owner or entity authorized by
19
+ the copyright owner that is granting the License.
20
+
21
+ "Legal Entity" shall mean the union of the acting entity and all
22
+ other entities that control, are controlled by, or are under common
23
+ control with that entity. For the purposes of this definition,
24
+ "control" means (i) the power, direct or indirect, to cause the
25
+ direction or management of such entity, whether by contract or
26
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
27
+ outstanding shares, or (iii) beneficial ownership of such entity.
28
+
29
+ "You" (or "Your") shall mean an individual or Legal Entity
30
+ exercising permissions granted by this License.
31
+
32
+ "Source" form shall mean the preferred form for making modifications,
33
+ including but not limited to software source code, documentation
34
+ source, and configuration files.
35
+
36
+ "Object" form shall mean any form resulting from mechanical
37
+ transformation or translation of a Source form, including but
38
+ not limited to compiled object code, generated documentation,
39
+ and conversions to other media types.
40
+
41
+ "Work" shall mean the work of authorship, whether in Source or
42
+ Object form, made available under the License, as indicated by a
43
+ copyright notice that is included in or attached to the work
44
+ (an example is provided in the Appendix below).
45
+
46
+ "Derivative Works" shall mean any work, whether in Source or Object
47
+ form, that is based on (or derived from) the Work and for which the
48
+ editorial revisions, annotations, elaborations, or other modifications
49
+ represent, as a whole, an original work of authorship. For the purposes
50
+ of this License, Derivative Works shall not include works that remain
51
+ separable from, or merely link (or bind by name) to the interfaces of,
52
+ the Work and Derivative Works thereof.
53
+
54
+ "Contribution" shall mean any work of authorship, including
55
+ the original version of the Work and any modifications or additions
56
+ to that Work or Derivative Works thereof, that is intentionally
57
+ submitted to Licensor for inclusion in the Work by the copyright owner
58
+ or by an individual or Legal Entity authorized to submit on behalf of
59
+ the copyright owner. For the purposes of this definition, "submitted"
60
+ means any form of electronic, verbal, or written communication sent
61
+ to the Licensor or its representatives, including but not limited to
62
+ communication on electronic mailing lists, source code control systems,
63
+ and issue tracking systems that are managed by, or on behalf of, the
64
+ Licensor for the purpose of discussing and improving the Work, but
65
+ excluding communication that is conspicuously marked or otherwise
66
+ designated in writing by the copyright owner as "Not a Contribution."
67
+
68
+ "Contributor" shall mean Licensor and any individual or Legal Entity
69
+ on behalf of whom a Contribution has been received by Licensor and
70
+ subsequently incorporated within the Work.
71
+
72
+ 2. Grant of Copyright License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ copyright license to reproduce, prepare Derivative Works of,
76
+ publicly display, publicly perform, sublicense, and distribute the
77
+ Work and such Derivative Works in Source or Object form.
78
+
79
+ 3. Grant of Patent License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ (except as stated in this section) patent license to make, have made,
83
+ use, offer to sell, sell, import, and otherwise transfer the Work,
84
+ where such license applies only to those patent claims licensable
85
+ by such Contributor that are necessarily infringed by their
86
+ Contribution(s) alone or by combination of their Contribution(s)
87
+ with the Work to which such Contribution(s) was submitted. If You
88
+ institute patent litigation against any entity (including a
89
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
90
+ or a Contribution incorporated within the Work constitutes direct
91
+ or contributory patent infringement, then any patent licenses
92
+ granted to You under this License for that Work shall terminate
93
+ as of the date such litigation is filed.
94
+
95
+ 4. Redistribution. You may reproduce and distribute copies of the
96
+ Work or Derivative Works thereof in any medium, with or without
97
+ modifications, and in Source or Object form, provided that You
98
+ meet the following conditions:
99
+
100
+ (a) You must give any other recipients of the Work or
101
+ Derivative Works a copy of this License; and
102
+
103
+ (b) You must cause any modified files to carry prominent notices
104
+ stating that You changed the files; and
105
+
106
+ (c) You must retain, in the Source form of any Derivative Works
107
+ that You distribute, all copyright, patent, trademark, and
108
+ attribution notices from the Source form of the Work,
109
+ excluding those notices that do not pertain to any part of
110
+ the Derivative Works; and
111
+
112
+ (d) If the Work includes a "NOTICE" text file as part of its
113
+ distribution, then any Derivative Works that You distribute must
114
+ include a readable copy of the attribution notices contained
115
+ within such NOTICE file, excluding those notices that do not
116
+ pertain to any part of the Derivative Works, in at least one
117
+ of the following places: within a NOTICE text file distributed
118
+ as part of the Derivative Works; within the Source form or
119
+ documentation, if provided along with the Derivative Works; or,
120
+ within a display generated by the Derivative Works, if and
121
+ wherever such third-party notices normally appear. The contents
122
+ of the NOTICE file are for informational purposes only and
123
+ do not modify the License. You may add Your own attribution
124
+ notices within Derivative Works that You distribute, alongside
125
+ or as an addendum to the NOTICE text from the Work, provided
126
+ that such additional attribution notices cannot be construed
127
+ as modifying the License.
128
+
129
+ You may add Your own copyright statement to Your modifications and
130
+ may provide additional or different license terms and conditions
131
+ for use, reproduction, or distribution of Your modifications, or
132
+ for any such Derivative Works as a whole, provided Your use,
133
+ reproduction, and distribution of the Work otherwise complies with
134
+ the conditions stated in this License.
135
+
136
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
137
+ any Contribution intentionally submitted for inclusion in the Work
138
+ by You to the Licensor shall be under the terms and conditions of
139
+ this License, without any additional terms or conditions.
140
+ Notwithstanding the above, nothing herein shall supersede or modify
141
+ the terms of any separate license agreement you may have executed
142
+ with Licensor regarding such Contributions.
143
+
144
+ 6. Trademarks. This License does not grant permission to use the trade
145
+ names, trademarks, service marks, or product names of the Licensor,
146
+ except as required for reasonable and customary use in describing the
147
+ origin of the Work and reproducing the content of the NOTICE file.
148
+
149
+ 7. Disclaimer of Warranty. Unless required by applicable law or
150
+ agreed to in writing, Licensor provides the Work (and each
151
+ Contributor provides its Contributions) on an "AS IS" BASIS,
152
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
153
+ implied, including, without limitation, any warranties or conditions
154
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
155
+ PARTICULAR PURPOSE. You are solely responsible for determining the
156
+ appropriateness of using or redistributing the Work and assume any
157
+ risks associated with Your exercise of permissions under this License.
158
+
159
+ 8. Limitation of Liability. In no event and under no legal theory,
160
+ whether in tort (including negligence), contract, or otherwise,
161
+ unless required by applicable law (such as deliberate and grossly
162
+ negligent acts) or agreed to in writing, shall any Contributor be
163
+ liable to You for damages, including any direct, indirect, special,
164
+ incidental, or consequential damages of any character arising as a
165
+ result of this License or out of the use or inability to use the
166
+ Work (including but not limited to damages for loss of goodwill,
167
+ work stoppage, computer failure or malfunction, or any and all
168
+ other commercial damages or losses), even if such Contributor
169
+ has been advised of the possibility of such damages.
170
+
171
+ 9. Accepting Warranty or Additional Liability. While redistributing
172
+ the Work or Derivative Works thereof, You may choose to offer,
173
+ and charge a fee for, acceptance of support, warranty, indemnity,
174
+ or other liability obligations and/or rights consistent with this
175
+ License. However, in accepting such obligations, You may act only
176
+ on Your own behalf and on Your sole responsibility, not on behalf
177
+ of any other Contributor, and only if You agree to indemnify,
178
+ defend, and hold each Contributor harmless for any liability
179
+ incurred by, or claims asserted against, such Contributor by reason
180
+ of your accepting any such warranty or additional liability.
181
+
182
+ END OF TERMS AND CONDITIONS
183
+
184
+ APPENDIX: How to apply the Apache License to your work.
185
+
186
+ To apply the Apache License to your work, attach the following
187
+ boilerplate notice, with the fields enclosed by brackets "[]"
188
+ replaced with your own identifying information. (Don't include
189
+ the brackets!) The text should be enclosed in the appropriate
190
+ comment syntax for the file format. We also recommend that a
191
+ file or class name and description of purpose be included on the
192
+ same "printed page" as the copyright notice for easier
193
+ identification within third-party archives.
194
+
195
+ Copyright [yyyy] [name of copyright owner]
196
+
197
+ Licensed under the Apache License, Version 2.0 (the "License");
198
+ you may not use this file except in compliance with the License.
199
+ You may obtain a copy of the License at
200
+
201
+ http://www.apache.org/licenses/LICENSE-2.0
202
+
203
+ Unless required by applicable law or agreed to in writing, software
204
+ distributed under the License is distributed on an "AS IS" BASIS,
205
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
206
+ See the License for the specific language governing permissions and
207
+ limitations under the License.
208
+ Classifier: Programming Language :: Python :: 3
209
+ Classifier: Programming Language :: Python :: 3.14
210
+ Classifier: License :: OSI Approved :: Apache Software License
211
+ Classifier: Intended Audience :: Developers
212
+ Classifier: Topic :: Security
213
+ Classifier: Typing :: Typed
214
+ Requires-Python: >=3.14
215
+ Project-URL: Homepage, https://gitlab.com/tylerchambers/zanzipy
216
+ Project-URL: Issues, https://gitlab.com/tylerchambers/zanzipy/-/issues
217
+ Project-URL: Repository, https://gitlab.com/tylerchambers/zanzipy
218
+ Description-Content-Type: text/markdown
219
+
220
+ # zanzipy
221
+
222
+ A clean, Pythonic implementation of Google's Zanzibar authorization system. Just add persistence and caching.
@@ -0,0 +1,19 @@
1
+ zanzipy/__init__.py,sha256=MnoTdu1KVnbwLtkaBzHnCwjZNZMSOVez3mn4fDNmgDc,155
2
+ zanzipy/models/__init__.py,sha256=wNT-SJ1ZFfED6SqiyxQud3UhlSVNLR2LLYeY8XtAEbk,605
3
+ zanzipy/models/check.py,sha256=jt1qrEX39jlXPiqhGbnB1tyE478On5cEarOTzxDt18k,4210
4
+ zanzipy/models/errors.py,sha256=5toJP9nImLwtY4E6npkJMtmDU4efP467i1UrPk526xM,426
5
+ zanzipy/models/filter.py,sha256=O_QIE4k6HUS5qxjeSYSXE7MjUGNWbup1MiJPAb2JX3I,3663
6
+ zanzipy/models/id.py,sha256=x_CAZ79f_HPzq2foiJ5D9otlJD7m4uAKIeaQNLqqI6E,836
7
+ zanzipy/models/identifier.py,sha256=8563b39AfPfgu2iZyI8qWFWiQOBGwcWWhM0Dd3zPa9w,915
8
+ zanzipy/models/namespace.py,sha256=59QKJy15lpv40PVISuCBelghaOkA9Maypz-joNMExu0,240
9
+ zanzipy/models/object.py,sha256=v4y7ot67kzPwRzECj0Lpz6kI22FP0lEvFxq92k8X6gU,402
10
+ zanzipy/models/relation.py,sha256=tYC6Gfq2iK_DrBgQbU1b3tgkyL0dfJD1g3ZSttGE_jo,238
11
+ zanzipy/models/subject.py,sha256=WJe2qm5knm-GdVKSbIFG8H3JfDvPZwHSYpXtqNhIV0w,1377
12
+ zanzipy/models/tuple.py,sha256=Vo1Y0TuFt7YyfGzBijTGmH-usbDW4Bnki3DzdJ9nmEc,7328
13
+ zanzipy/schema/permissions.py,sha256=NepF3DdkQBRw8ymFZ48ayifmKRtzQj15vy60CnKSmvE,649
14
+ zanzipy/schema/relations.py,sha256=tf16tagZU_su17rkfGwDIGHIb8qCpnGTDyhSNtRVCCE,1684
15
+ zanzipy/schema/rules.py,sha256=cc-bmt8ZQYy8EU59RGIe5WOHyVJmtk63GCq5y0PLPC0,5961
16
+ zanzipy/schema/subjects.py,sha256=cLHWl2TItkucL6k04bDsU7gBx5tfnXovx48otYxgiWs,685
17
+ zanzipy-0.1.0.dist-info/WHEEL,sha256=ZbtZh9LqsQoZs-WmwRO6z-tavdkb5LzNxvrOv2F_OXE,78
18
+ zanzipy-0.1.0.dist-info/METADATA,sha256=V-yGgzB1yqnxIqeuyw2qNiF1N8ePsZRjOZMmWBbopzk,13993
19
+ zanzipy-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.9.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any