python-authz 0.5.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anupam Gupta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,166 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-authz
3
+ Version: 0.5.0
4
+ Summary: A framework-agnostic ReBAC/RBAC/ABAC authorization engine built on one Zanzibar-style relationship graph
5
+ Author: Anupam Gupta
6
+ Author-email: Anupam Gupta <anupam@trois.in>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Security
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Dist: duckdb>=1.5.5
18
+ Requires-Dist: aiosqlite>=0.21.0
19
+ Requires-Dist: asyncpg>=0.31.0
20
+ Requires-Dist: fastapi[all]>=0.141.1 ; extra == 'fastapi'
21
+ Requires-Python: >=3.11
22
+ Project-URL: Homepage, https://github.com/mapuna/python-authz
23
+ Project-URL: Repository, https://github.com/mapuna/python-authz
24
+ Project-URL: Issues, https://github.com/mapuna/python-authz/issues
25
+ Provides-Extra: fastapi
26
+ Description-Content-Type: text/markdown
27
+
28
+ # authz
29
+
30
+ A framework-agnostic ReBAC/RBAC/ABAC authorization engine.
31
+
32
+ ## About
33
+
34
+ Most systems end up with three separate authorization mechanisms: roles
35
+ for admin/editor/viewer distinctions (RBAC), attribute rules for things
36
+ like "only during business hours" (ABAC), and some hand-rolled traversal
37
+ for hierarchies like folders or nested groups (ReBAC). `authz` implements
38
+ all three on one data structure instead: a graph of relationship facts,
39
+ each one a `(namespace, object, relation, subject)` tuple, in the style
40
+ of Google's Zanzibar paper.
41
+
42
+ A role is just a relation on an object, so "alice is an editor of
43
+ document:roadmap" is a tuple like any other. A folder hierarchy is a
44
+ traversal between tuples: "you can view a document if you can view its
45
+ parent folder" is one rule, applied uniformly no matter how deep the
46
+ folder tree goes. An attribute check is a condition attached to a
47
+ specific tuple, evaluated against the current subject and context at
48
+ check time. Because all three live in the same graph, a single `check()`
49
+ call can walk through a role, into a group, and across a parent/child
50
+ boundary in one pass, all using the same traversal logic, instead of
51
+ three separate mechanisms that would each need to be kept correct and
52
+ kept in agreement with each other.
53
+
54
+ ## Status
55
+
56
+ Early release, version 0.5:
57
+
58
+ - the core engine, async SQLite and PostgreSQL storage backends, and the
59
+ optional FastAPI `Depends()` integration (`authz.integrations.fastapi`,
60
+ installed via `python-authz[fastapi]`)
61
+ - a reference sample app (`examples/sample_app/`) and OAuth2/JWT auth
62
+ integration recipes (`examples/auth_integrations/`)
63
+
64
+ ## Roadmap
65
+
66
+ - DuckDB and MongoDB storage backends
67
+ - a standalone HTTP service mode beyond the sample app's admin routes
68
+ - a SAML auth integration recipe (OAuth2 and JWT are already covered)
69
+ - JSON-Logic and CEL `ConditionEvaluator` implementations, alongside the
70
+ existing Python-callable one
71
+ - Java, Kotlin, Rust, and C++ SDKs
72
+ - making `asyncpg`/`duckdb` and `pyjwt`/`httpx2` optional too, the way
73
+ `fastapi` already is
74
+
75
+ ## Install
76
+
77
+ ```bash
78
+ uv add python-authz
79
+ ```
80
+
81
+ ## Quickstart
82
+
83
+ A schema declares, per namespace, how each relation is computed: `Direct()`
84
+ means "true when a matching tuple exists," `Union` combines several rules
85
+ with OR, and `TupleToUserset` re-checks a relation on a related object (the
86
+ mechanism behind "viewer of the parent folder implies viewer of the
87
+ document"). Once the schema is registered, `write()` adds facts to the
88
+ graph and `check()` answers a yes/no access question against it:
89
+
90
+ ```python
91
+ from authz import (
92
+ Client, Direct, From, Namespace, PythonCallableEvaluator,
93
+ RelationTuple, SqliteStorage, TupleToUserset, Union,
94
+ )
95
+
96
+ async with SqliteStorage(":memory:") as storage:
97
+ client = Client(storage=storage, condition_evaluator=PythonCallableEvaluator())
98
+
99
+ folder = Namespace("folder", {
100
+ "owner": Direct(),
101
+ "viewer": Union(Direct(), From("owner")),
102
+ })
103
+ document = Namespace("document", {
104
+ "parent": Direct(),
105
+ "viewer": Union(Direct(), TupleToUserset("parent", "viewer")),
106
+ })
107
+
108
+ client.register_schema(folder, document)
109
+
110
+ await client.write([
111
+ RelationTuple("folder", "workspace", "owner", "user:alice"),
112
+ RelationTuple("document", "roadmap", "parent", "folder:workspace"),
113
+ ])
114
+
115
+ await client.check("user:alice", "viewer", "document:roadmap") # True
116
+ ```
117
+
118
+ See [`docs/quickstart.md`](docs/quickstart.md) for the full walkthrough
119
+ (groups, ABAC conditions, consistency tokens, `expand()`), and
120
+ [`examples/seed_data.py`](examples/seed_data.py) for a runnable version of
121
+ it: `python -m examples.seed_data`.
122
+
123
+ Before designing your own schema, read [`docs/pitfalls.md`](docs/pitfalls.md).
124
+ It covers schema vs. data cycles, which rewrite rule (`Union`,
125
+ `Intersection`, `Exclusion`, `From`, `TupleToUserset`) fits which
126
+ situation, and when a depth-limit error means your data is legitimately
127
+ deep versus something bypassed the guards.
128
+
129
+ ## FastAPI Integration Example
130
+
131
+ A route needs one thing from an authorization library: block the request
132
+ before the handler runs if the caller lacks permission. `authz.integrations.fastapi`
133
+ does that as a single `Depends()`, so the check happens the same way
134
+ FastAPI already resolves any other dependency. It's an optional adapter
135
+ built as a proof of concept; a Django, Flask, or plain-script consumer
136
+ should call the same `Client` directly instead.
137
+
138
+ ```python
139
+ from fastapi import Depends
140
+ from authz.integrations.fastapi import requires
141
+
142
+
143
+ @app.get("/documents/{document_id}")
144
+ async def read_document(
145
+ document_id: str,
146
+ _: None = Depends(requires(
147
+ "viewer", "document:{document_id}",
148
+ get_client=get_authz_client, get_subject=get_current_user,
149
+ )),
150
+ ):
151
+ ...
152
+ ```
153
+
154
+ `requires()` makes the route depend on a `check()` call: when that call
155
+ returns `False`, the request never reaches the handler body, and the
156
+ caller receives a 403 automatically. See
157
+ [`docs/fastapi_integration.md`](docs/fastapi_integration.md) for the full
158
+ example, including how `get_client`/`get_subject` compose with your app's
159
+ own database and auth setup.
160
+
161
+ ## Development
162
+
163
+ ```bash
164
+ uv sync --extra fastapi
165
+ uv run pytest
166
+ ```
@@ -0,0 +1,139 @@
1
+ # authz
2
+
3
+ A framework-agnostic ReBAC/RBAC/ABAC authorization engine.
4
+
5
+ ## About
6
+
7
+ Most systems end up with three separate authorization mechanisms: roles
8
+ for admin/editor/viewer distinctions (RBAC), attribute rules for things
9
+ like "only during business hours" (ABAC), and some hand-rolled traversal
10
+ for hierarchies like folders or nested groups (ReBAC). `authz` implements
11
+ all three on one data structure instead: a graph of relationship facts,
12
+ each one a `(namespace, object, relation, subject)` tuple, in the style
13
+ of Google's Zanzibar paper.
14
+
15
+ A role is just a relation on an object, so "alice is an editor of
16
+ document:roadmap" is a tuple like any other. A folder hierarchy is a
17
+ traversal between tuples: "you can view a document if you can view its
18
+ parent folder" is one rule, applied uniformly no matter how deep the
19
+ folder tree goes. An attribute check is a condition attached to a
20
+ specific tuple, evaluated against the current subject and context at
21
+ check time. Because all three live in the same graph, a single `check()`
22
+ call can walk through a role, into a group, and across a parent/child
23
+ boundary in one pass, all using the same traversal logic, instead of
24
+ three separate mechanisms that would each need to be kept correct and
25
+ kept in agreement with each other.
26
+
27
+ ## Status
28
+
29
+ Early release, version 0.5:
30
+
31
+ - the core engine, async SQLite and PostgreSQL storage backends, and the
32
+ optional FastAPI `Depends()` integration (`authz.integrations.fastapi`,
33
+ installed via `python-authz[fastapi]`)
34
+ - a reference sample app (`examples/sample_app/`) and OAuth2/JWT auth
35
+ integration recipes (`examples/auth_integrations/`)
36
+
37
+ ## Roadmap
38
+
39
+ - DuckDB and MongoDB storage backends
40
+ - a standalone HTTP service mode beyond the sample app's admin routes
41
+ - a SAML auth integration recipe (OAuth2 and JWT are already covered)
42
+ - JSON-Logic and CEL `ConditionEvaluator` implementations, alongside the
43
+ existing Python-callable one
44
+ - Java, Kotlin, Rust, and C++ SDKs
45
+ - making `asyncpg`/`duckdb` and `pyjwt`/`httpx2` optional too, the way
46
+ `fastapi` already is
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ uv add python-authz
52
+ ```
53
+
54
+ ## Quickstart
55
+
56
+ A schema declares, per namespace, how each relation is computed: `Direct()`
57
+ means "true when a matching tuple exists," `Union` combines several rules
58
+ with OR, and `TupleToUserset` re-checks a relation on a related object (the
59
+ mechanism behind "viewer of the parent folder implies viewer of the
60
+ document"). Once the schema is registered, `write()` adds facts to the
61
+ graph and `check()` answers a yes/no access question against it:
62
+
63
+ ```python
64
+ from authz import (
65
+ Client, Direct, From, Namespace, PythonCallableEvaluator,
66
+ RelationTuple, SqliteStorage, TupleToUserset, Union,
67
+ )
68
+
69
+ async with SqliteStorage(":memory:") as storage:
70
+ client = Client(storage=storage, condition_evaluator=PythonCallableEvaluator())
71
+
72
+ folder = Namespace("folder", {
73
+ "owner": Direct(),
74
+ "viewer": Union(Direct(), From("owner")),
75
+ })
76
+ document = Namespace("document", {
77
+ "parent": Direct(),
78
+ "viewer": Union(Direct(), TupleToUserset("parent", "viewer")),
79
+ })
80
+
81
+ client.register_schema(folder, document)
82
+
83
+ await client.write([
84
+ RelationTuple("folder", "workspace", "owner", "user:alice"),
85
+ RelationTuple("document", "roadmap", "parent", "folder:workspace"),
86
+ ])
87
+
88
+ await client.check("user:alice", "viewer", "document:roadmap") # True
89
+ ```
90
+
91
+ See [`docs/quickstart.md`](docs/quickstart.md) for the full walkthrough
92
+ (groups, ABAC conditions, consistency tokens, `expand()`), and
93
+ [`examples/seed_data.py`](examples/seed_data.py) for a runnable version of
94
+ it: `python -m examples.seed_data`.
95
+
96
+ Before designing your own schema, read [`docs/pitfalls.md`](docs/pitfalls.md).
97
+ It covers schema vs. data cycles, which rewrite rule (`Union`,
98
+ `Intersection`, `Exclusion`, `From`, `TupleToUserset`) fits which
99
+ situation, and when a depth-limit error means your data is legitimately
100
+ deep versus something bypassed the guards.
101
+
102
+ ## FastAPI Integration Example
103
+
104
+ A route needs one thing from an authorization library: block the request
105
+ before the handler runs if the caller lacks permission. `authz.integrations.fastapi`
106
+ does that as a single `Depends()`, so the check happens the same way
107
+ FastAPI already resolves any other dependency. It's an optional adapter
108
+ built as a proof of concept; a Django, Flask, or plain-script consumer
109
+ should call the same `Client` directly instead.
110
+
111
+ ```python
112
+ from fastapi import Depends
113
+ from authz.integrations.fastapi import requires
114
+
115
+
116
+ @app.get("/documents/{document_id}")
117
+ async def read_document(
118
+ document_id: str,
119
+ _: None = Depends(requires(
120
+ "viewer", "document:{document_id}",
121
+ get_client=get_authz_client, get_subject=get_current_user,
122
+ )),
123
+ ):
124
+ ...
125
+ ```
126
+
127
+ `requires()` makes the route depend on a `check()` call: when that call
128
+ returns `False`, the request never reaches the handler body, and the
129
+ caller receives a 403 automatically. See
130
+ [`docs/fastapi_integration.md`](docs/fastapi_integration.md) for the full
131
+ example, including how `get_client`/`get_subject` compose with your app's
132
+ own database and auth setup.
133
+
134
+ ## Development
135
+
136
+ ```bash
137
+ uv sync --extra fastapi
138
+ uv run pytest
139
+ ```
@@ -0,0 +1,58 @@
1
+ [project]
2
+ name = "python-authz"
3
+ version = "0.5.0"
4
+ description = "A framework-agnostic ReBAC/RBAC/ABAC authorization engine built on one Zanzibar-style relationship graph"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = [
10
+ "duckdb>=1.5.5",
11
+ "aiosqlite>=0.21.0",
12
+ "asyncpg>=0.31.0",
13
+ ]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Topic :: Security",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ ]
24
+
25
+ [[project.authors]]
26
+ name = "Anupam Gupta"
27
+ email = "anupam@trois.in"
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/mapuna/python-authz"
31
+ Repository = "https://github.com/mapuna/python-authz"
32
+ Issues = "https://github.com/mapuna/python-authz/issues"
33
+
34
+ [project.optional-dependencies]
35
+ fastapi = ["fastapi[all]>=0.141.1"]
36
+
37
+ [project.scripts]
38
+ authz = "authz:main"
39
+
40
+ [dependency-groups]
41
+ dev = [
42
+ "httpx2>=2.12.0",
43
+ "pyjwt>=2.13.0",
44
+ "pytest>=8.3.0",
45
+ "pytest-asyncio>=0.24.0",
46
+ "testcontainers[postgres]>=4.15.0",
47
+ ]
48
+
49
+ [tool.uv.build-backend]
50
+ module-name = "authz"
51
+
52
+ [tool.pytest.ini_options]
53
+ asyncio_mode = "auto"
54
+ testpaths = ["tests"]
55
+
56
+ [build-system]
57
+ requires = ["uv_build>=0.12.5,<0.13.0"]
58
+ build-backend = "uv_build"
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "python-authz"
3
+ version = "0.5.0"
4
+ description = "A framework-agnostic ReBAC/RBAC/ABAC authorization engine built on one Zanzibar-style relationship graph"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Anupam Gupta", email = "anupam@trois.in" }]
9
+ requires-python = ">=3.11"
10
+ dependencies = ["duckdb>=1.5.5", "aiosqlite>=0.21.0", "asyncpg>=0.31.0"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Topic :: Security",
19
+ "Topic :: Software Development :: Libraries :: Python Modules",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/mapuna/python-authz"
24
+ Repository = "https://github.com/mapuna/python-authz"
25
+ Issues = "https://github.com/mapuna/python-authz/issues"
26
+
27
+ [project.optional-dependencies]
28
+ fastapi = ["fastapi[all]>=0.141.1"]
29
+
30
+ [dependency-groups]
31
+ dev = [
32
+ "httpx2>=2.12.0",
33
+ "pyjwt>=2.13.0",
34
+ "pytest>=8.3.0",
35
+ "pytest-asyncio>=0.24.0",
36
+ "testcontainers[postgres]>=4.15.0",
37
+ ]
38
+
39
+ [project.scripts]
40
+ authz = "authz:main"
41
+
42
+ [tool.uv.build-backend]
43
+ module-name = "authz"
44
+
45
+ [tool.pytest.ini_options]
46
+ asyncio_mode = "auto"
47
+ testpaths = ["tests"]
48
+
49
+ [build-system]
50
+ requires = ["uv_build>=0.12.5,<0.13.0"]
51
+ build-backend = "uv_build"
@@ -0,0 +1,61 @@
1
+ from authz.conditions import ConditionEvaluator, PythonCallableEvaluator
2
+ from authz.engine import Client, UsersetTree
3
+ from authz.errors import (
4
+ AuthError,
5
+ ConditionNotFound,
6
+ CycleDetected,
7
+ DepthLimitExceeded,
8
+ NamespaceNotFound,
9
+ RelationNotFound,
10
+ SchemaCycleDetected,
11
+ WouldCreateCycle,
12
+ )
13
+ from authz.schema import (
14
+ Direct,
15
+ Exclusion,
16
+ From,
17
+ Intersection,
18
+ Namespace,
19
+ RewriteRule,
20
+ TupleToUserset,
21
+ Union,
22
+ )
23
+ from authz.storage.base import Storage, Token
24
+ from authz.storage.postgres import PostgresStorage
25
+ from authz.storage.sqlite import SqliteStorage
26
+ from authz.tuples import Condition, ObjectRef, RelationTuple, SubjectRef
27
+
28
+ __all__ = [
29
+ "AuthError",
30
+ "Client",
31
+ "Condition",
32
+ "ConditionEvaluator",
33
+ "ConditionNotFound",
34
+ "CycleDetected",
35
+ "DepthLimitExceeded",
36
+ "Direct",
37
+ "Exclusion",
38
+ "From",
39
+ "Intersection",
40
+ "Namespace",
41
+ "NamespaceNotFound",
42
+ "ObjectRef",
43
+ "PostgresStorage",
44
+ "PythonCallableEvaluator",
45
+ "RelationNotFound",
46
+ "RelationTuple",
47
+ "RewriteRule",
48
+ "SchemaCycleDetected",
49
+ "SqliteStorage",
50
+ "Storage",
51
+ "SubjectRef",
52
+ "Token",
53
+ "TupleToUserset",
54
+ "Union",
55
+ "UsersetTree",
56
+ "WouldCreateCycle",
57
+ ]
58
+
59
+
60
+ def main() -> None:
61
+ print("Hello from authz!")
@@ -0,0 +1,37 @@
1
+ import inspect
2
+ from typing import Any, Awaitable, Callable, Mapping, Protocol, Union
3
+
4
+ from authz.errors import ConditionNotFound
5
+
6
+ ConditionFn = Callable[..., Union[bool, Awaitable[bool]]]
7
+
8
+
9
+ class ConditionEvaluator(Protocol):
10
+ def is_registered(self, name: str) -> bool: ...
11
+
12
+ async def evaluate(
13
+ self, name: str, subject: str, resource: str, context: Mapping[str, Any]
14
+ ) -> bool: ...
15
+
16
+
17
+ class PythonCallableEvaluator:
18
+ def __init__(self) -> None:
19
+ self._conditions: dict[str, ConditionFn] = {}
20
+
21
+ def register(self, name: str, fn: ConditionFn) -> None:
22
+ self._conditions[name] = fn
23
+
24
+ def is_registered(self, name: str) -> bool:
25
+ return name in self._conditions
26
+
27
+ async def evaluate(
28
+ self, name: str, subject: str, resource: str, context: Mapping[str, Any]
29
+ ) -> bool:
30
+ try:
31
+ fn = self._conditions[name]
32
+ except KeyError:
33
+ raise ConditionNotFound(name) from None
34
+ result = fn(subject=subject, resource=resource, **context)
35
+ if inspect.isawaitable(result):
36
+ result = await result
37
+ return bool(result)