authzen-client 0.2.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.
- authzen_client/__init__.py +62 -0
- authzen_client/_client.py +201 -0
- authzen_client/async_client.py +179 -0
- authzen_client/client.py +167 -0
- authzen_client/exceptions.py +24 -0
- authzen_client/models.py +274 -0
- authzen_client/py.typed +0 -0
- authzen_client/settings.py +31 -0
- authzen_client/types.py +5 -0
- authzen_client-0.2.0.dist-info/METADATA +89 -0
- authzen_client-0.2.0.dist-info/RECORD +14 -0
- authzen_client-0.2.0.dist-info/WHEEL +5 -0
- authzen_client-0.2.0.dist-info/licenses/LICENSE +21 -0
- authzen_client-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Typed Python client and models for the AuthZEN Authorization API."""
|
|
2
|
+
|
|
3
|
+
from authzen_client.client import AsyncAuthZENClient, AuthZENClient
|
|
4
|
+
from authzen_client.exceptions import AuthZENError, ProtocolError, TransportError
|
|
5
|
+
from authzen_client.models import (
|
|
6
|
+
Action,
|
|
7
|
+
ActionSearchRequest,
|
|
8
|
+
ActionSearchResponse,
|
|
9
|
+
Context,
|
|
10
|
+
Decision,
|
|
11
|
+
Evaluation,
|
|
12
|
+
EvaluationRequest,
|
|
13
|
+
EvaluationResponse,
|
|
14
|
+
EvaluationsOptions,
|
|
15
|
+
EvaluationsRequest,
|
|
16
|
+
EvaluationsResponse,
|
|
17
|
+
PageRequest,
|
|
18
|
+
PageResponse,
|
|
19
|
+
PDPMetadata,
|
|
20
|
+
Resource,
|
|
21
|
+
ResourceQuery,
|
|
22
|
+
ResourceSearchRequest,
|
|
23
|
+
ResourceSearchResponse,
|
|
24
|
+
Subject,
|
|
25
|
+
SubjectQuery,
|
|
26
|
+
SubjectSearchRequest,
|
|
27
|
+
SubjectSearchResponse,
|
|
28
|
+
)
|
|
29
|
+
from authzen_client.settings import Endpoints
|
|
30
|
+
from authzen_client.types import JsonObject
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"Action",
|
|
34
|
+
"ActionSearchRequest",
|
|
35
|
+
"ActionSearchResponse",
|
|
36
|
+
"AsyncAuthZENClient",
|
|
37
|
+
"AuthZENClient",
|
|
38
|
+
"AuthZENError",
|
|
39
|
+
"Context",
|
|
40
|
+
"Decision",
|
|
41
|
+
"Endpoints",
|
|
42
|
+
"Evaluation",
|
|
43
|
+
"EvaluationRequest",
|
|
44
|
+
"EvaluationResponse",
|
|
45
|
+
"EvaluationsOptions",
|
|
46
|
+
"EvaluationsRequest",
|
|
47
|
+
"EvaluationsResponse",
|
|
48
|
+
"JsonObject",
|
|
49
|
+
"PDPMetadata",
|
|
50
|
+
"PageRequest",
|
|
51
|
+
"PageResponse",
|
|
52
|
+
"ProtocolError",
|
|
53
|
+
"Resource",
|
|
54
|
+
"ResourceQuery",
|
|
55
|
+
"ResourceSearchRequest",
|
|
56
|
+
"ResourceSearchResponse",
|
|
57
|
+
"Subject",
|
|
58
|
+
"SubjectQuery",
|
|
59
|
+
"SubjectSearchRequest",
|
|
60
|
+
"SubjectSearchResponse",
|
|
61
|
+
"TransportError",
|
|
62
|
+
]
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Shared protocol validation and endpoint state for both clients."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Generator, Mapping
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from typing import Literal
|
|
6
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
7
|
+
|
|
8
|
+
import httpx2
|
|
9
|
+
from pydantic import BaseModel, ValidationError
|
|
10
|
+
|
|
11
|
+
from authzen_client.exceptions import ProtocolError, TransportError
|
|
12
|
+
from authzen_client.models import (
|
|
13
|
+
PageRequest,
|
|
14
|
+
PageResponse,
|
|
15
|
+
PDPMetadata,
|
|
16
|
+
SearchRequest,
|
|
17
|
+
)
|
|
18
|
+
from authzen_client.settings import Endpoints
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
from authlib.common.errors import AuthlibBaseError
|
|
22
|
+
except ImportError:
|
|
23
|
+
_AUTH_ERRORS: tuple[type[Exception], ...] = ()
|
|
24
|
+
else:
|
|
25
|
+
_AUTH_ERRORS = (AuthlibBaseError,)
|
|
26
|
+
|
|
27
|
+
type Endpoint = Literal["evaluation", "evaluations", "subjects", "resources", "actions"]
|
|
28
|
+
|
|
29
|
+
_METADATA_FIELDS = {
|
|
30
|
+
"evaluation": "access_evaluation_endpoint",
|
|
31
|
+
"evaluations": "access_evaluations_endpoint",
|
|
32
|
+
"subjects": "search_subject_endpoint",
|
|
33
|
+
"resources": "search_resource_endpoint",
|
|
34
|
+
"actions": "search_action_endpoint",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _with_base(base: httpx2.URL, value: str) -> str:
|
|
39
|
+
"""Join an endpoint onto the PDP base, keeping a base path such as /tenant."""
|
|
40
|
+
if httpx2.URL(value).is_absolute_url:
|
|
41
|
+
return value
|
|
42
|
+
prefix = str(base)
|
|
43
|
+
if not prefix.endswith("/"):
|
|
44
|
+
prefix += "/"
|
|
45
|
+
return prefix + value.lstrip("/")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _base_url(value: str) -> httpx2.URL:
|
|
49
|
+
try:
|
|
50
|
+
url = httpx2.URL(value)
|
|
51
|
+
except httpx2.InvalidURL as exc:
|
|
52
|
+
raise ValueError("base_url must be a valid HTTPS URL.") from exc
|
|
53
|
+
if url.scheme != "https" or not url.host or url.query or url.fragment:
|
|
54
|
+
raise ValueError("base_url must be an HTTPS URL without query or fragment.")
|
|
55
|
+
return url
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@contextmanager
|
|
59
|
+
def _request_errors() -> Generator[None, None, None]:
|
|
60
|
+
try:
|
|
61
|
+
yield
|
|
62
|
+
except httpx2.DecodingError as exc:
|
|
63
|
+
raise ProtocolError("The PDP response could not be decoded.") from exc
|
|
64
|
+
except httpx2.RequestError as exc:
|
|
65
|
+
raise TransportError("The AuthZEN HTTP request failed.") from exc
|
|
66
|
+
except _AUTH_ERRORS as exc:
|
|
67
|
+
raise ProtocolError("OAuth authentication failed.") from exc
|
|
68
|
+
except (httpx2.HTTPError, ValueError, AttributeError) as exc:
|
|
69
|
+
raise ProtocolError(
|
|
70
|
+
"HTTP request or authentication failed.",
|
|
71
|
+
response=getattr(exc, "response", None),
|
|
72
|
+
) from exc
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _response_model[T: BaseModel](response: httpx2.Response, model: type[T]) -> T:
|
|
76
|
+
if response.status_code != 200:
|
|
77
|
+
raise ProtocolError(
|
|
78
|
+
f"The PDP returned HTTP {response.status_code}, expected 200.",
|
|
79
|
+
response=response,
|
|
80
|
+
)
|
|
81
|
+
media_type = response.headers.get("content-type", "").partition(";")[0]
|
|
82
|
+
if media_type.strip().lower() != "application/json":
|
|
83
|
+
raise ProtocolError(
|
|
84
|
+
"The PDP response Content-Type must be application/json.", response=response
|
|
85
|
+
)
|
|
86
|
+
try:
|
|
87
|
+
return model.model_validate_json(response.content)
|
|
88
|
+
except ValidationError as exc:
|
|
89
|
+
raise ProtocolError(
|
|
90
|
+
"The PDP returned an invalid response.", response=response
|
|
91
|
+
) from exc
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class _Omitted:
|
|
95
|
+
"""Constructor argument the caller did not pass."""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
_OMITTED = _Omitted()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _timeout(
|
|
102
|
+
value: httpx2.Timeout | float | None | _Omitted,
|
|
103
|
+
) -> httpx2.Timeout | float | None:
|
|
104
|
+
if isinstance(value, _Omitted):
|
|
105
|
+
return 5.0
|
|
106
|
+
return value
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _reject_borrowed_settings(
|
|
110
|
+
*,
|
|
111
|
+
auth: object | None,
|
|
112
|
+
transport: object | None,
|
|
113
|
+
limits: object | None,
|
|
114
|
+
timeout: object,
|
|
115
|
+
) -> None:
|
|
116
|
+
"""Name each setting that must be configured on a caller-owned HTTP client."""
|
|
117
|
+
conflicts: list[str] = []
|
|
118
|
+
if auth is not None:
|
|
119
|
+
conflicts.append("auth")
|
|
120
|
+
if transport is not None:
|
|
121
|
+
conflicts.append("transport")
|
|
122
|
+
if limits is not None:
|
|
123
|
+
conflicts.append("limits")
|
|
124
|
+
if not isinstance(timeout, _Omitted):
|
|
125
|
+
conflicts.append("timeout")
|
|
126
|
+
if conflicts:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
f"Configure {', '.join(conflicts)} on the supplied http_client."
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _page_state[T: SearchRequest](request: T) -> tuple[T, set[str]]:
|
|
133
|
+
"""Copy a search and record its token so later pages cannot mutate or loop."""
|
|
134
|
+
seen: set[str] = set()
|
|
135
|
+
token = None if request.page is None else request.page.token
|
|
136
|
+
if token is not None and token != "":
|
|
137
|
+
seen.add(token)
|
|
138
|
+
return request.model_copy(deep=True), seen
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _next_request[T: SearchRequest](
|
|
142
|
+
request: T, page: PageResponse | None, seen: set[str]
|
|
143
|
+
) -> T | None:
|
|
144
|
+
if page is None or not page.next_token:
|
|
145
|
+
return None
|
|
146
|
+
if page.next_token in seen:
|
|
147
|
+
raise ProtocolError("The PDP repeated a pagination token.")
|
|
148
|
+
seen.add(page.next_token)
|
|
149
|
+
next_page = (request.page or PageRequest()).model_copy(
|
|
150
|
+
update={"token": page.next_token}
|
|
151
|
+
)
|
|
152
|
+
return request.model_copy(update={"page": next_page})
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class _ClientBase:
|
|
156
|
+
def __init__(
|
|
157
|
+
self,
|
|
158
|
+
base_url: str,
|
|
159
|
+
headers: Mapping[str, str] | None,
|
|
160
|
+
endpoints: Endpoints | None,
|
|
161
|
+
) -> None:
|
|
162
|
+
self._base = _base_url(base_url)
|
|
163
|
+
self._pdp_identifier = base_url
|
|
164
|
+
self._endpoints = endpoints if endpoints is not None else Endpoints()
|
|
165
|
+
self.metadata: PDPMetadata | None = None
|
|
166
|
+
self._headers = httpx2.Headers(headers)
|
|
167
|
+
self._headers.setdefault("Accept", "application/json")
|
|
168
|
+
|
|
169
|
+
def _body_headers(self) -> httpx2.Headers:
|
|
170
|
+
"""JSON content type for requests that send a body."""
|
|
171
|
+
headers = self._headers.copy()
|
|
172
|
+
headers["Content-Type"] = "application/json"
|
|
173
|
+
return headers
|
|
174
|
+
|
|
175
|
+
def _url(self, endpoint: Endpoint) -> str:
|
|
176
|
+
advertised = getattr(self.metadata, _METADATA_FIELDS[endpoint], None)
|
|
177
|
+
fallback = getattr(self._endpoints, endpoint)
|
|
178
|
+
chosen = advertised if advertised is not None else fallback
|
|
179
|
+
return _with_base(self._base, str(chosen))
|
|
180
|
+
|
|
181
|
+
def _metadata_url(self) -> str:
|
|
182
|
+
url = urlsplit(self._pdp_identifier)
|
|
183
|
+
return urlunsplit(
|
|
184
|
+
(
|
|
185
|
+
url.scheme,
|
|
186
|
+
url.netloc,
|
|
187
|
+
"/.well-known/authzen-configuration" + url.path,
|
|
188
|
+
"",
|
|
189
|
+
"",
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
def _accept_metadata(self, response: httpx2.Response) -> PDPMetadata:
|
|
194
|
+
metadata = _response_model(response, PDPMetadata)
|
|
195
|
+
if metadata.policy_decision_point != self._pdp_identifier:
|
|
196
|
+
raise ProtocolError(
|
|
197
|
+
"The metadata PDP identifier does not match base_url.",
|
|
198
|
+
response=response,
|
|
199
|
+
)
|
|
200
|
+
self.metadata = metadata
|
|
201
|
+
return metadata
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Request AuthZEN decisions using asynchronous HTTPS."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
|
|
4
|
+
from types import TracebackType
|
|
5
|
+
from typing import Self
|
|
6
|
+
|
|
7
|
+
import httpx2
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
|
|
10
|
+
from authzen_client._client import (
|
|
11
|
+
_OMITTED,
|
|
12
|
+
Endpoint,
|
|
13
|
+
_ClientBase,
|
|
14
|
+
_next_request,
|
|
15
|
+
_Omitted,
|
|
16
|
+
_page_state,
|
|
17
|
+
_reject_borrowed_settings,
|
|
18
|
+
_request_errors,
|
|
19
|
+
_response_model,
|
|
20
|
+
_timeout,
|
|
21
|
+
)
|
|
22
|
+
from authzen_client.models import (
|
|
23
|
+
Action,
|
|
24
|
+
ActionSearchRequest,
|
|
25
|
+
ActionSearchResponse,
|
|
26
|
+
EvaluationRequest,
|
|
27
|
+
EvaluationResponse,
|
|
28
|
+
EvaluationsRequest,
|
|
29
|
+
EvaluationsResponse,
|
|
30
|
+
PDPMetadata,
|
|
31
|
+
Resource,
|
|
32
|
+
ResourceSearchRequest,
|
|
33
|
+
ResourceSearchResponse,
|
|
34
|
+
SearchRequest,
|
|
35
|
+
SearchResponse,
|
|
36
|
+
Subject,
|
|
37
|
+
SubjectSearchRequest,
|
|
38
|
+
SubjectSearchResponse,
|
|
39
|
+
)
|
|
40
|
+
from authzen_client.settings import Endpoints
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class AsyncAuthZENClient(_ClientBase):
|
|
44
|
+
"""Request AuthZEN decisions using asynchronous HTTPS.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
base_url: HTTPS PDP identifier. A path prefix is preserved.
|
|
48
|
+
auth: HTTPX2 authentication object.
|
|
49
|
+
headers: Additional headers. POST requests send JSON.
|
|
50
|
+
transport: HTTPX2 transport for testing or custom connections.
|
|
51
|
+
timeout: Network-operation timeout, or None to disable timeouts.
|
|
52
|
+
limits: Connection pool limits for the owned HTTP client.
|
|
53
|
+
endpoints: Fallback paths or HTTPS URLs, overridden by discovery.
|
|
54
|
+
http_client: HTTPX2 client you created, including an Authlib client.
|
|
55
|
+
You close it. Set its transport and authentication on that client.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
*,
|
|
61
|
+
base_url: str,
|
|
62
|
+
auth: httpx2.Auth | None = None,
|
|
63
|
+
headers: Mapping[str, str] | None = None,
|
|
64
|
+
transport: httpx2.AsyncBaseTransport | None = None,
|
|
65
|
+
timeout: httpx2.Timeout | float | None | _Omitted = _OMITTED,
|
|
66
|
+
limits: httpx2.Limits | None = None,
|
|
67
|
+
endpoints: Endpoints | None = None,
|
|
68
|
+
http_client: httpx2.AsyncClient | None = None,
|
|
69
|
+
) -> None:
|
|
70
|
+
super().__init__(base_url, headers, endpoints)
|
|
71
|
+
if http_client is not None:
|
|
72
|
+
_reject_borrowed_settings(
|
|
73
|
+
auth=auth, transport=transport, limits=limits, timeout=timeout
|
|
74
|
+
)
|
|
75
|
+
self._owns_http = False
|
|
76
|
+
self._http = http_client
|
|
77
|
+
return
|
|
78
|
+
self._owns_http = True
|
|
79
|
+
self._http = httpx2.AsyncClient(
|
|
80
|
+
auth=auth,
|
|
81
|
+
transport=transport,
|
|
82
|
+
timeout=_timeout(timeout),
|
|
83
|
+
limits=limits if limits is not None else httpx2.Limits(),
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
async def _post(self, endpoint: Endpoint, request: BaseModel) -> httpx2.Response:
|
|
87
|
+
with _request_errors():
|
|
88
|
+
return await self._http.post(
|
|
89
|
+
self._url(endpoint),
|
|
90
|
+
headers=self._body_headers(),
|
|
91
|
+
json=request.model_dump(mode="json", exclude_defaults=True),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
async def discover(self) -> PDPMetadata:
|
|
95
|
+
"""Validate PDP metadata and select its advertised endpoints."""
|
|
96
|
+
with _request_errors():
|
|
97
|
+
response = await self._http.get(self._metadata_url(), headers=self._headers)
|
|
98
|
+
return self._accept_metadata(response)
|
|
99
|
+
|
|
100
|
+
async def evaluate(self, request: EvaluationRequest) -> EvaluationResponse:
|
|
101
|
+
"""Return a single allow or deny decision."""
|
|
102
|
+
return _response_model(
|
|
103
|
+
await self._post("evaluation", request), EvaluationResponse
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
async def evaluate_batch(self, request: EvaluationsRequest) -> EvaluationsResponse:
|
|
107
|
+
"""Return the batch response from the PDP."""
|
|
108
|
+
return _response_model(
|
|
109
|
+
await self._post("evaluations", request), EvaluationsResponse
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
async def search_resources(
|
|
113
|
+
self, request: ResourceSearchRequest
|
|
114
|
+
) -> ResourceSearchResponse:
|
|
115
|
+
"""Fetch one page of resources permitted for the subject and action."""
|
|
116
|
+
return _response_model(
|
|
117
|
+
await self._post("resources", request), ResourceSearchResponse
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
async def search_subjects(
|
|
121
|
+
self, request: SubjectSearchRequest
|
|
122
|
+
) -> SubjectSearchResponse:
|
|
123
|
+
"""Fetch one page of subjects permitted for the resource and action."""
|
|
124
|
+
return _response_model(
|
|
125
|
+
await self._post("subjects", request), SubjectSearchResponse
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
async def search_actions(
|
|
129
|
+
self, request: ActionSearchRequest
|
|
130
|
+
) -> ActionSearchResponse:
|
|
131
|
+
"""Fetch one page of actions permitted for the subject and resource."""
|
|
132
|
+
return _response_model(
|
|
133
|
+
await self._post("actions", request), ActionSearchResponse
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
async def _iterate[T: SearchRequest, R: Subject | Resource | Action](
|
|
137
|
+
self,
|
|
138
|
+
request: T,
|
|
139
|
+
search: Callable[[T], Awaitable[SearchResponse[R]]],
|
|
140
|
+
) -> AsyncIterator[R]:
|
|
141
|
+
current: T | None
|
|
142
|
+
current, seen = _page_state(request)
|
|
143
|
+
while current is not None:
|
|
144
|
+
response = await search(current)
|
|
145
|
+
for result in response.results:
|
|
146
|
+
yield result
|
|
147
|
+
current = _next_request(current, response.page, seen)
|
|
148
|
+
|
|
149
|
+
def iter_resources(self, request: ResourceSearchRequest) -> AsyncIterator[Resource]:
|
|
150
|
+
"""Lazily yield resources across pages without changing the input request."""
|
|
151
|
+
return self._iterate(request, self.search_resources)
|
|
152
|
+
|
|
153
|
+
def iter_subjects(self, request: SubjectSearchRequest) -> AsyncIterator[Subject]:
|
|
154
|
+
"""Lazily yield subjects across pages."""
|
|
155
|
+
return self._iterate(request, self.search_subjects)
|
|
156
|
+
|
|
157
|
+
def iter_actions(self, request: ActionSearchRequest) -> AsyncIterator[Action]:
|
|
158
|
+
"""Lazily yield actions across pages."""
|
|
159
|
+
return self._iterate(request, self.search_actions)
|
|
160
|
+
|
|
161
|
+
async def aclose(self) -> None:
|
|
162
|
+
"""Close the HTTP client this library opened. A passed http_client stays open."""
|
|
163
|
+
if self._owns_http:
|
|
164
|
+
await self._http.aclose()
|
|
165
|
+
|
|
166
|
+
async def __aenter__(self) -> Self:
|
|
167
|
+
"""Enter the owned HTTP client context."""
|
|
168
|
+
if self._owns_http:
|
|
169
|
+
await self._http.__aenter__()
|
|
170
|
+
return self
|
|
171
|
+
|
|
172
|
+
async def __aexit__(
|
|
173
|
+
self,
|
|
174
|
+
exc_type: type[BaseException] | None,
|
|
175
|
+
exc_value: BaseException | None,
|
|
176
|
+
traceback: TracebackType | None,
|
|
177
|
+
) -> None:
|
|
178
|
+
"""Release owned HTTP resources on leaving the context."""
|
|
179
|
+
await self.aclose()
|
authzen_client/client.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Request AuthZEN decisions using synchronous HTTPS."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
4
|
+
from types import TracebackType
|
|
5
|
+
from typing import Self
|
|
6
|
+
|
|
7
|
+
import httpx2
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
|
|
10
|
+
from authzen_client._client import (
|
|
11
|
+
_OMITTED,
|
|
12
|
+
Endpoint,
|
|
13
|
+
_ClientBase,
|
|
14
|
+
_next_request,
|
|
15
|
+
_Omitted,
|
|
16
|
+
_page_state,
|
|
17
|
+
_reject_borrowed_settings,
|
|
18
|
+
_request_errors,
|
|
19
|
+
_response_model,
|
|
20
|
+
_timeout,
|
|
21
|
+
)
|
|
22
|
+
from authzen_client.async_client import AsyncAuthZENClient
|
|
23
|
+
from authzen_client.models import (
|
|
24
|
+
Action,
|
|
25
|
+
ActionSearchRequest,
|
|
26
|
+
ActionSearchResponse,
|
|
27
|
+
EvaluationRequest,
|
|
28
|
+
EvaluationResponse,
|
|
29
|
+
EvaluationsRequest,
|
|
30
|
+
EvaluationsResponse,
|
|
31
|
+
PDPMetadata,
|
|
32
|
+
Resource,
|
|
33
|
+
ResourceSearchRequest,
|
|
34
|
+
ResourceSearchResponse,
|
|
35
|
+
SearchRequest,
|
|
36
|
+
SearchResponse,
|
|
37
|
+
Subject,
|
|
38
|
+
SubjectSearchRequest,
|
|
39
|
+
SubjectSearchResponse,
|
|
40
|
+
)
|
|
41
|
+
from authzen_client.settings import Endpoints
|
|
42
|
+
|
|
43
|
+
__all__ = ["AsyncAuthZENClient", "AuthZENClient"]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AuthZENClient(_ClientBase):
|
|
47
|
+
"""Request AuthZEN decisions using synchronous HTTPS.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
base_url: HTTPS PDP identifier. A path prefix is preserved.
|
|
51
|
+
auth: HTTPX2 authentication object.
|
|
52
|
+
headers: Additional headers. POST requests send JSON.
|
|
53
|
+
transport: HTTPX2 transport for testing or custom connections.
|
|
54
|
+
timeout: Network-operation timeout, or None to disable timeouts.
|
|
55
|
+
limits: Connection pool limits for the owned HTTP client.
|
|
56
|
+
endpoints: Fallback paths or HTTPS URLs, overridden by discovery.
|
|
57
|
+
http_client: HTTPX2 client you created, including an Authlib client.
|
|
58
|
+
You close it. Set its transport and authentication on that client.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def __init__(
|
|
62
|
+
self,
|
|
63
|
+
*,
|
|
64
|
+
base_url: str,
|
|
65
|
+
auth: httpx2.Auth | None = None,
|
|
66
|
+
headers: Mapping[str, str] | None = None,
|
|
67
|
+
transport: httpx2.BaseTransport | None = None,
|
|
68
|
+
timeout: httpx2.Timeout | float | None | _Omitted = _OMITTED,
|
|
69
|
+
limits: httpx2.Limits | None = None,
|
|
70
|
+
endpoints: Endpoints | None = None,
|
|
71
|
+
http_client: httpx2.Client | None = None,
|
|
72
|
+
) -> None:
|
|
73
|
+
super().__init__(base_url, headers, endpoints)
|
|
74
|
+
if http_client is not None:
|
|
75
|
+
_reject_borrowed_settings(
|
|
76
|
+
auth=auth, transport=transport, limits=limits, timeout=timeout
|
|
77
|
+
)
|
|
78
|
+
self._owns_http = False
|
|
79
|
+
self._http = http_client
|
|
80
|
+
return
|
|
81
|
+
self._owns_http = True
|
|
82
|
+
self._http = httpx2.Client(
|
|
83
|
+
auth=auth,
|
|
84
|
+
transport=transport,
|
|
85
|
+
timeout=_timeout(timeout),
|
|
86
|
+
limits=limits if limits is not None else httpx2.Limits(),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def _post(self, endpoint: Endpoint, request: BaseModel) -> httpx2.Response:
|
|
90
|
+
with _request_errors():
|
|
91
|
+
return self._http.post(
|
|
92
|
+
self._url(endpoint),
|
|
93
|
+
headers=self._body_headers(),
|
|
94
|
+
json=request.model_dump(mode="json", exclude_defaults=True),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
def discover(self) -> PDPMetadata:
|
|
98
|
+
"""Validate PDP metadata and select its advertised endpoints."""
|
|
99
|
+
with _request_errors():
|
|
100
|
+
response = self._http.get(self._metadata_url(), headers=self._headers)
|
|
101
|
+
return self._accept_metadata(response)
|
|
102
|
+
|
|
103
|
+
def evaluate(self, request: EvaluationRequest) -> EvaluationResponse:
|
|
104
|
+
"""Return a single allow or deny decision."""
|
|
105
|
+
return _response_model(self._post("evaluation", request), EvaluationResponse)
|
|
106
|
+
|
|
107
|
+
def evaluate_batch(self, request: EvaluationsRequest) -> EvaluationsResponse:
|
|
108
|
+
"""Return the batch response from the PDP."""
|
|
109
|
+
return _response_model(self._post("evaluations", request), EvaluationsResponse)
|
|
110
|
+
|
|
111
|
+
def search_resources(
|
|
112
|
+
self, request: ResourceSearchRequest
|
|
113
|
+
) -> ResourceSearchResponse:
|
|
114
|
+
"""Fetch one page of resources permitted for the subject and action."""
|
|
115
|
+
return _response_model(self._post("resources", request), ResourceSearchResponse)
|
|
116
|
+
|
|
117
|
+
def search_subjects(self, request: SubjectSearchRequest) -> SubjectSearchResponse:
|
|
118
|
+
"""Fetch one page of subjects permitted for the resource and action."""
|
|
119
|
+
return _response_model(self._post("subjects", request), SubjectSearchResponse)
|
|
120
|
+
|
|
121
|
+
def search_actions(self, request: ActionSearchRequest) -> ActionSearchResponse:
|
|
122
|
+
"""Fetch one page of actions permitted for the subject and resource."""
|
|
123
|
+
return _response_model(self._post("actions", request), ActionSearchResponse)
|
|
124
|
+
|
|
125
|
+
def _iterate[T: SearchRequest, R: Subject | Resource | Action](
|
|
126
|
+
self,
|
|
127
|
+
request: T,
|
|
128
|
+
search: Callable[[T], SearchResponse[R]],
|
|
129
|
+
) -> Iterator[R]:
|
|
130
|
+
current: T | None
|
|
131
|
+
current, seen = _page_state(request)
|
|
132
|
+
while current is not None:
|
|
133
|
+
response = search(current)
|
|
134
|
+
yield from response.results
|
|
135
|
+
current = _next_request(current, response.page, seen)
|
|
136
|
+
|
|
137
|
+
def iter_resources(self, request: ResourceSearchRequest) -> Iterator[Resource]:
|
|
138
|
+
"""Lazily yield resources across pages without changing the input request."""
|
|
139
|
+
return self._iterate(request, self.search_resources)
|
|
140
|
+
|
|
141
|
+
def iter_subjects(self, request: SubjectSearchRequest) -> Iterator[Subject]:
|
|
142
|
+
"""Lazily yield subjects across pages."""
|
|
143
|
+
return self._iterate(request, self.search_subjects)
|
|
144
|
+
|
|
145
|
+
def iter_actions(self, request: ActionSearchRequest) -> Iterator[Action]:
|
|
146
|
+
"""Lazily yield actions across pages."""
|
|
147
|
+
return self._iterate(request, self.search_actions)
|
|
148
|
+
|
|
149
|
+
def close(self) -> None:
|
|
150
|
+
"""Close the HTTP client this library opened. A passed http_client stays open."""
|
|
151
|
+
if self._owns_http:
|
|
152
|
+
self._http.close()
|
|
153
|
+
|
|
154
|
+
def __enter__(self) -> Self:
|
|
155
|
+
"""Enter the owned HTTP client context."""
|
|
156
|
+
if self._owns_http:
|
|
157
|
+
self._http.__enter__()
|
|
158
|
+
return self
|
|
159
|
+
|
|
160
|
+
def __exit__(
|
|
161
|
+
self,
|
|
162
|
+
exc_type: type[BaseException] | None,
|
|
163
|
+
exc_value: BaseException | None,
|
|
164
|
+
traceback: TracebackType | None,
|
|
165
|
+
) -> None:
|
|
166
|
+
"""Release owned HTTP resources on leaving the context."""
|
|
167
|
+
self.close()
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Errors raised while communicating with an AuthZEN PDP."""
|
|
2
|
+
|
|
3
|
+
import httpx2
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AuthZENError(Exception):
|
|
7
|
+
"""Base exception for AuthZEN client failures."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TransportError(AuthZENError):
|
|
11
|
+
"""A request to the PDP or token service failed at the HTTP transport layer."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ProtocolError(AuthZENError):
|
|
15
|
+
"""An HTTP or response error from the PDP or token service.
|
|
16
|
+
|
|
17
|
+
The ``response`` attribute contains the HTTP response when available.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self, message: str, *, response: httpx2.Response | None = None
|
|
22
|
+
) -> None:
|
|
23
|
+
self.response = response
|
|
24
|
+
super().__init__(message)
|
authzen_client/models.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Models for AuthZEN single access evaluations.
|
|
2
|
+
|
|
3
|
+
Unknown protocol fields are ignored. Keys inside properties and context are kept.
|
|
4
|
+
Optional objects default to empty objects. Use ``exclude_defaults=True`` when
|
|
5
|
+
dumping to omit them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Annotated, Literal, Self
|
|
9
|
+
|
|
10
|
+
from pydantic import (
|
|
11
|
+
BaseModel,
|
|
12
|
+
ConfigDict,
|
|
13
|
+
Field,
|
|
14
|
+
HttpUrl,
|
|
15
|
+
RootModel,
|
|
16
|
+
TypeAdapter,
|
|
17
|
+
ValidationInfo,
|
|
18
|
+
field_validator,
|
|
19
|
+
model_validator,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
from authzen_client.types import JsonObject, JsonValue
|
|
23
|
+
|
|
24
|
+
_JSON_CONFIG = ConfigDict(strict=True, allow_inf_nan=False)
|
|
25
|
+
_MODEL_CONFIG: ConfigDict = {**_JSON_CONFIG, "extra": "ignore"}
|
|
26
|
+
_JSON_VALUE = TypeAdapter(JsonValue, config=_JSON_CONFIG)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Context(RootModel[JsonObject]):
|
|
30
|
+
"""Environment or enforcement data serialized as a plain JSON object.
|
|
31
|
+
|
|
32
|
+
Access the underlying dictionary through ``root``. The PEP and PDP define
|
|
33
|
+
the meaning of its keys.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
model_config = _JSON_CONFIG
|
|
37
|
+
|
|
38
|
+
root: JsonObject = Field(default_factory=dict)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Subject(BaseModel):
|
|
42
|
+
"""A user or machine principal whose id is scoped to its type."""
|
|
43
|
+
|
|
44
|
+
model_config = _MODEL_CONFIG
|
|
45
|
+
|
|
46
|
+
type: str
|
|
47
|
+
id: str
|
|
48
|
+
properties: JsonObject = Field(default_factory=dict)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Resource(BaseModel):
|
|
52
|
+
"""A target resource whose id is scoped to its type."""
|
|
53
|
+
|
|
54
|
+
model_config = _MODEL_CONFIG
|
|
55
|
+
|
|
56
|
+
type: str
|
|
57
|
+
id: str
|
|
58
|
+
properties: JsonObject = Field(default_factory=dict)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Action(BaseModel):
|
|
62
|
+
"""An operation the subject wants to perform, such as read or update."""
|
|
63
|
+
|
|
64
|
+
model_config = _MODEL_CONFIG
|
|
65
|
+
|
|
66
|
+
name: str
|
|
67
|
+
properties: JsonObject = Field(default_factory=dict)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class EvaluationRequest(BaseModel):
|
|
71
|
+
"""A single access check for a subject, action, and resource."""
|
|
72
|
+
|
|
73
|
+
model_config = _MODEL_CONFIG
|
|
74
|
+
|
|
75
|
+
subject: Subject
|
|
76
|
+
action: Action
|
|
77
|
+
resource: Resource
|
|
78
|
+
context: Context = Field(default_factory=Context)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Decision(BaseModel):
|
|
82
|
+
"""The PDP's allow or deny result and optional enforcement context.
|
|
83
|
+
|
|
84
|
+
A false decision is a regular denial result. The PEP interprets any
|
|
85
|
+
additional information in context when enforcing the decision.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
model_config = _MODEL_CONFIG
|
|
89
|
+
|
|
90
|
+
decision: bool
|
|
91
|
+
context: Context = Field(default_factory=Context)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# The single-evaluation response has the same structure as a Decision.
|
|
95
|
+
EvaluationResponse = Decision
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Evaluation(BaseModel):
|
|
99
|
+
"""A batch entry whose omitted entities inherit the request defaults."""
|
|
100
|
+
|
|
101
|
+
model_config = _MODEL_CONFIG
|
|
102
|
+
|
|
103
|
+
subject: Subject | None = None
|
|
104
|
+
action: Action | None = None
|
|
105
|
+
resource: Resource | None = None
|
|
106
|
+
context: Context | None = None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class EvaluationsOptions(BaseModel):
|
|
110
|
+
"""Batch execution semantics. Additional JSON options are kept."""
|
|
111
|
+
|
|
112
|
+
model_config = {**_JSON_CONFIG, "extra": "allow"}
|
|
113
|
+
|
|
114
|
+
evaluations_semantic: Literal[
|
|
115
|
+
"execute_all", "deny_on_first_deny", "permit_on_first_permit"
|
|
116
|
+
] = "execute_all"
|
|
117
|
+
|
|
118
|
+
@model_validator(mode="after")
|
|
119
|
+
def extra_options_are_json(self) -> Self:
|
|
120
|
+
for value in (self.__pydantic_extra__ or {}).values():
|
|
121
|
+
_JSON_VALUE.validate_python(value)
|
|
122
|
+
return self
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class EvaluationsRequest(Evaluation):
|
|
126
|
+
"""Batch evaluations with optional shared defaults and short-circuiting."""
|
|
127
|
+
|
|
128
|
+
evaluations: list[Evaluation] = Field(default_factory=list)
|
|
129
|
+
options: EvaluationsOptions = Field(default_factory=EvaluationsOptions)
|
|
130
|
+
|
|
131
|
+
@model_validator(mode="after")
|
|
132
|
+
def required_entities(self) -> Self:
|
|
133
|
+
for evaluation in self.evaluations or [Evaluation()]:
|
|
134
|
+
for name in ("subject", "action", "resource"):
|
|
135
|
+
if getattr(evaluation, name) is None and getattr(self, name) is None:
|
|
136
|
+
raise ValueError(f"Each evaluation must provide or inherit {name}.")
|
|
137
|
+
return self
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class EvaluationsResponse(BaseModel):
|
|
141
|
+
"""Ordered batch decisions, or a single decision for the fallback request."""
|
|
142
|
+
|
|
143
|
+
model_config = _MODEL_CONFIG
|
|
144
|
+
|
|
145
|
+
evaluations: list[Decision] | None = None
|
|
146
|
+
decision: bool | None = None
|
|
147
|
+
context: Context = Field(default_factory=Context)
|
|
148
|
+
|
|
149
|
+
@model_validator(mode="after")
|
|
150
|
+
def has_result(self) -> Self:
|
|
151
|
+
if self.evaluations is None and self.decision is None:
|
|
152
|
+
raise ValueError("The response must contain evaluations or a decision.")
|
|
153
|
+
return self
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class PageRequest(BaseModel):
|
|
157
|
+
"""Opaque continuation token, result limit and PDP-specific page options."""
|
|
158
|
+
|
|
159
|
+
model_config = _MODEL_CONFIG
|
|
160
|
+
|
|
161
|
+
token: str | None = None
|
|
162
|
+
limit: Annotated[int, Field(ge=0)] | None = None
|
|
163
|
+
properties: JsonObject = Field(default_factory=dict)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class PageResponse(BaseModel):
|
|
167
|
+
"""Pagination metadata. An empty next_token marks the last page."""
|
|
168
|
+
|
|
169
|
+
model_config = _MODEL_CONFIG
|
|
170
|
+
|
|
171
|
+
next_token: str
|
|
172
|
+
count: Annotated[int, Field(ge=0)] | None = None
|
|
173
|
+
total: Annotated[int, Field(ge=0)] | None = None
|
|
174
|
+
properties: JsonObject = Field(default_factory=dict)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class SubjectQuery(BaseModel):
|
|
178
|
+
"""Subject type and properties to search. The PDP ignores any supplied id."""
|
|
179
|
+
|
|
180
|
+
model_config = _MODEL_CONFIG
|
|
181
|
+
|
|
182
|
+
type: str
|
|
183
|
+
id: str | None = None
|
|
184
|
+
properties: JsonObject = Field(default_factory=dict)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class ResourceQuery(BaseModel):
|
|
188
|
+
"""Resource type and properties to search. The PDP ignores any supplied id."""
|
|
189
|
+
|
|
190
|
+
model_config = _MODEL_CONFIG
|
|
191
|
+
|
|
192
|
+
type: str
|
|
193
|
+
id: str | None = None
|
|
194
|
+
properties: JsonObject = Field(default_factory=dict)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class SearchRequest(BaseModel):
|
|
198
|
+
"""Context and pagination shared by the three search request models."""
|
|
199
|
+
|
|
200
|
+
model_config = _MODEL_CONFIG
|
|
201
|
+
|
|
202
|
+
context: Context = Field(default_factory=Context)
|
|
203
|
+
page: PageRequest | None = None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class SubjectSearchRequest(SearchRequest):
|
|
207
|
+
"""Find subjects permitted to perform an action on a resource."""
|
|
208
|
+
|
|
209
|
+
subject: SubjectQuery
|
|
210
|
+
action: Action
|
|
211
|
+
resource: Resource
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class ResourceSearchRequest(SearchRequest):
|
|
215
|
+
"""Find resources a subject may access with the given action."""
|
|
216
|
+
|
|
217
|
+
subject: Subject
|
|
218
|
+
action: Action
|
|
219
|
+
resource: ResourceQuery
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class ActionSearchRequest(SearchRequest):
|
|
223
|
+
"""Find actions a subject may perform on a resource."""
|
|
224
|
+
|
|
225
|
+
subject: Subject
|
|
226
|
+
resource: Resource
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class SearchResponse[T: Subject | Resource | Action](BaseModel):
|
|
230
|
+
"""A page of authorized entities and optional response context."""
|
|
231
|
+
|
|
232
|
+
model_config = _MODEL_CONFIG
|
|
233
|
+
|
|
234
|
+
results: list[T]
|
|
235
|
+
page: PageResponse | None = None
|
|
236
|
+
context: Context = Field(default_factory=Context)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
SubjectSearchResponse = SearchResponse[Subject]
|
|
240
|
+
ResourceSearchResponse = SearchResponse[Resource]
|
|
241
|
+
ActionSearchResponse = SearchResponse[Action]
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class PDPMetadata(BaseModel):
|
|
245
|
+
"""Unsigned PDP metadata for locating the single-evaluation endpoint."""
|
|
246
|
+
|
|
247
|
+
model_config = _MODEL_CONFIG
|
|
248
|
+
|
|
249
|
+
policy_decision_point: str
|
|
250
|
+
access_evaluation_endpoint: str
|
|
251
|
+
access_evaluations_endpoint: str | None = None
|
|
252
|
+
search_subject_endpoint: str | None = None
|
|
253
|
+
search_resource_endpoint: str | None = None
|
|
254
|
+
search_action_endpoint: str | None = None
|
|
255
|
+
supported_capabilities: list[str] = Field(default_factory=list)
|
|
256
|
+
|
|
257
|
+
@field_validator(
|
|
258
|
+
"policy_decision_point",
|
|
259
|
+
"access_evaluation_endpoint",
|
|
260
|
+
"access_evaluations_endpoint",
|
|
261
|
+
"search_subject_endpoint",
|
|
262
|
+
"search_resource_endpoint",
|
|
263
|
+
"search_action_endpoint",
|
|
264
|
+
)
|
|
265
|
+
@classmethod
|
|
266
|
+
def https_url(cls, value: str | None, info: ValidationInfo) -> str | None:
|
|
267
|
+
if value is None:
|
|
268
|
+
return None
|
|
269
|
+
url = HttpUrl(value)
|
|
270
|
+
if url.scheme != "https" or url.fragment not in (None, ""):
|
|
271
|
+
raise ValueError("PDP metadata URLs must use HTTPS without a fragment.")
|
|
272
|
+
if info.field_name == "policy_decision_point" and url.query not in (None, ""):
|
|
273
|
+
raise ValueError("The PDP identifier must not contain a query.")
|
|
274
|
+
return value
|
authzen_client/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Per-client endpoint defaults from the AuthZEN HTTPS binding."""
|
|
2
|
+
|
|
3
|
+
import httpx2
|
|
4
|
+
from pydantic import BaseModel, ConfigDict, field_validator
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Endpoints(BaseModel):
|
|
8
|
+
"""Fallback endpoint paths or HTTPS URLs, overridden by discovery."""
|
|
9
|
+
|
|
10
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
11
|
+
|
|
12
|
+
evaluation: str = "/access/v1/evaluation"
|
|
13
|
+
evaluations: str = "/access/v1/evaluations"
|
|
14
|
+
subjects: str = "/access/v1/search/subject"
|
|
15
|
+
resources: str = "/access/v1/search/resource"
|
|
16
|
+
actions: str = "/access/v1/search/action"
|
|
17
|
+
|
|
18
|
+
@field_validator("*")
|
|
19
|
+
@classmethod
|
|
20
|
+
def endpoint_url(cls, value: str) -> str:
|
|
21
|
+
url = httpx2.URL(value)
|
|
22
|
+
if url.fragment or value.startswith("//"):
|
|
23
|
+
raise ValueError(
|
|
24
|
+
"Endpoints must not contain a fragment or authority-only URL."
|
|
25
|
+
)
|
|
26
|
+
if url.is_absolute_url:
|
|
27
|
+
if url.scheme != "https" or not url.host:
|
|
28
|
+
raise ValueError("Absolute endpoints must use HTTPS.")
|
|
29
|
+
elif not value.startswith("/"):
|
|
30
|
+
raise ValueError("Relative endpoints must start with /.")
|
|
31
|
+
return value
|
authzen_client/types.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: authzen-client
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A typed Python client for the AuthZEN Authorization API.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/kapustazh/authzen-client
|
|
7
|
+
Project-URL: Documentation, https://github.com/kapustazh/authzen-client/tree/main/docs
|
|
8
|
+
Project-URL: Issues, https://github.com/kapustazh/authzen-client/issues
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: httpx2<3,>=2.16.2
|
|
13
|
+
Requires-Dist: pydantic<3,>=2
|
|
14
|
+
Provides-Extra: oauth
|
|
15
|
+
Requires-Dist: authlib<2,>=1.9.8; extra == "oauth"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# authzen-client
|
|
19
|
+
|
|
20
|
+
A typed Python SDK for the [AuthZEN Authorization API](https://openid.net/specs/authorization-api-1_0.html).
|
|
21
|
+
Supports sync and async evaluation, batch requests, paginated search, discovery,
|
|
22
|
+
and authentication through HTTPX2 and Authlib.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
Requires Python 3.12+. Install from a checkout in your application's environment.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
git clone https://github.com/kapustazh/authzen-client.git
|
|
30
|
+
cd authzen-client
|
|
31
|
+
python -m pip install .
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
For OAuth Client Credentials, install the optional integration.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
python -m pip install '.[oauth]'
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Quickstart
|
|
41
|
+
|
|
42
|
+
Pass the PDP's HTTPS base URL and apply its decision in your application.
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from authzen_client import Action, AuthZENClient, EvaluationRequest, Resource, Subject
|
|
46
|
+
|
|
47
|
+
request = EvaluationRequest(
|
|
48
|
+
subject=Subject(type="user", id="alice"),
|
|
49
|
+
action=Action(name="read"),
|
|
50
|
+
resource=Resource(type="document", id="123"),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
with AuthZENClient(base_url="https://pdp.example.com") as client:
|
|
54
|
+
response = client.evaluate(request)
|
|
55
|
+
|
|
56
|
+
if response.decision:
|
|
57
|
+
print("Access granted")
|
|
58
|
+
else:
|
|
59
|
+
print("Access denied")
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Run the bundled document-service example against an in-process PDP.
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
uv sync
|
|
66
|
+
uv run python -m examples.evaluate
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
```text
|
|
70
|
+
alice: AuthZEN project notes
|
|
71
|
+
bob: access denied
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Documentation
|
|
75
|
+
|
|
76
|
+
- [Quickstart and runnable examples](docs/quickstart.md)
|
|
77
|
+
- [Sync and async clients](docs/clients.md)
|
|
78
|
+
- [Batch evaluations](docs/batch.md)
|
|
79
|
+
- [Search and pagination](docs/search.md)
|
|
80
|
+
- [Authentication](docs/authentication.md)
|
|
81
|
+
- [Configuration and discovery](docs/configuration.md)
|
|
82
|
+
- [Errors](docs/errors.md)
|
|
83
|
+
- [API reference](docs/api.md)
|
|
84
|
+
- [Migrating from 0.1](docs/migration.md)
|
|
85
|
+
- [Development and builds](docs/development.md)
|
|
86
|
+
|
|
87
|
+
## License
|
|
88
|
+
|
|
89
|
+
[MIT](LICENSE).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
authzen_client/__init__.py,sha256=8HBfvQ4lD8LQGenu-1tBwP4pcCUMmILvgO0ZXEvFuYM,1455
|
|
2
|
+
authzen_client/_client.py,sha256=BPoLuZkWomWUoE7rv0Dc1AK1eTUepuzAgeJds7Kweo0,6623
|
|
3
|
+
authzen_client/async_client.py,sha256=IiKayJ-BhbTpg7ir2zVO4Md89WGsLvZCp-T_SFkKB7U,6436
|
|
4
|
+
authzen_client/client.py,sha256=F8gCWqB6PbO2VTIQsK-J9_eA_Mf5VGlxqMcsy-IU9LI,6168
|
|
5
|
+
authzen_client/exceptions.py,sha256=Vy9tHfdpaELE0FFAfYOrdg-lfHdV6mSrlVvNWizsWOI,641
|
|
6
|
+
authzen_client/models.py,sha256=EeQSRmqYYx6lyw9aPkf14KnkHKG7ND4jYsum38M-PMI,7849
|
|
7
|
+
authzen_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
authzen_client/settings.py,sha256=6IHQqmdr-oeM0_jEmpgZAX2iJj79X2rV92em71iuTts,1142
|
|
9
|
+
authzen_client/types.py,sha256=ddJOlR6xwW13ey5JEWBwMPrJnzXidAuCK6ApwHwD4pg,132
|
|
10
|
+
authzen_client-0.2.0.dist-info/licenses/LICENSE,sha256=4zUl9tmiDdryu_eUDtISU5ZID4KvShzG73ySvxmOo54,1074
|
|
11
|
+
authzen_client-0.2.0.dist-info/METADATA,sha256=pZ-se3nWgrZ-jFxnWt6sQmtwbmBQNyPN4NK_phdCzpE,2403
|
|
12
|
+
authzen_client-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
authzen_client-0.2.0.dist-info/top_level.txt,sha256=UYwG_dtXbn-B3Zy5RUqiFHADZ7TlHTaqIUHRTCzepZQ,15
|
|
14
|
+
authzen_client-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matvii Nesterenko
|
|
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 @@
|
|
|
1
|
+
authzen_client
|