pytest-authz-matrix 0.2.0__tar.gz → 0.3.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.
- {pytest_authz_matrix-0.2.0/src/pytest_authz_matrix.egg-info → pytest_authz_matrix-0.3.0}/PKG-INFO +18 -1
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/README.md +17 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/pyproject.toml +1 -1
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/__init__.py +1 -1
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/fastapi.py +29 -22
- pytest_authz_matrix-0.3.0/src/pytest_authz_matrix/fastapi.py +187 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0/src/pytest_authz_matrix.egg-info}/PKG-INFO +18 -1
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix.egg-info/SOURCES.txt +2 -0
- pytest_authz_matrix-0.3.0/tests/test_fastapi_defaults.py +130 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/LICENSE +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/MANIFEST.in +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/setup.cfg +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/__init__.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/base.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/django.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/generic.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/registry.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/case.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/config.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/discovery.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/exceptions.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/models.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/plugin.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/py.typed +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/reporting.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/templating.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix.egg-info/dependency_links.txt +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix.egg-info/entry_points.txt +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix.egg-info/requires.txt +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix.egg-info/top_level.txt +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/conftest.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_adapter_registry.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_case.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_config.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_discovery.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_django_adapter.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_fastapi_adapter.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_fastapi_case.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_fastapi_plugin.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_plugin.py +0 -0
- {pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/tests/test_reporting.py +0 -0
{pytest_authz_matrix-0.2.0/src/pytest_authz_matrix.egg-info → pytest_authz_matrix-0.3.0}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pytest-authz-matrix
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Authorization contract testing for Python web APIs
|
|
5
5
|
Author: Aleshinloye Olamilekan
|
|
6
6
|
License-Expression: MIT
|
|
@@ -153,6 +153,23 @@ The DRF adapter preserves the existing `data=...`, `format=...`, and Django URL-
|
|
|
153
153
|
|
|
154
154
|
## FastAPI
|
|
155
155
|
|
|
156
|
+
Add one pytest test to check required FastAPI security dependencies automatically:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from pytest_authz_matrix.fastapi import check_fastapi
|
|
160
|
+
|
|
161
|
+
from app.main import app
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def test_authorization():
|
|
165
|
+
check_fastapi(app)
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
No YAML setup is required. See the [FastAPI guide](https://github.com/Leanstix/pytest-authz-matrix/blob/main/docs/fastapi.md)
|
|
169
|
+
for permission defaults and Python overrides.
|
|
170
|
+
|
|
171
|
+
### YAML contracts
|
|
172
|
+
|
|
156
173
|
Actor fixtures return FastAPI/Starlette `TestClient` instances:
|
|
157
174
|
|
|
158
175
|
```python
|
|
@@ -110,6 +110,23 @@ The DRF adapter preserves the existing `data=...`, `format=...`, and Django URL-
|
|
|
110
110
|
|
|
111
111
|
## FastAPI
|
|
112
112
|
|
|
113
|
+
Add one pytest test to check required FastAPI security dependencies automatically:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from pytest_authz_matrix.fastapi import check_fastapi
|
|
117
|
+
|
|
118
|
+
from app.main import app
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def test_authorization():
|
|
122
|
+
check_fastapi(app)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
No YAML setup is required. See the [FastAPI guide](https://github.com/Leanstix/pytest-authz-matrix/blob/main/docs/fastapi.md)
|
|
126
|
+
for permission defaults and Python overrides.
|
|
127
|
+
|
|
128
|
+
### YAML contracts
|
|
129
|
+
|
|
113
130
|
Actor fixtures return FastAPI/Starlette `TestClient` instances:
|
|
114
131
|
|
|
115
132
|
```python
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/fastapi.py
RENAMED
|
@@ -71,8 +71,7 @@ class FastAPIAdapter:
|
|
|
71
71
|
reason=f"object {type(app).__name__!r} is not a FastAPI application",
|
|
72
72
|
)
|
|
73
73
|
try:
|
|
74
|
-
|
|
75
|
-
from starlette.routing import Mount
|
|
74
|
+
routes = {route for route, _ in iter_fastapi_routes(app)}
|
|
76
75
|
except ImportError:
|
|
77
76
|
return DiscoveryResult(
|
|
78
77
|
False,
|
|
@@ -80,26 +79,6 @@ class FastAPIAdapter:
|
|
|
80
79
|
reason="FastAPI is not installed",
|
|
81
80
|
)
|
|
82
81
|
|
|
83
|
-
def walk(
|
|
84
|
-
registered: Sequence[Any], prefix: str = "", namespace: str = ""
|
|
85
|
-
) -> Iterator[DiscoveredRoute]:
|
|
86
|
-
for original, effective in _route_contexts(routing, registered):
|
|
87
|
-
if isinstance(original, Mount):
|
|
88
|
-
mount = getattr(effective, "starlette_route", None) or effective
|
|
89
|
-
yield from walk(
|
|
90
|
-
original.routes,
|
|
91
|
-
prefix + mount.path,
|
|
92
|
-
namespace + (f"{original.name}:" if original.name else ""),
|
|
93
|
-
)
|
|
94
|
-
elif isinstance(original, routing.APIRoute):
|
|
95
|
-
for method in effective.methods or ():
|
|
96
|
-
yield DiscoveredRoute(
|
|
97
|
-
method=method.upper(),
|
|
98
|
-
name=namespace + effective.name,
|
|
99
|
-
pattern=prefix + effective.path,
|
|
100
|
-
)
|
|
101
|
-
|
|
102
|
-
routes = set(walk(app.routes))
|
|
103
82
|
return DiscoveryResult(
|
|
104
83
|
True,
|
|
105
84
|
framework=self.name,
|
|
@@ -107,6 +86,34 @@ class FastAPIAdapter:
|
|
|
107
86
|
)
|
|
108
87
|
|
|
109
88
|
|
|
89
|
+
def iter_fastapi_routes(app: Any) -> Iterator[tuple[DiscoveredRoute, Any]]:
|
|
90
|
+
"""Yield effective HTTP routes with their dependency metadata."""
|
|
91
|
+
from fastapi import routing
|
|
92
|
+
from starlette.routing import Mount
|
|
93
|
+
|
|
94
|
+
def walk(
|
|
95
|
+
registered: Sequence[Any], prefix: str = "", namespace: str = ""
|
|
96
|
+
) -> Iterator[tuple[DiscoveredRoute, Any]]:
|
|
97
|
+
for original, effective in _route_contexts(routing, registered):
|
|
98
|
+
if isinstance(original, Mount):
|
|
99
|
+
mount = getattr(effective, "starlette_route", None) or effective
|
|
100
|
+
yield from walk(
|
|
101
|
+
original.routes,
|
|
102
|
+
prefix + mount.path,
|
|
103
|
+
namespace + (f"{original.name}:" if original.name else ""),
|
|
104
|
+
)
|
|
105
|
+
elif isinstance(original, routing.APIRoute):
|
|
106
|
+
for method in sorted(effective.methods or ()):
|
|
107
|
+
route = DiscoveredRoute(
|
|
108
|
+
method=method.upper(),
|
|
109
|
+
name=namespace + effective.name,
|
|
110
|
+
pattern=prefix + effective.path,
|
|
111
|
+
)
|
|
112
|
+
yield route, effective.dependant
|
|
113
|
+
|
|
114
|
+
yield from walk(app.routes)
|
|
115
|
+
|
|
116
|
+
|
|
110
117
|
def _route_contexts(
|
|
111
118
|
routing: Any, routes: Sequence[Any]
|
|
112
119
|
) -> Iterator[tuple[Any, Any]]:
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Run FastAPI authorization checks directly from Python."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Mapping
|
|
6
|
+
from contextlib import ExitStack
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from typing import Any, Protocol
|
|
10
|
+
from urllib.parse import urlsplit
|
|
11
|
+
|
|
12
|
+
from pytest_authz_matrix.adapters.fastapi import FastAPIAdapter, iter_fastapi_routes
|
|
13
|
+
from pytest_authz_matrix.exceptions import AuthzConfigurationError
|
|
14
|
+
|
|
15
|
+
RouteKey = tuple[str, str]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Permission(str, Enum):
|
|
19
|
+
"""Expected access outcome for one actor."""
|
|
20
|
+
|
|
21
|
+
PUBLIC = "public"
|
|
22
|
+
AUTHENTICATED = "authenticated"
|
|
23
|
+
FORBIDDEN = "forbidden"
|
|
24
|
+
CONCEALED = "concealed"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_EXPECTED: Mapping[Permission, Iterable[int]] = {
|
|
28
|
+
Permission.PUBLIC: range(200, 300),
|
|
29
|
+
Permission.AUTHENTICATED: (401, 403),
|
|
30
|
+
Permission.FORBIDDEN: (403,),
|
|
31
|
+
Permission.CONCEALED: (404,),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _ActorClient(Protocol):
|
|
36
|
+
def request(self, method: str, url: str, **kwargs: Any) -> Any: ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class FastAPICheckResult:
|
|
41
|
+
"""Number of checks performed and any route that still needs test input."""
|
|
42
|
+
|
|
43
|
+
checked: int
|
|
44
|
+
unclassified: tuple[RouteKey, ...]
|
|
45
|
+
needs_path: tuple[RouteKey, ...]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def check_fastapi(
|
|
49
|
+
app: Any,
|
|
50
|
+
*,
|
|
51
|
+
permissions: Mapping[RouteKey, Permission | int | Mapping[str, Permission | int]] | None = None,
|
|
52
|
+
actors: Mapping[str, _ActorClient] | None = None,
|
|
53
|
+
paths: Mapping[RouteKey, str] | None = None,
|
|
54
|
+
payloads: Mapping[RouteKey, Any] | None = None,
|
|
55
|
+
) -> FastAPICheckResult:
|
|
56
|
+
"""Assert the access expectations of explicitly configured and recognized routes.
|
|
57
|
+
|
|
58
|
+
The default anonymous actor has no credentials. Built-in required security
|
|
59
|
+
dependencies imply an anonymous rejection. Custom policies can declare
|
|
60
|
+
expected outcomes for any supplied actor client.
|
|
61
|
+
"""
|
|
62
|
+
if not FastAPIAdapter().supports_app(app):
|
|
63
|
+
raise AuthzConfigurationError("check_fastapi() requires a FastAPI application")
|
|
64
|
+
|
|
65
|
+
from fastapi.testclient import TestClient
|
|
66
|
+
from starlette.routing import compile_path
|
|
67
|
+
|
|
68
|
+
policies = permissions or {}
|
|
69
|
+
clients = dict(actors or {})
|
|
70
|
+
route_paths = paths or {}
|
|
71
|
+
bodies = payloads or {}
|
|
72
|
+
routes: dict[RouteKey, Any] = {}
|
|
73
|
+
for route, dependant in iter_fastapi_routes(app):
|
|
74
|
+
routes.setdefault((route.method, route.pattern), dependant)
|
|
75
|
+
|
|
76
|
+
unknown = (policies.keys() | route_paths.keys() | bodies.keys()) - routes.keys()
|
|
77
|
+
if unknown:
|
|
78
|
+
raise AuthzConfigurationError(f"Unknown FastAPI routes: {sorted(unknown)!r}")
|
|
79
|
+
|
|
80
|
+
unclassified = []
|
|
81
|
+
needs_path = []
|
|
82
|
+
checks = []
|
|
83
|
+
for key, dependant in routes.items():
|
|
84
|
+
policy = policies.get(key)
|
|
85
|
+
if policy is None:
|
|
86
|
+
if not _requires_credentials(dependant):
|
|
87
|
+
unclassified.append(key)
|
|
88
|
+
continue
|
|
89
|
+
policy = Permission.AUTHENTICATED
|
|
90
|
+
|
|
91
|
+
path = route_paths.get(key, key[1])
|
|
92
|
+
if key not in route_paths and "{" in path:
|
|
93
|
+
if key in policies:
|
|
94
|
+
raise AuthzConfigurationError(f"Provide a concrete test path for {key!r}")
|
|
95
|
+
needs_path.append(key)
|
|
96
|
+
continue
|
|
97
|
+
url = urlsplit(path)
|
|
98
|
+
pattern, _, _ = compile_path(key[1])
|
|
99
|
+
if (
|
|
100
|
+
not path.startswith("/")
|
|
101
|
+
or path.startswith("//")
|
|
102
|
+
or url.scheme
|
|
103
|
+
or url.netloc
|
|
104
|
+
or url.fragment
|
|
105
|
+
or not pattern.fullmatch(url.path)
|
|
106
|
+
):
|
|
107
|
+
raise AuthzConfigurationError(f"Test path {path!r} does not match {key[1]!r}")
|
|
108
|
+
|
|
109
|
+
expectations = policy if isinstance(policy, Mapping) else {"anonymous": policy}
|
|
110
|
+
if not expectations:
|
|
111
|
+
raise AuthzConfigurationError(f"Empty permission policy for {key[0]} {key[1]}")
|
|
112
|
+
for actor, expectation in expectations.items():
|
|
113
|
+
if actor != "anonymous" and actor not in clients:
|
|
114
|
+
raise AuthzConfigurationError(f"No test client supplied for actor {actor!r}")
|
|
115
|
+
if type(expectation) is int and 100 <= expectation <= 599:
|
|
116
|
+
statuses: Iterable[int] = (expectation,)
|
|
117
|
+
elif isinstance(expectation, Permission):
|
|
118
|
+
statuses = _EXPECTED[expectation]
|
|
119
|
+
else:
|
|
120
|
+
raise AuthzConfigurationError(f"Invalid permission expectation: {expectation!r}")
|
|
121
|
+
checks.append((key, path, actor, expectation, statuses))
|
|
122
|
+
|
|
123
|
+
if not checks:
|
|
124
|
+
raise AuthzConfigurationError(
|
|
125
|
+
"No FastAPI authorization checks were generated. "
|
|
126
|
+
f"Unclassified routes: {unclassified!r}. Routes needing paths: {needs_path!r}."
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
with ExitStack() as stack:
|
|
130
|
+
anonymous = None
|
|
131
|
+
if "anonymous" not in clients and any(case[2] == "anonymous" for case in checks):
|
|
132
|
+
anonymous = stack.enter_context(TestClient(app))
|
|
133
|
+
clients["anonymous"] = anonymous
|
|
134
|
+
|
|
135
|
+
failures = []
|
|
136
|
+
for key, path, actor, expectation, statuses in checks:
|
|
137
|
+
if actor == "anonymous" and anonymous is not None:
|
|
138
|
+
anonymous.cookies.clear()
|
|
139
|
+
request_options = {"json": bodies[key]} if key in bodies else {}
|
|
140
|
+
response = clients[actor].request(
|
|
141
|
+
key[0], path, follow_redirects=False, **request_options
|
|
142
|
+
)
|
|
143
|
+
if response.status_code not in statuses:
|
|
144
|
+
label = expectation.value if isinstance(expectation, Permission) else expectation
|
|
145
|
+
failures.append(
|
|
146
|
+
f"{key[0]} {path} ({actor}): expected {label}, got HTTP {response.status_code}"
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
if failures:
|
|
150
|
+
raise AssertionError("FastAPI authorization checks failed:\n" + "\n".join(failures))
|
|
151
|
+
return FastAPICheckResult(len(checks), tuple(unclassified), tuple(needs_path))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _requires_credentials(dependant: Any) -> bool:
|
|
155
|
+
from fastapi.security import (
|
|
156
|
+
APIKeyCookie,
|
|
157
|
+
APIKeyHeader,
|
|
158
|
+
APIKeyQuery,
|
|
159
|
+
HTTPBasic,
|
|
160
|
+
HTTPBearer,
|
|
161
|
+
HTTPDigest,
|
|
162
|
+
OAuth2,
|
|
163
|
+
OAuth2AuthorizationCodeBearer,
|
|
164
|
+
OAuth2PasswordBearer,
|
|
165
|
+
OpenIdConnect,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
security_types = {
|
|
169
|
+
APIKeyCookie,
|
|
170
|
+
APIKeyHeader,
|
|
171
|
+
APIKeyQuery,
|
|
172
|
+
HTTPBasic,
|
|
173
|
+
HTTPBearer,
|
|
174
|
+
HTTPDigest,
|
|
175
|
+
OAuth2,
|
|
176
|
+
OAuth2AuthorizationCodeBearer,
|
|
177
|
+
OAuth2PasswordBearer,
|
|
178
|
+
OpenIdConnect,
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
def required(node: Any) -> bool:
|
|
182
|
+
call = node.call
|
|
183
|
+
return (type(call) in security_types and bool(call.auto_error)) or any(
|
|
184
|
+
required(child) for child in node.dependencies
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
return required(dependant)
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0/src/pytest_authz_matrix.egg-info}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pytest-authz-matrix
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Authorization contract testing for Python web APIs
|
|
5
5
|
Author: Aleshinloye Olamilekan
|
|
6
6
|
License-Expression: MIT
|
|
@@ -153,6 +153,23 @@ The DRF adapter preserves the existing `data=...`, `format=...`, and Django URL-
|
|
|
153
153
|
|
|
154
154
|
## FastAPI
|
|
155
155
|
|
|
156
|
+
Add one pytest test to check required FastAPI security dependencies automatically:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from pytest_authz_matrix.fastapi import check_fastapi
|
|
160
|
+
|
|
161
|
+
from app.main import app
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def test_authorization():
|
|
165
|
+
check_fastapi(app)
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
No YAML setup is required. See the [FastAPI guide](https://github.com/Leanstix/pytest-authz-matrix/blob/main/docs/fastapi.md)
|
|
169
|
+
for permission defaults and Python overrides.
|
|
170
|
+
|
|
171
|
+
### YAML contracts
|
|
172
|
+
|
|
156
173
|
Actor fixtures return FastAPI/Starlette `TestClient` instances:
|
|
157
174
|
|
|
158
175
|
```python
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix.egg-info/SOURCES.txt
RENAMED
|
@@ -7,6 +7,7 @@ src/pytest_authz_matrix/case.py
|
|
|
7
7
|
src/pytest_authz_matrix/config.py
|
|
8
8
|
src/pytest_authz_matrix/discovery.py
|
|
9
9
|
src/pytest_authz_matrix/exceptions.py
|
|
10
|
+
src/pytest_authz_matrix/fastapi.py
|
|
10
11
|
src/pytest_authz_matrix/models.py
|
|
11
12
|
src/pytest_authz_matrix/plugin.py
|
|
12
13
|
src/pytest_authz_matrix/py.typed
|
|
@@ -32,6 +33,7 @@ tests/test_discovery.py
|
|
|
32
33
|
tests/test_django_adapter.py
|
|
33
34
|
tests/test_fastapi_adapter.py
|
|
34
35
|
tests/test_fastapi_case.py
|
|
36
|
+
tests/test_fastapi_defaults.py
|
|
35
37
|
tests/test_fastapi_plugin.py
|
|
36
38
|
tests/test_plugin.py
|
|
37
39
|
tests/test_reporting.py
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
from typing import Annotated
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from fastapi import APIRouter, Depends, FastAPI, HTTPException
|
|
5
|
+
from fastapi.responses import RedirectResponse
|
|
6
|
+
from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer
|
|
7
|
+
from fastapi.testclient import TestClient
|
|
8
|
+
|
|
9
|
+
from pytest_authz_matrix.exceptions import AuthzConfigurationError
|
|
10
|
+
from pytest_authz_matrix.fastapi import Permission, check_fastapi
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_infers_required_security_in_nested_routers_and_mounts() -> None:
|
|
14
|
+
app = FastAPI(openapi_url=None)
|
|
15
|
+
router = APIRouter()
|
|
16
|
+
bearer = HTTPBearer()
|
|
17
|
+
|
|
18
|
+
def authorize(credentials: Annotated[HTTPAuthorizationCredentials, Depends(bearer)]):
|
|
19
|
+
return credentials
|
|
20
|
+
|
|
21
|
+
@router.get("/secret", dependencies=[Depends(authorize)], include_in_schema=False)
|
|
22
|
+
def secret():
|
|
23
|
+
raise AssertionError("Anonymous request reached a protected endpoint")
|
|
24
|
+
|
|
25
|
+
@router.get("/records/{record_id}", dependencies=[Depends(bearer)])
|
|
26
|
+
def record(record_id: int):
|
|
27
|
+
return {"id": record_id}
|
|
28
|
+
|
|
29
|
+
@router.get("/optional", dependencies=[Depends(HTTPBearer(auto_error=False))])
|
|
30
|
+
def optional():
|
|
31
|
+
raise AssertionError("Unknown permissions must not be assumed public")
|
|
32
|
+
|
|
33
|
+
child = FastAPI()
|
|
34
|
+
child.include_router(router, prefix="/v1")
|
|
35
|
+
app.mount("/admin", child)
|
|
36
|
+
result = check_fastapi(app)
|
|
37
|
+
|
|
38
|
+
assert result.checked == 1
|
|
39
|
+
assert result.unclassified == (("GET", "/admin/v1/optional"),)
|
|
40
|
+
assert result.needs_path == (("GET", "/admin/v1/records/{record_id}"),)
|
|
41
|
+
result = check_fastapi(
|
|
42
|
+
app, paths={("GET", "/admin/v1/records/{record_id}"): "/admin/v1/records/42"}
|
|
43
|
+
)
|
|
44
|
+
assert result.checked == 2
|
|
45
|
+
assert result.needs_path == ()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_detects_when_an_inferred_authentication_gate_accepts_anonymous() -> None:
|
|
49
|
+
app = FastAPI()
|
|
50
|
+
bearer = HTTPBearer()
|
|
51
|
+
|
|
52
|
+
@app.get("/secret", dependencies=[Depends(bearer)])
|
|
53
|
+
def secret():
|
|
54
|
+
return {"status": "ok"}
|
|
55
|
+
|
|
56
|
+
app.dependency_overrides[bearer] = lambda: None
|
|
57
|
+
with pytest.raises(AssertionError, match=r"GET /secret \(anonymous\).*HTTP 200"):
|
|
58
|
+
check_fastapi(app)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_custom_permissions_cover_anonymous_and_application_roles() -> None:
|
|
62
|
+
app = FastAPI()
|
|
63
|
+
api_key = APIKeyHeader(name="X-Role", auto_error=False)
|
|
64
|
+
|
|
65
|
+
@app.post("/books/{book_id:int}", status_code=201)
|
|
66
|
+
def publish(book_id: int, book: dict[str, str], role: Annotated[str | None, Depends(api_key)]):
|
|
67
|
+
if role is None:
|
|
68
|
+
raise HTTPException(404)
|
|
69
|
+
if role != "editor":
|
|
70
|
+
raise HTTPException(403)
|
|
71
|
+
return {"id": book_id, **book}
|
|
72
|
+
|
|
73
|
+
@app.get("/public")
|
|
74
|
+
def public():
|
|
75
|
+
return {"status": "ok"}
|
|
76
|
+
|
|
77
|
+
key = ("POST", "/books/{book_id:int}")
|
|
78
|
+
with (
|
|
79
|
+
TestClient(app, headers={"X-Role": "editor"}) as editor,
|
|
80
|
+
TestClient(app, headers={"X-Role": "viewer"}) as viewer,
|
|
81
|
+
):
|
|
82
|
+
result = check_fastapi(
|
|
83
|
+
app,
|
|
84
|
+
permissions={
|
|
85
|
+
key: {
|
|
86
|
+
"anonymous": Permission.CONCEALED,
|
|
87
|
+
"viewer": Permission.FORBIDDEN,
|
|
88
|
+
"editor": 201,
|
|
89
|
+
},
|
|
90
|
+
("GET", "/public"): Permission.PUBLIC,
|
|
91
|
+
},
|
|
92
|
+
actors={"editor": editor, "viewer": viewer},
|
|
93
|
+
paths={key: "/books/42"},
|
|
94
|
+
payloads={key: {"title": "Sample"}},
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
assert result.checked == 4
|
|
98
|
+
assert not result.unclassified
|
|
99
|
+
assert not result.needs_path
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_explicit_redirect_status_can_be_checked() -> None:
|
|
103
|
+
app = FastAPI()
|
|
104
|
+
|
|
105
|
+
@app.get("/sign-in")
|
|
106
|
+
def sign_in():
|
|
107
|
+
return RedirectResponse("/landing", status_code=302)
|
|
108
|
+
|
|
109
|
+
assert check_fastapi(app, permissions={("GET", "/sign-in"): 302}).checked == 1
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_unknown_policies_cannot_pass_without_running_checks() -> None:
|
|
113
|
+
app = FastAPI()
|
|
114
|
+
|
|
115
|
+
@app.get("/public")
|
|
116
|
+
def public():
|
|
117
|
+
return {"status": "ok"}
|
|
118
|
+
|
|
119
|
+
with pytest.raises(AuthzConfigurationError, match="No FastAPI authorization checks"):
|
|
120
|
+
check_fastapi(app)
|
|
121
|
+
with pytest.raises(AuthzConfigurationError, match="Unknown FastAPI routes"):
|
|
122
|
+
check_fastapi(app, permissions={("GET", "/missing"): Permission.PUBLIC})
|
|
123
|
+
with pytest.raises(AuthzConfigurationError, match="No test client supplied"):
|
|
124
|
+
check_fastapi(app, permissions={("GET", "/public"): {"editor": Permission.PUBLIC}})
|
|
125
|
+
with pytest.raises(AuthzConfigurationError, match="does not match"):
|
|
126
|
+
check_fastapi(
|
|
127
|
+
app,
|
|
128
|
+
permissions={("GET", "/public"): Permission.PUBLIC},
|
|
129
|
+
paths={("GET", "/public"): "//external.test/public"},
|
|
130
|
+
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/__init__.py
RENAMED
|
File without changes
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/base.py
RENAMED
|
File without changes
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/django.py
RENAMED
|
File without changes
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/generic.py
RENAMED
|
File without changes
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/adapters/registry.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/discovery.py
RENAMED
|
File without changes
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/exceptions.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/reporting.py
RENAMED
|
File without changes
|
{pytest_authz_matrix-0.2.0 → pytest_authz_matrix-0.3.0}/src/pytest_authz_matrix/templating.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|