pytest-authz-matrix 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.
@@ -0,0 +1,7 @@
1
+ """Authorization contract testing for pytest."""
2
+
3
+ from pytest_authz_matrix.case import AuthorizationCase
4
+ from pytest_authz_matrix.exceptions import AuthzConfigurationError
5
+
6
+ __all__ = ["AuthorizationCase", "AuthzConfigurationError"]
7
+ __version__ = "0.1.0"
@@ -0,0 +1,173 @@
1
+ """Runtime API exposed to generated pytest authorization cases."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any, Protocol
7
+ from urllib.parse import urlencode
8
+
9
+ from pytest_authz_matrix.exceptions import AuthzExecutionError
10
+ from pytest_authz_matrix.models import CaseSpec
11
+ from pytest_authz_matrix.templating import related_object, render_path
12
+
13
+ _UNSET = object()
14
+
15
+
16
+ class CaseRecorder(Protocol):
17
+ """Reporting hook implemented by the pytest runtime."""
18
+
19
+ def record_case(self, spec: CaseSpec, *, passed: bool, actual_status: int | None) -> None:
20
+ """Record the result of one case assertion."""
21
+
22
+
23
+ class AuthorizationCase:
24
+ """A generated actor/resource test case.
25
+
26
+ Call :meth:`run` for the standard request-and-assert workflow. Use
27
+ :meth:`execute` and :meth:`assert_response` separately when a test needs to
28
+ inspect the response or application state between those operations.
29
+ """
30
+
31
+ def __init__(self, request: Any, spec: CaseSpec, recorder: CaseRecorder | None = None) -> None:
32
+ self._request = request
33
+ self.spec = spec
34
+ self._recorder = recorder
35
+ self._resource_object: Any = _UNSET
36
+
37
+ @property
38
+ def actor(self) -> str:
39
+ return self.spec.actor.name
40
+
41
+ @property
42
+ def relationship(self) -> str | None:
43
+ return self.spec.relationship
44
+
45
+ @property
46
+ def outcome(self) -> str:
47
+ return self.spec.expectation.outcome
48
+
49
+ @property
50
+ def resource(self) -> Any | None:
51
+ """Resolve and cache the current relationship object."""
52
+
53
+ if self._resource_object is _UNSET:
54
+ if self.spec.resource is None:
55
+ self._resource_object = None
56
+ else:
57
+ container = self._fixture(self.spec.resource.fixture)
58
+ if self.relationship is None:
59
+ raise AuthzExecutionError("Generated resource case has no relationship name")
60
+ self._resource_object = related_object(container, self.relationship)
61
+ return self._resource_object
62
+
63
+ @property
64
+ def path(self) -> str:
65
+ """Return the URL for this case after resolving its resource placeholder."""
66
+
67
+ return render_path(
68
+ self.spec.contract.path,
69
+ resource=self.resource,
70
+ resource_spec=self.spec.resource,
71
+ params=self.spec.contract.params,
72
+ )
73
+
74
+ def execute(
75
+ self,
76
+ *,
77
+ data: Any = _UNSET,
78
+ query: Any = _UNSET,
79
+ headers: Mapping[str, str] | None = None,
80
+ ) -> Any:
81
+ """Send this case through the actor's configured API client fixture."""
82
+
83
+ client = self._fixture(self.spec.actor.client_fixture)
84
+ request_spec = self.spec.contract.request
85
+ request_data = self._optional_fixture(request_spec.data_fixture) if data is _UNSET else data
86
+ query_data = (
87
+ self._optional_fixture(request_spec.query_fixture) if query is _UNSET else query
88
+ )
89
+ path = _append_query(self.path, query_data)
90
+ request_headers = dict(request_spec.headers)
91
+ if headers:
92
+ request_headers.update(headers)
93
+
94
+ kwargs: dict[str, Any] = {}
95
+ if request_data is not None:
96
+ kwargs["data"] = request_data
97
+ if request_spec.format is not None:
98
+ kwargs["format"] = request_spec.format
99
+ if request_headers:
100
+ kwargs["headers"] = request_headers
101
+
102
+ method = self.spec.contract.method.lower()
103
+ sender = getattr(client, method, None)
104
+ if callable(sender):
105
+ return sender(path, **kwargs)
106
+ generic = getattr(client, "generic", None)
107
+ if callable(generic):
108
+ return generic(self.spec.contract.method, path, **kwargs)
109
+ raise AuthzExecutionError(
110
+ f"Fixture {self.spec.actor.client_fixture!r} has neither {method}() nor generic()"
111
+ )
112
+
113
+ def assert_response(self, response: Any) -> Any:
114
+ """Assert the configured status outcome and return the response unchanged."""
115
+
116
+ status = getattr(response, "status_code", None)
117
+ expected = self.spec.expectation.statuses
118
+ passed = isinstance(status, int) and status in expected
119
+ if self._recorder is not None:
120
+ self._recorder.record_case(self.spec, passed=passed, actual_status=status)
121
+ if not passed:
122
+ expected_text = ", ".join(str(item) for item in expected)
123
+ detail = _response_detail(response)
124
+ raise AssertionError(
125
+ f"{self.spec.id} expected HTTP {expected_text}, got {status!r}{detail}"
126
+ )
127
+ return response
128
+
129
+ def run(self, **request_overrides: Any) -> Any:
130
+ """Execute this case, assert its status, and return the response."""
131
+
132
+ return self.assert_response(self.execute(**request_overrides))
133
+
134
+ def _fixture(self, name: str) -> Any:
135
+ try:
136
+ return self._request.getfixturevalue(name)
137
+ except Exception as exc:
138
+ raise AuthzExecutionError(f"Could not resolve pytest fixture {name!r}") from exc
139
+
140
+ def _optional_fixture(self, name: str | None) -> Any | None:
141
+ return self._fixture(name) if name else None
142
+
143
+
144
+ def _append_query(path: str, query: Any | None) -> str:
145
+ if query is None:
146
+ return path
147
+ if isinstance(query, str):
148
+ encoded = query.lstrip("?")
149
+ else:
150
+ try:
151
+ encoded = urlencode(query, doseq=True)
152
+ except (TypeError, ValueError) as exc:
153
+ raise AuthzExecutionError(
154
+ "Query fixture must be a string or urlencode-compatible value"
155
+ ) from exc
156
+ if not encoded:
157
+ return path
158
+ separator = "&" if "?" in path else "?"
159
+ return f"{path}{separator}{encoded}"
160
+
161
+
162
+ def _response_detail(response: Any) -> str:
163
+ value = getattr(response, "data", None)
164
+ if value is None:
165
+ value = getattr(response, "content", None)
166
+ if isinstance(value, bytes):
167
+ value = value.decode("utf-8", errors="replace")
168
+ if value in (None, "", b""):
169
+ return ""
170
+ rendered = repr(value)
171
+ if len(rendered) > 300:
172
+ rendered = rendered[:297] + "..."
173
+ return f"; response={rendered}"
@@ -0,0 +1,241 @@
1
+ """Load and validate authorization matrix YAML files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import yaml
10
+
11
+ from pytest_authz_matrix.exceptions import AuthzConfigurationError
12
+ from pytest_authz_matrix.models import (
13
+ DEFAULT_OUTCOMES,
14
+ ActorSpec,
15
+ ContractSpec,
16
+ Expectation,
17
+ MatrixConfig,
18
+ RequestSpec,
19
+ ResourceSpec,
20
+ )
21
+
22
+
23
+ def load_config(path: str | Path) -> MatrixConfig:
24
+ """Load a YAML file and return a fully validated immutable configuration."""
25
+
26
+ config_path = Path(path)
27
+ if not config_path.is_file():
28
+ raise AuthzConfigurationError(f"Authorization config not found: {config_path}")
29
+
30
+ try:
31
+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))
32
+ except yaml.YAMLError as exc:
33
+ raise AuthzConfigurationError(f"Invalid YAML in {config_path}: {exc}") from exc
34
+
35
+ root = _mapping(raw, "root")
36
+ version = root.get("version", 1)
37
+ if version != 1:
38
+ raise AuthzConfigurationError(f"Unsupported config version {version!r}; expected 1")
39
+
40
+ outcomes = _parse_outcomes(root.get("outcomes", {}))
41
+ actors = _parse_actors(_mapping(root.get("actors"), "actors"))
42
+ resources = _parse_resources(_mapping(root.get("resources", {}), "resources"))
43
+ contracts = _parse_contracts(
44
+ _mapping(root.get("contracts"), "contracts"), actors, resources, outcomes
45
+ )
46
+ if not contracts:
47
+ raise AuthzConfigurationError("contracts must define at least one authorization contract")
48
+
49
+ return MatrixConfig(
50
+ version=version,
51
+ actors=actors,
52
+ resources=resources,
53
+ outcomes=outcomes,
54
+ contracts=contracts,
55
+ )
56
+
57
+
58
+ def _parse_outcomes(raw: Any) -> dict[str, tuple[int, ...]]:
59
+ outcomes = dict(DEFAULT_OUTCOMES)
60
+ for name, value in _mapping(raw, "outcomes").items():
61
+ outcomes[str(name)] = _statuses(value, f"outcomes.{name}")
62
+ return outcomes
63
+
64
+
65
+ def _parse_actors(raw: Mapping[str, Any]) -> dict[str, ActorSpec]:
66
+ actors: dict[str, ActorSpec] = {}
67
+ for name, value in raw.items():
68
+ if isinstance(value, str):
69
+ fixture = value
70
+ else:
71
+ actor = _mapping(value, f"actors.{name}")
72
+ fixture = _required_string(actor, "client_fixture", f"actors.{name}")
73
+ actors[name] = ActorSpec(name=name, client_fixture=fixture)
74
+ if not actors:
75
+ raise AuthzConfigurationError("actors must define at least one actor")
76
+ return actors
77
+
78
+
79
+ def _parse_resources(raw: Mapping[str, Any]) -> dict[str, ResourceSpec]:
80
+ resources: dict[str, ResourceSpec] = {}
81
+ for name, value in raw.items():
82
+ resource = _mapping(value, f"resources.{name}")
83
+ fixture = _required_string(resource, "fixture", f"resources.{name}")
84
+ lookup = resource.get("lookup", "pk")
85
+ if not isinstance(lookup, str) or not lookup:
86
+ raise AuthzConfigurationError(f"resources.{name}.lookup must be a non-empty string")
87
+ resources[name] = ResourceSpec(name=name, fixture=fixture, lookup=lookup)
88
+ return resources
89
+
90
+
91
+ def _parse_contracts(
92
+ raw: Mapping[str, Any],
93
+ actors: Mapping[str, ActorSpec],
94
+ resources: Mapping[str, ResourceSpec],
95
+ outcomes: Mapping[str, tuple[int, ...]],
96
+ ) -> dict[str, ContractSpec]:
97
+ contracts: dict[str, ContractSpec] = {}
98
+ for name, value in raw.items():
99
+ location = f"contracts.{name}"
100
+ contract = _mapping(value, location)
101
+ method = _required_string(contract, "method", location).upper()
102
+ path = _required_string(contract, "path", location)
103
+ resource_name = contract.get("resource")
104
+ if resource_name is not None and resource_name not in resources:
105
+ raise AuthzConfigurationError(
106
+ f"{location}.resource references unknown resource {resource_name!r}"
107
+ )
108
+
109
+ matrix = _parse_matrix(
110
+ _mapping(contract.get("matrix"), f"{location}.matrix"),
111
+ actors,
112
+ outcomes,
113
+ has_resource=resource_name is not None,
114
+ location=f"{location}.matrix",
115
+ )
116
+ request = _parse_request(contract.get("request", {}), f"{location}.request")
117
+ params = dict(_mapping(contract.get("params", {}), f"{location}.params"))
118
+ route_name = contract.get("route_name")
119
+ if route_name is not None and not isinstance(route_name, str):
120
+ raise AuthzConfigurationError(f"{location}.route_name must be a string")
121
+
122
+ contracts[name] = ContractSpec(
123
+ name=name,
124
+ method=method,
125
+ path=path,
126
+ matrix=matrix,
127
+ resource=resource_name,
128
+ route_name=route_name,
129
+ params=params,
130
+ request=request,
131
+ )
132
+ return contracts
133
+
134
+
135
+ def _parse_matrix(
136
+ raw: Mapping[str, Any],
137
+ actors: Mapping[str, ActorSpec],
138
+ outcomes: Mapping[str, tuple[int, ...]],
139
+ *,
140
+ has_resource: bool,
141
+ location: str,
142
+ ) -> dict[str, dict[str | None, Expectation]]:
143
+ matrix: dict[str, dict[str | None, Expectation]] = {}
144
+ for actor_name, value in raw.items():
145
+ if actor_name not in actors:
146
+ raise AuthzConfigurationError(f"{location} references unknown actor {actor_name!r}")
147
+ if has_resource:
148
+ relationships = _mapping(value, f"{location}.{actor_name}")
149
+ if not relationships:
150
+ raise AuthzConfigurationError(
151
+ f"{location}.{actor_name} must define at least one resource relationship"
152
+ )
153
+ matrix[actor_name] = {
154
+ relationship: _expectation(
155
+ expectation,
156
+ outcomes,
157
+ f"{location}.{actor_name}.{relationship}",
158
+ )
159
+ for relationship, expectation in relationships.items()
160
+ }
161
+ else:
162
+ matrix[actor_name] = {None: _expectation(value, outcomes, f"{location}.{actor_name}")}
163
+ if not matrix:
164
+ raise AuthzConfigurationError(f"{location} must not be empty")
165
+ return matrix
166
+
167
+
168
+ def _expectation(raw: Any, outcomes: Mapping[str, tuple[int, ...]], location: str) -> Expectation:
169
+ if isinstance(raw, str):
170
+ outcome = raw
171
+ statuses = outcomes.get(outcome)
172
+ if statuses is None:
173
+ raise AuthzConfigurationError(f"{location} references unknown outcome {outcome!r}")
174
+ return Expectation(outcome=outcome, statuses=statuses)
175
+ if isinstance(raw, int):
176
+ return Expectation(outcome="status", statuses=_statuses(raw, location))
177
+ if isinstance(raw, list):
178
+ return Expectation(outcome="status", statuses=_statuses(raw, location))
179
+
180
+ value = _mapping(raw, location)
181
+ outcome = value.get("outcome", "custom")
182
+ if not isinstance(outcome, str):
183
+ raise AuthzConfigurationError(f"{location}.outcome must be a string")
184
+ if "statuses" in value:
185
+ statuses = _statuses(value["statuses"], f"{location}.statuses")
186
+ elif "status" in value:
187
+ statuses = _statuses(value["status"], f"{location}.status")
188
+ elif outcome in outcomes:
189
+ statuses = outcomes[outcome]
190
+ else:
191
+ raise AuthzConfigurationError(
192
+ f"{location} must include status/statuses or reference a known outcome"
193
+ )
194
+ return Expectation(outcome=outcome, statuses=statuses)
195
+
196
+
197
+ def _parse_request(raw: Any, location: str) -> RequestSpec:
198
+ value = _mapping(raw, location)
199
+ headers = _mapping(value.get("headers", {}), f"{location}.headers")
200
+ if any(not isinstance(key, str) or not isinstance(item, str) for key, item in headers.items()):
201
+ raise AuthzConfigurationError(f"{location}.headers keys and values must be strings")
202
+ return RequestSpec(
203
+ data_fixture=_optional_string(value, "data_fixture", location),
204
+ query_fixture=_optional_string(value, "query_fixture", location),
205
+ format=_optional_string(value, "format", location, default="json"),
206
+ headers=dict(headers),
207
+ )
208
+
209
+
210
+ def _statuses(value: Any, location: str) -> tuple[int, ...]:
211
+ values = value if isinstance(value, list) else [value]
212
+ if not values or any(
213
+ not isinstance(status, int) or isinstance(status, bool) for status in values
214
+ ):
215
+ raise AuthzConfigurationError(f"{location} must contain one or more integer HTTP statuses")
216
+ invalid = [status for status in values if status < 100 or status > 599]
217
+ if invalid:
218
+ raise AuthzConfigurationError(f"{location} contains invalid HTTP statuses: {invalid}")
219
+ return tuple(values)
220
+
221
+
222
+ def _mapping(value: Any, location: str) -> Mapping[str, Any]:
223
+ if not isinstance(value, Mapping):
224
+ raise AuthzConfigurationError(f"{location} must be a mapping")
225
+ return value
226
+
227
+
228
+ def _required_string(value: Mapping[str, Any], key: str, location: str) -> str:
229
+ result = value.get(key)
230
+ if not isinstance(result, str) or not result:
231
+ raise AuthzConfigurationError(f"{location}.{key} must be a non-empty string")
232
+ return result
233
+
234
+
235
+ def _optional_string(
236
+ value: Mapping[str, Any], key: str, location: str, *, default: str | None = None
237
+ ) -> str | None:
238
+ result = value.get(key, default)
239
+ if result is not None and not isinstance(result, str):
240
+ raise AuthzConfigurationError(f"{location}.{key} must be a string or null")
241
+ return result
@@ -0,0 +1,154 @@
1
+ """Best-effort discovery of Django REST Framework URL routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ from pytest_authz_matrix.models import ContractSpec, MatrixConfig
10
+
11
+ _TEMPLATE_PARAMETER = re.compile(r"\{[^{}]+\}")
12
+ _DJANGO_CONVERTER = re.compile(r"<(?:(?:[^:<>]+):)?([^<>]+)>")
13
+ _REGEX_GROUP = re.compile(r"\(\?P<[^>]+>[^)]+\)")
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class DiscoveredRoute:
18
+ """One HTTP method exposed by a DRF URL pattern."""
19
+
20
+ method: str
21
+ name: str | None
22
+ pattern: str
23
+
24
+ @property
25
+ def id(self) -> str:
26
+ label = self.name or self.pattern
27
+ return f"{self.method} {label}"
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class DiscoveryResult:
32
+ """The outcome of optional DRF route discovery."""
33
+
34
+ available: bool
35
+ routes: tuple[DiscoveredRoute, ...] = ()
36
+ reason: str | None = None
37
+
38
+
39
+ def discover_drf_routes() -> DiscoveryResult:
40
+ """Walk Django's root URL resolver and return DRF methods only."""
41
+
42
+ try:
43
+ from django.conf import settings # type: ignore[import-untyped]
44
+ from django.urls import ( # type: ignore[import-untyped]
45
+ URLPattern,
46
+ URLResolver,
47
+ get_resolver,
48
+ )
49
+ except ImportError:
50
+ return DiscoveryResult(False, reason="Django REST Framework is not installed")
51
+ if not settings.configured:
52
+ return DiscoveryResult(False, reason="Django settings are not configured")
53
+ try:
54
+ from rest_framework.views import APIView # type: ignore[import-untyped]
55
+ except Exception as exc:
56
+ return DiscoveryResult(False, reason=f"Django REST Framework is unavailable: {exc}")
57
+
58
+ try:
59
+ root = get_resolver()
60
+ except Exception as exc: # Django may be installed but not configured in this test run.
61
+ return DiscoveryResult(False, reason=f"Django URL resolver unavailable: {exc}")
62
+
63
+ routes: set[DiscoveredRoute] = set()
64
+
65
+ def walk(patterns: list[Any], prefix: str = "", namespace: str = "") -> None:
66
+ for item in patterns:
67
+ current_pattern = prefix + str(item.pattern)
68
+ if isinstance(item, URLResolver):
69
+ child_namespace = namespace
70
+ if item.namespace:
71
+ child_namespace = (
72
+ f"{namespace}:{item.namespace}" if namespace else item.namespace
73
+ )
74
+ walk(list(item.url_patterns), current_pattern, child_namespace)
75
+ continue
76
+ if not isinstance(item, URLPattern):
77
+ continue
78
+
79
+ callback = item.callback
80
+ view_class = getattr(callback, "cls", None)
81
+ if view_class is None:
82
+ view_class = getattr(callback, "view_class", None)
83
+ if not isinstance(view_class, type) or not issubclass(view_class, APIView):
84
+ continue
85
+
86
+ route_name = item.name
87
+ if route_name and namespace:
88
+ route_name = f"{namespace}:{route_name}"
89
+ for method in _view_methods(callback, view_class):
90
+ routes.add(
91
+ DiscoveredRoute(
92
+ method=method,
93
+ name=route_name,
94
+ pattern=current_pattern,
95
+ )
96
+ )
97
+
98
+ try:
99
+ walk(list(root.url_patterns))
100
+ except Exception as exc:
101
+ return DiscoveryResult(False, reason=f"DRF route discovery failed: {exc}")
102
+ return DiscoveryResult(True, routes=tuple(sorted(routes, key=lambda route: route.id)))
103
+
104
+
105
+ def covered_routes(
106
+ discovery: DiscoveryResult, config: MatrixConfig
107
+ ) -> tuple[set[DiscoveredRoute], set[DiscoveredRoute]]:
108
+ """Split discovered routes into covered and uncovered method-route pairs."""
109
+
110
+ if not discovery.available:
111
+ return set(), set()
112
+ covered: set[DiscoveredRoute] = set()
113
+ uncovered: set[DiscoveredRoute] = set()
114
+ contracts = tuple(config.contracts.values())
115
+ for route in discovery.routes:
116
+ target = covered if any(_matches(route, contract) for contract in contracts) else uncovered
117
+ target.add(route)
118
+ return covered, uncovered
119
+
120
+
121
+ def normalize_path(path: str) -> str:
122
+ """Normalize OpenAPI-like, Django converter, and regex path parameters."""
123
+
124
+ normalized = _TEMPLATE_PARAMETER.sub("{}", path)
125
+ normalized = _REGEX_GROUP.sub("{}", normalized)
126
+ normalized = _DJANGO_CONVERTER.sub("{}", normalized)
127
+ normalized = normalized.replace("^", "").replace("$", "")
128
+ normalized = normalized.replace("\\Z", "")
129
+ normalized = re.sub(r"/+$", "", normalized.lstrip("/"))
130
+ return normalized
131
+
132
+
133
+ def _view_methods(callback: Any, view_class: type[Any]) -> tuple[str, ...]:
134
+ actions = getattr(callback, "actions", None)
135
+ if actions:
136
+ methods = actions.keys()
137
+ else:
138
+ methods = (
139
+ method
140
+ for method in getattr(view_class, "http_method_names", ())
141
+ if callable(getattr(view_class, method, None))
142
+ )
143
+ allowed = {
144
+ str(method).upper() for method in methods if str(method).upper() not in {"HEAD", "OPTIONS"}
145
+ }
146
+ return tuple(sorted(allowed))
147
+
148
+
149
+ def _matches(route: DiscoveredRoute, contract: ContractSpec) -> bool:
150
+ if route.method != contract.method:
151
+ return False
152
+ if contract.route_name and route.name:
153
+ return contract.route_name in {route.name, route.name.rsplit(":", 1)[-1]}
154
+ return normalize_path(route.pattern) == normalize_path(contract.path)
@@ -0,0 +1,13 @@
1
+ """Public exceptions raised by pytest-authz-matrix."""
2
+
3
+
4
+ class AuthzMatrixError(Exception):
5
+ """Base error for the package."""
6
+
7
+
8
+ class AuthzConfigurationError(AuthzMatrixError):
9
+ """Raised when an authorization contract file is invalid."""
10
+
11
+
12
+ class AuthzExecutionError(AuthzMatrixError):
13
+ """Raised when a generated authorization case cannot be executed."""
@@ -0,0 +1,89 @@
1
+ """Typed domain models used by the configuration and pytest plugin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ DEFAULT_OUTCOMES: dict[str, tuple[int, ...]] = {
9
+ "allow": (200,),
10
+ "deny": (403,),
11
+ "conceal": (404,),
12
+ "unauthenticated": (401,),
13
+ }
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class ActorSpec:
18
+ """An authenticated (or anonymous) API client exposed by a pytest fixture."""
19
+
20
+ name: str
21
+ client_fixture: str
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class ResourceSpec:
26
+ """A mapping of relationship names to application objects."""
27
+
28
+ name: str
29
+ fixture: str
30
+ lookup: str = "pk"
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class Expectation:
35
+ """The HTTP statuses accepted for a named authorization outcome."""
36
+
37
+ outcome: str
38
+ statuses: tuple[int, ...]
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class RequestSpec:
43
+ """Optional request data used by a contract."""
44
+
45
+ data_fixture: str | None = None
46
+ query_fixture: str | None = None
47
+ format: str | None = "json"
48
+ headers: dict[str, str] = field(default_factory=dict)
49
+
50
+
51
+ @dataclass(frozen=True, slots=True)
52
+ class ContractSpec:
53
+ """An endpoint and its complete actor-to-resource access contract."""
54
+
55
+ name: str
56
+ method: str
57
+ path: str
58
+ matrix: dict[str, dict[str | None, Expectation]]
59
+ resource: str | None = None
60
+ route_name: str | None = None
61
+ params: dict[str, Any] = field(default_factory=dict)
62
+ request: RequestSpec = field(default_factory=RequestSpec)
63
+
64
+
65
+ @dataclass(frozen=True, slots=True)
66
+ class MatrixConfig:
67
+ """Validated top-level authorization configuration."""
68
+
69
+ version: int
70
+ actors: dict[str, ActorSpec]
71
+ resources: dict[str, ResourceSpec]
72
+ outcomes: dict[str, tuple[int, ...]]
73
+ contracts: dict[str, ContractSpec]
74
+
75
+
76
+ @dataclass(frozen=True, slots=True)
77
+ class CaseSpec:
78
+ """One generated actor/resource authorization test."""
79
+
80
+ contract: ContractSpec
81
+ actor: ActorSpec
82
+ resource: ResourceSpec | None
83
+ relationship: str | None
84
+ expectation: Expectation
85
+
86
+ @property
87
+ def id(self) -> str:
88
+ relationship = self.relationship or "endpoint"
89
+ return f"{self.contract.name}[{self.actor.name}-{relationship}-{self.expectation.outcome}]"