tba-tests-identity 0.4.0.dev2__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,47 @@
1
+ """Test fixtures and conformance helpers for the TBA identity package suite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .cross_cutting import (
6
+ AuthorizationCode,
7
+ FakeIdentityProvider,
8
+ FakeRelyingParty,
9
+ FakeResourceServer,
10
+ MatrixCellStatus,
11
+ PackageMatrixCell,
12
+ PackageMatrixHarness,
13
+ SeededClient,
14
+ SeededTenant,
15
+ SeededUser,
16
+ TestkitError,
17
+ TestkitProviderRuntimeProfile,
18
+ TestkitSeedSet,
19
+ TokenResponse,
20
+ build_fake_flow,
21
+ cross_language_vectors,
22
+ default_seed_set,
23
+ pkce_s256,
24
+ provider_runtime_profile,
25
+ )
26
+
27
+ __all__ = [
28
+ "AuthorizationCode",
29
+ "FakeIdentityProvider",
30
+ "FakeRelyingParty",
31
+ "FakeResourceServer",
32
+ "MatrixCellStatus",
33
+ "PackageMatrixCell",
34
+ "PackageMatrixHarness",
35
+ "SeededClient",
36
+ "SeededTenant",
37
+ "SeededUser",
38
+ "TestkitError",
39
+ "TestkitProviderRuntimeProfile",
40
+ "TestkitSeedSet",
41
+ "TokenResponse",
42
+ "build_fake_flow",
43
+ "cross_language_vectors",
44
+ "default_seed_set",
45
+ "pkce_s256",
46
+ "provider_runtime_profile",
47
+ ]
@@ -0,0 +1,395 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import hashlib
5
+ import secrets
6
+ from dataclasses import dataclass, field
7
+ from enum import Enum
8
+ from typing import Iterable, Mapping
9
+ from urllib.parse import parse_qs, urlencode, urlparse
10
+
11
+
12
+ class TestkitError(RuntimeError):
13
+ pass
14
+
15
+
16
+ TestkitError.__test__ = False
17
+
18
+
19
+ class MatrixCellStatus(str, Enum):
20
+ PLANNED = "planned"
21
+ PASSING = "passing"
22
+ FAILING = "failing"
23
+
24
+
25
+ def _b64url(data: bytes) -> str:
26
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
27
+
28
+
29
+ def pkce_s256(verifier: str) -> str:
30
+ if not verifier:
31
+ raise TestkitError("PKCE verifier is required")
32
+ return _b64url(hashlib.sha256(verifier.encode("ascii")).digest())
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class SeededTenant:
37
+ tenant_id: str
38
+ issuer: str
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class SeededClient:
43
+ client_id: str
44
+ tenant_id: str
45
+ redirect_uri: str
46
+ scopes: tuple[str, ...] = ("openid",)
47
+
48
+ def __post_init__(self) -> None:
49
+ object.__setattr__(self, "scopes", tuple(sorted(set(self.scopes))))
50
+
51
+
52
+ @dataclass(frozen=True, slots=True)
53
+ class SeededUser:
54
+ subject: str
55
+ tenant_id: str
56
+ username: str
57
+
58
+
59
+ @dataclass(frozen=True, slots=True)
60
+ class TestkitSeedSet:
61
+ tenant: SeededTenant
62
+ clients: tuple[SeededClient, ...]
63
+ users: tuple[SeededUser, ...]
64
+
65
+ def client(self, client_id: str) -> SeededClient:
66
+ for client in self.clients:
67
+ if client.client_id == client_id:
68
+ return client
69
+ raise TestkitError("seeded client is not configured")
70
+
71
+ def user(self, subject: str) -> SeededUser:
72
+ for user in self.users:
73
+ if user.subject == subject:
74
+ return user
75
+ raise TestkitError("seeded user is not configured")
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class TestkitProviderRuntimeProfile:
80
+ name: str = "testkit-provider-runtime"
81
+ tenant_id: str = "test"
82
+ routes: tuple[str, ...] = (
83
+ "/authorize",
84
+ "/token",
85
+ "/userinfo",
86
+ "/.well-known/openid-configuration",
87
+ "/.well-known/jwks.json",
88
+ "/rpc",
89
+ "/device_authorization",
90
+ "/tenants",
91
+ "/users",
92
+ )
93
+ feature_flags: Mapping[str, bool] = field(
94
+ default_factory=lambda: {
95
+ "public_oauth": True,
96
+ "public_oidc": True,
97
+ "admin_crud": True,
98
+ "json_rpc": True,
99
+ "device_flow": True,
100
+ "token_exchange": True,
101
+ "dpop": True,
102
+ "tenant_discovery": True,
103
+ "seeded_identities": True,
104
+ }
105
+ )
106
+
107
+ def __post_init__(self) -> None:
108
+ object.__setattr__(self, "routes", tuple(dict.fromkeys(self.routes)))
109
+ object.__setattr__(self, "feature_flags", dict(self.feature_flags))
110
+
111
+ def require_route(self, route: str) -> None:
112
+ if route not in self.routes:
113
+ raise TestkitError(f"testkit provider route is not enabled: {route}")
114
+
115
+ def require_feature(self, feature: str) -> None:
116
+ if not self.feature_flags.get(feature, False):
117
+ raise TestkitError(f"testkit provider feature is not enabled: {feature}")
118
+
119
+
120
+ @dataclass(frozen=True, slots=True)
121
+ class AuthorizationCode:
122
+ code: str
123
+ client_id: str
124
+ redirect_uri: str
125
+ subject: str
126
+ scope: tuple[str, ...]
127
+ code_challenge: str
128
+ nonce: str
129
+
130
+
131
+ @dataclass(frozen=True, slots=True)
132
+ class TokenResponse:
133
+ access_token: str
134
+ id_token: str
135
+ token_type: str
136
+ subject: str
137
+ scope: tuple[str, ...]
138
+
139
+
140
+ class FakeIdentityProvider:
141
+ def __init__(
142
+ self,
143
+ *,
144
+ seeds: TestkitSeedSet,
145
+ profile: TestkitProviderRuntimeProfile | None = None,
146
+ ) -> None:
147
+ self.seeds = seeds
148
+ self.profile = profile or TestkitProviderRuntimeProfile(tenant_id=seeds.tenant.tenant_id)
149
+ self._codes: dict[str, AuthorizationCode] = {}
150
+ self._tokens: dict[str, TokenResponse] = {}
151
+
152
+ def discovery_document(self) -> Mapping[str, str]:
153
+ issuer = self.seeds.tenant.issuer.rstrip("/")
154
+ return {
155
+ "issuer": issuer,
156
+ "authorization_endpoint": f"{issuer}/authorize",
157
+ "token_endpoint": f"{issuer}/token",
158
+ "userinfo_endpoint": f"{issuer}/userinfo",
159
+ "jwks_uri": f"{issuer}/.well-known/jwks.json",
160
+ "device_authorization_endpoint": f"{issuer}/device_authorization",
161
+ }
162
+
163
+ def jwks(self) -> Mapping[str, object]:
164
+ return {"keys": [{"kid": f"{self.seeds.tenant.tenant_id}-sig-1", "kty": "OKP", "use": "sig"}]}
165
+
166
+ def authorize(
167
+ self,
168
+ *,
169
+ client_id: str,
170
+ redirect_uri: str,
171
+ subject: str,
172
+ scope: Iterable[str],
173
+ code_challenge: str,
174
+ nonce: str,
175
+ ) -> AuthorizationCode:
176
+ self.profile.require_route("/authorize")
177
+ client = self.seeds.client(client_id)
178
+ self.seeds.user(subject)
179
+ if redirect_uri != client.redirect_uri:
180
+ raise TestkitError("redirect URI is not registered for seeded client")
181
+ requested_scopes = tuple(sorted(set(scope)))
182
+ if not set(requested_scopes).issubset(set(client.scopes)):
183
+ raise TestkitError("requested scope is not allowed for seeded client")
184
+ code = AuthorizationCode(
185
+ code=f"code_{secrets.token_urlsafe(12)}",
186
+ client_id=client_id,
187
+ redirect_uri=redirect_uri,
188
+ subject=subject,
189
+ scope=requested_scopes,
190
+ code_challenge=code_challenge,
191
+ nonce=nonce,
192
+ )
193
+ self._codes[code.code] = code
194
+ return code
195
+
196
+ def token(self, *, code: str, code_verifier: str, client_id: str) -> TokenResponse:
197
+ self.profile.require_route("/token")
198
+ try:
199
+ grant = self._codes[code]
200
+ except KeyError as exc:
201
+ raise TestkitError("authorization code is unknown or already used") from exc
202
+ if grant.client_id != client_id:
203
+ raise TestkitError("authorization code client mismatch")
204
+ if pkce_s256(code_verifier) != grant.code_challenge:
205
+ raise TestkitError("PKCE verifier does not match authorization code")
206
+ self._codes.pop(code)
207
+ token = TokenResponse(
208
+ access_token=f"at_{secrets.token_urlsafe(16)}",
209
+ id_token=f"id_{grant.subject}_{grant.nonce}",
210
+ token_type="Bearer",
211
+ subject=grant.subject,
212
+ scope=grant.scope,
213
+ )
214
+ self._tokens[token.access_token] = token
215
+ return token
216
+
217
+ def introspect(self, access_token: str) -> Mapping[str, object]:
218
+ token = self._tokens.get(access_token)
219
+ if token is None:
220
+ return {"active": False}
221
+ return {
222
+ "active": True,
223
+ "iss": self.seeds.tenant.issuer,
224
+ "sub": token.subject,
225
+ "aud": "api://test",
226
+ "scope": " ".join(token.scope),
227
+ "token_type": token.token_type,
228
+ }
229
+
230
+ def userinfo(self, access_token: str) -> Mapping[str, str]:
231
+ self.profile.require_route("/userinfo")
232
+ payload = self.introspect(access_token)
233
+ if not payload.get("active"):
234
+ raise TestkitError("userinfo requires an active access token")
235
+ user = self.seeds.user(str(payload["sub"]))
236
+ return {"sub": user.subject, "preferred_username": user.username, "tenant_id": user.tenant_id}
237
+
238
+
239
+ @dataclass(slots=True)
240
+ class FakeRelyingParty:
241
+ client: SeededClient
242
+ issuer: str
243
+ code_verifier: str = "testkit-vector-verifier"
244
+ state: str = "testkit-state"
245
+ nonce: str = "testkit-nonce"
246
+
247
+ def authorization_url(self) -> str:
248
+ return f"{self.issuer.rstrip('/')}/authorize?{urlencode(self.authorization_params())}"
249
+
250
+ def authorization_params(self) -> Mapping[str, str]:
251
+ return {
252
+ "response_type": "code",
253
+ "client_id": self.client.client_id,
254
+ "redirect_uri": self.client.redirect_uri,
255
+ "scope": " ".join(self.client.scopes),
256
+ "state": self.state,
257
+ "nonce": self.nonce,
258
+ "code_challenge": pkce_s256(self.code_verifier),
259
+ "code_challenge_method": "S256",
260
+ }
261
+
262
+ def parse_callback(self, callback_url: str) -> Mapping[str, str]:
263
+ parsed = parse_qs(urlparse(callback_url).query)
264
+ code = (parsed.get("code") or [""])[0]
265
+ state = (parsed.get("state") or [""])[0]
266
+ if not code or state != self.state:
267
+ raise TestkitError("RP callback is missing code or has invalid state")
268
+ return {"code": code, "state": state}
269
+
270
+
271
+ @dataclass(slots=True)
272
+ class FakeResourceServer:
273
+ idp: FakeIdentityProvider
274
+ audience: str = "api://test"
275
+ required_scopes: tuple[str, ...] = ("openid",)
276
+
277
+ def verify(self, authorization: str | None) -> Mapping[str, object]:
278
+ if not authorization:
279
+ raise TestkitError("resource server request is missing authorization")
280
+ scheme, _, token = authorization.partition(" ")
281
+ if scheme.lower() != "bearer" or not token:
282
+ raise TestkitError("resource server request must use bearer authorization")
283
+ payload = self.idp.introspect(token)
284
+ if not payload.get("active"):
285
+ raise TestkitError("resource server token is inactive")
286
+ scopes = set(str(payload.get("scope", "")).split())
287
+ missing = set(self.required_scopes) - scopes
288
+ if missing:
289
+ raise TestkitError(f"resource server token is missing scopes: {', '.join(sorted(missing))}")
290
+ if payload.get("aud") != self.audience:
291
+ raise TestkitError("resource server audience mismatch")
292
+ return payload
293
+
294
+
295
+ @dataclass(frozen=True, slots=True)
296
+ class PackageMatrixCell:
297
+ package: str
298
+ python_version: str
299
+ test_paths: tuple[str, ...]
300
+ cross_cutting: bool = False
301
+ status: MatrixCellStatus = MatrixCellStatus.PLANNED
302
+
303
+ def __post_init__(self) -> None:
304
+ object.__setattr__(self, "test_paths", tuple(self.test_paths))
305
+ object.__setattr__(self, "status", MatrixCellStatus(self.status))
306
+
307
+
308
+ class PackageMatrixHarness:
309
+ def __init__(self, *, python_versions: Iterable[str] = ("3.10", "3.11", "3.12", "3.13", "3.14")) -> None:
310
+ self.python_versions = tuple(python_versions)
311
+
312
+ def cells_for(self, package: str, *, test_paths: Iterable[str], cross_cutting: bool = False) -> tuple[PackageMatrixCell, ...]:
313
+ paths = tuple(test_paths)
314
+ if not package or not paths:
315
+ raise TestkitError("package matrix cells require package and test paths")
316
+ return tuple(
317
+ PackageMatrixCell(package=package, python_version=version, test_paths=paths, cross_cutting=cross_cutting)
318
+ for version in self.python_versions
319
+ )
320
+
321
+ def assert_complete(self, cells: Iterable[PackageMatrixCell], *, package: str) -> None:
322
+ present = {cell.python_version for cell in cells if cell.package == package}
323
+ missing = set(self.python_versions) - present
324
+ if missing:
325
+ raise TestkitError(f"package matrix is missing Python versions: {', '.join(sorted(missing))}")
326
+
327
+
328
+ def default_seed_set() -> TestkitSeedSet:
329
+ return TestkitSeedSet(
330
+ tenant=SeededTenant(tenant_id="test", issuer="https://issuer.example.test"),
331
+ clients=(
332
+ SeededClient(
333
+ client_id="test-rp",
334
+ tenant_id="test",
335
+ redirect_uri="https://rp.example.test/callback",
336
+ scopes=("openid", "profile", "api.read"),
337
+ ),
338
+ ),
339
+ users=(SeededUser(subject="user:123", tenant_id="test", username="alice"),),
340
+ )
341
+
342
+
343
+ def provider_runtime_profile() -> TestkitProviderRuntimeProfile:
344
+ return TestkitProviderRuntimeProfile()
345
+
346
+
347
+ def cross_language_vectors() -> Mapping[str, object]:
348
+ verifier = "testkit-vector-verifier"
349
+ return {
350
+ "pkce_verifier": verifier,
351
+ "pkce_s256": pkce_s256(verifier),
352
+ "state": "testkit-state",
353
+ "nonce": "testkit-nonce",
354
+ "authorization_required_params": (
355
+ "client_id",
356
+ "code_challenge",
357
+ "code_challenge_method",
358
+ "nonce",
359
+ "redirect_uri",
360
+ "response_type",
361
+ "scope",
362
+ "state",
363
+ ),
364
+ }
365
+
366
+
367
+ def build_fake_flow() -> tuple[FakeIdentityProvider, FakeRelyingParty, FakeResourceServer]:
368
+ seeds = default_seed_set()
369
+ idp = FakeIdentityProvider(seeds=seeds)
370
+ rp = FakeRelyingParty(client=seeds.client("test-rp"), issuer=seeds.tenant.issuer)
371
+ rs = FakeResourceServer(idp=idp)
372
+ return idp, rp, rs
373
+
374
+
375
+ __all__ = [
376
+ "AuthorizationCode",
377
+ "FakeIdentityProvider",
378
+ "FakeRelyingParty",
379
+ "FakeResourceServer",
380
+ "MatrixCellStatus",
381
+ "PackageMatrixCell",
382
+ "PackageMatrixHarness",
383
+ "SeededClient",
384
+ "SeededTenant",
385
+ "SeededUser",
386
+ "TestkitError",
387
+ "TestkitProviderRuntimeProfile",
388
+ "TestkitSeedSet",
389
+ "TokenResponse",
390
+ "build_fake_flow",
391
+ "cross_language_vectors",
392
+ "default_seed_set",
393
+ "pkce_s256",
394
+ "provider_runtime_profile",
395
+ ]
File without changes
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: tba-tests-identity
3
+ Version: 0.4.0.dev2
4
+ Summary: Test fixtures, fake identity components, conformance vectors, integration harnesses, and cross-cutting verification helpers.
5
+ License-Expression: Apache-2.0
6
+ Keywords: tigrbl,identity,testkit,pytest,conformance,fixtures,integration-tests,oauth,oidc,iam
7
+ Requires-Python: >=3.10,<3.16
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Typing :: Typed
14
+ Classifier: Topic :: Internet :: WWW/HTTP
15
+ Classifier: Topic :: Security
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Project-URL: Homepage, https://github.com/tigrbl/tigrbl_auth
24
+ Project-URL: PyPI, https://pypi.org/project/tba-tests-identity/
25
+ Project-URL: Repository, https://github.com/tigrbl/tigrbl_auth
26
+ Project-URL: Source, https://github.com/tigrbl/tigrbl_auth/tree/master/pkgs/120-tests/tba-tests-identity
27
+ Project-URL: SSOT, https://github.com/tigrbl/tigrbl_auth/blob/master/.ssot/registry.json
28
+ Description-Content-Type: text/markdown
29
+
30
+ # tba-tests-identity
31
+
32
+ <!-- BEGIN TBA README HEADER -->
33
+ <p align="center">
34
+ <a href="https://github.com/tigrbl/tigrbl_auth#readme"><img src="https://raw.githubusercontent.com/tigrbl/tigrbl_auth/master/docs/assets/tba-brand.png" alt="TBA · Tigrbl Auth" width="240"></a>
35
+ </p>
36
+ <p align="center">
37
+ <a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/120-tests/tba-tests-identity/pyproject.toml"><img alt="Checkout: 0.4.0.dev2" src="https://img.shields.io/badge/Checkout-0.4.0.dev2-1f6feb"></a>
38
+ <a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/120-tests/tba-tests-identity/pyproject.toml"><img alt="Python: &gt;=3.10,&lt;3.16" src="https://img.shields.io/badge/Python-%3E%3D3.10%2C%3C3.16-3776ab"></a>
39
+ <a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/120-tests/tba-tests-identity/pyproject.toml"><img alt="License: Apache-2.0" src="https://img.shields.io/badge/License-Apache--2.0-525252"></a>
40
+ <a href="https://github.com/tigrbl/tigrbl_auth/tree/master/pkgs/120-tests"><img alt="Layer: 120 tests" src="https://img.shields.io/badge/Layer-120%20tests-0a7f5a"></a>
41
+ <a href="https://pypi.org/project/tba-tests-identity/"><img alt="PyPI version for tba-tests-identity" src="https://img.shields.io/pypi/v/tba-tests-identity?label=tba-tests-identity%20PyPI"></a>
42
+ </p>
43
+ <p align="center">
44
+ <a href="https://pepy.tech/project/tba-tests-identity"><img alt="Monthly PyPI downloads for tba-tests-identity" src="https://static.pepy.tech/badge/tba-tests-identity/month"></a>
45
+ <a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/120-tests/tba-tests-identity/README.md#verification"><img alt="Evidence: verification" src="https://img.shields.io/badge/Evidence-verification-8250df"></a>
46
+ </p>
47
+ <!-- END TBA README HEADER -->
48
+
49
+ Reuse deterministic identity fixtures, fake flows, and cross-language vectors in tests.
50
+
51
+ ## Quick start
52
+
53
+ Install the version used by this example.
54
+
55
+ ```bash
56
+ python -m pip install "tba-tests-identity==0.4.0.dev2"
57
+ ```
58
+
59
+ Save the following as `quickstart.py` and run `python quickstart.py`. The assertions should pass.
60
+
61
+ ```python
62
+ from tba_tests_identity import pkce_s256
63
+
64
+ verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
65
+ assert pkce_s256(verifier) == "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
66
+ ```
67
+
68
+ ## When to use it
69
+
70
+ Use the testkit for repeatable protocol and integration tests. Its fake providers and sample credentials are test fixtures. Real identity deployment and credential handling belong to the runtime and provider packages.
71
+
72
+ ## Verification
73
+
74
+ See the [related repository tests](https://github.com/tigrbl/tigrbl_auth/blob/master/tests/unit/test_testkit_cross_cutting_boundary.py) for the implementation scope covered by this example.
75
+
76
+ [Workspace and package catalog](https://github.com/tigrbl/tigrbl_auth#package-catalog) · [tba-protocol-cwt](https://github.com/tigrbl/tigrbl_auth/tree/master/pkgs/50-protocols/tba-protocol-cwt#readme) · [Report an issue](https://github.com/tigrbl/tigrbl_auth/issues) · [Repository license](https://github.com/tigrbl/tigrbl_auth/blob/master/LICENSE)
77
+
@@ -0,0 +1,6 @@
1
+ tba_tests_identity/__init__.py,sha256=lkoIA1QQwsSZFFMpiJwtYMOZXWgbGAkaBjeEBnSmHQM,1053
2
+ tba_tests_identity/cross_cutting.py,sha256=L3an_WQzjyYry2sVhQqVZVOKPhq9xhdWuxOnGjUr0Gg,13026
3
+ tba_tests_identity/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ tba_tests_identity-0.4.0.dev2.dist-info/METADATA,sha256=45Yg9BkMZlpMMruORYxYIAgNBCLBwWbdlU7XUIx505g,4569
5
+ tba_tests_identity-0.4.0.dev2.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
6
+ tba_tests_identity-0.4.0.dev2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.5.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any