agent-auth-rs 1.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ include LICENSE README.md THIRD_PARTY_NOTICES.md
2
+ include agent_auth_rs/py.typed
3
+ prune tests
4
+ global-exclude __pycache__ *.py[cod]
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent_auth_rs
3
+ Version: 1.0.1
4
+ Summary: Agent Auth RS 校验 SDK(spec 010 P1b):MCP 资源服务器侧 access token 校验 — aud 强校验、命名空间 sub_type 策略、kid 强制 alg、未知 kid 重取限流+负缓存、WWW-Authenticate 发现头。
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/amliuyong/a-auth
7
+ Project-URL: Documentation, https://github.com/amliuyong/a-auth/blob/main/docs/RS_SDK_RELEASE.md
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ License-File: THIRD_PARTY_NOTICES.md
12
+ Requires-Dist: pyjwt>=2.8
13
+ Requires-Dist: cryptography>=41
14
+ Provides-Extra: test
15
+ Requires-Dist: build>=1.2; extra == "test"
16
+ Requires-Dist: pytest>=7; extra == "test"
17
+ Requires-Dist: setuptools>=77; extra == "test"
18
+ Requires-Dist: wheel>=0.45; extra == "test"
19
+ Dynamic: license-file
20
+
21
+ # Agent Auth resource-server SDK
22
+
23
+ Python 3.10+ access-token verification for resource servers. Apache-2.0.
24
+
25
+ Install a qualified wheel or source distribution into an independent virtual
26
+ environment:
27
+
28
+ ```bash
29
+ python -m venv .venv
30
+ .venv/bin/python -m pip install /absolute/path/to/agent_auth_rs-1.0.1-py3-none-any.whl
31
+ ```
32
+
33
+ The fixed registry command is `python -m pip install agent_auth_rs==1.0.1`.
34
+ See the release guide below for verified registry availability and receipts.
35
+ The distribution name is `agent_auth_rs`; the existing Python import remains
36
+ `agent_auth_rs`.
37
+
38
+ ```python
39
+ from agent_auth_rs import RsSdk, RsSdkConfig, RoutePolicy
40
+
41
+ sdk = RsSdk(RsSdkConfig(
42
+ issuer="https://auth.example.com",
43
+ resource_id="https://mcp.example.com",
44
+ ))
45
+
46
+ def protected_resource(authorization_header):
47
+ result = sdk.authenticate(
48
+ authorization_header,
49
+ RoutePolicy(require_sub_type="user", require_scopes=["read"]),
50
+ )
51
+ if not result.ok:
52
+ return result.status, result.headers, None
53
+ return 200, {}, {"subject": result.token.sub}
54
+ ```
55
+
56
+ Configure the exact issuer and resource identifier of your deployment. The
57
+ SDK obtains public JWKS and rejects wrong issuer, audience, signature, expiry,
58
+ subject type and required scopes. It consumes the issued pairwise subject.
59
+
60
+ `verify_dpop_proof` is a separate helper: call it for a verified `cnf.jkt`
61
+ token with the actual method/URL/access token and maintain a replay cache using
62
+ the returned `jti`. `authenticate` does not automatically enforce DPoP.
63
+ RAR helpers and route policy evaluators only narrow access. Grant-backed RAR
64
+ requires authenticated introspection; offline JWT verification cannot promise
65
+ immediate revocation or cancel an operation already running.
66
+
67
+ Version 1.x preserves the existing public verification API. Pin versions, run
68
+ the installed-artifact qualification on upgrades, and review release notes.
69
+ This package does not obtain, store, refresh or exchange OAuth credentials.
70
+
71
+ Release and compatibility evidence:
72
+ [RS SDK release guide](https://github.com/amliuyong/a-auth/blob/main/docs/RS_SDK_RELEASE.md).
@@ -0,0 +1,52 @@
1
+ # Agent Auth resource-server SDK
2
+
3
+ Python 3.10+ access-token verification for resource servers. Apache-2.0.
4
+
5
+ Install a qualified wheel or source distribution into an independent virtual
6
+ environment:
7
+
8
+ ```bash
9
+ python -m venv .venv
10
+ .venv/bin/python -m pip install /absolute/path/to/agent_auth_rs-1.0.1-py3-none-any.whl
11
+ ```
12
+
13
+ The fixed registry command is `python -m pip install agent_auth_rs==1.0.1`.
14
+ See the release guide below for verified registry availability and receipts.
15
+ The distribution name is `agent_auth_rs`; the existing Python import remains
16
+ `agent_auth_rs`.
17
+
18
+ ```python
19
+ from agent_auth_rs import RsSdk, RsSdkConfig, RoutePolicy
20
+
21
+ sdk = RsSdk(RsSdkConfig(
22
+ issuer="https://auth.example.com",
23
+ resource_id="https://mcp.example.com",
24
+ ))
25
+
26
+ def protected_resource(authorization_header):
27
+ result = sdk.authenticate(
28
+ authorization_header,
29
+ RoutePolicy(require_sub_type="user", require_scopes=["read"]),
30
+ )
31
+ if not result.ok:
32
+ return result.status, result.headers, None
33
+ return 200, {}, {"subject": result.token.sub}
34
+ ```
35
+
36
+ Configure the exact issuer and resource identifier of your deployment. The
37
+ SDK obtains public JWKS and rejects wrong issuer, audience, signature, expiry,
38
+ subject type and required scopes. It consumes the issued pairwise subject.
39
+
40
+ `verify_dpop_proof` is a separate helper: call it for a verified `cnf.jkt`
41
+ token with the actual method/URL/access token and maintain a replay cache using
42
+ the returned `jti`. `authenticate` does not automatically enforce DPoP.
43
+ RAR helpers and route policy evaluators only narrow access. Grant-backed RAR
44
+ requires authenticated introspection; offline JWT verification cannot promise
45
+ immediate revocation or cancel an operation already running.
46
+
47
+ Version 1.x preserves the existing public verification API. Pin versions, run
48
+ the installed-artifact qualification on upgrades, and review release notes.
49
+ This package does not obtain, store, refresh or exchange OAuth credentials.
50
+
51
+ Release and compatibility evidence:
52
+ [RS SDK release guide](https://github.com/amliuyong/a-auth/blob/main/docs/RS_SDK_RELEASE.md).
@@ -0,0 +1,14 @@
1
+ # Third-party dependencies
2
+
3
+ The SDK source is Apache-2.0, as specified in LICENSE. Runtime dependencies are
4
+ installed separately and retain their own licenses; they are not vendored into
5
+ the wheel or source distribution.
6
+
7
+ | Dependency | Declared range | License | Source |
8
+ | --- | --- | --- | --- |
9
+ | PyJWT | >=2.8 | MIT | <https://github.com/jpadilla/pyjwt> |
10
+ | cryptography | >=41 | Apache-2.0 OR BSD-3-Clause | <https://github.com/pyca/cryptography> |
11
+
12
+ Platform-dependent transitive dependencies retain the notices supplied in
13
+ their own distributions. Test and build tools are excluded from SDK runtime
14
+ dependencies.
@@ -0,0 +1,100 @@
1
+ """Agent Auth RS 校验 SDK(spec 010 P1b)—— MCP 资源服务器侧 access token 校验。
2
+
3
+ 决策真相源:docs/DESIGN §6/§2 / CONFORMANCE C8.2/C8.3/C8.4/C8.8。RS 侧只消费/校验,不派生 sub。
4
+ """
5
+
6
+ from .types import (
7
+ NAMESPACE,
8
+ AuthResult,
9
+ Jwk,
10
+ RarPolicy,
11
+ RoutePolicy,
12
+ RsSdkConfig,
13
+ ScopeImplications,
14
+ ScopeResolver,
15
+ VerifiedToken,
16
+ VerifyError,
17
+ )
18
+ from .sdk import RsSdk
19
+ from .authorization import (
20
+ create_scope_resolver,
21
+ derive_resource_metadata_url,
22
+ normalize_resource_id,
23
+ validate_resource_metadata_url,
24
+ validate_scope_token,
25
+ )
26
+ from .introspection import (
27
+ IntrospectionClient,
28
+ IntrospectionConfig,
29
+ IntrospectionResult,
30
+ )
31
+ from .rar import (
32
+ AccessRequest,
33
+ RarResult,
34
+ RAR_TYPE_V1,
35
+ PolicyDecision,
36
+ PolicyEvaluator,
37
+ enforce_rar,
38
+ extract_authorization_details,
39
+ )
40
+ from .dpop import (
41
+ DPoPResult,
42
+ verify_dpop_proof,
43
+ compute_jkt,
44
+ compute_ath,
45
+ normalize_htu,
46
+ )
47
+ from .payment import (
48
+ PAYMENT_EXECUTE_SCOPE,
49
+ PAYMENT_RAR_TYPE_V1,
50
+ PAYMENT_TERMS_DIGEST_DOMAIN,
51
+ PaymentAuthorizationError,
52
+ VerifiedPaymentAuthorization,
53
+ payment_terms_canonical_bytes,
54
+ payment_terms_digest,
55
+ validate_payment_terms,
56
+ verify_payment_authorization,
57
+ )
58
+
59
+ __all__ = [
60
+ "NAMESPACE",
61
+ "AuthResult",
62
+ "Jwk",
63
+ "RarPolicy",
64
+ "RoutePolicy",
65
+ "RsSdkConfig",
66
+ "ScopeImplications",
67
+ "ScopeResolver",
68
+ "VerifiedToken",
69
+ "VerifyError",
70
+ "RsSdk",
71
+ "create_scope_resolver",
72
+ "derive_resource_metadata_url",
73
+ "normalize_resource_id",
74
+ "validate_resource_metadata_url",
75
+ "validate_scope_token",
76
+ "IntrospectionClient",
77
+ "IntrospectionConfig",
78
+ "IntrospectionResult",
79
+ "AccessRequest",
80
+ "RarResult",
81
+ "RAR_TYPE_V1",
82
+ "PolicyDecision",
83
+ "PolicyEvaluator",
84
+ "enforce_rar",
85
+ "extract_authorization_details",
86
+ "DPoPResult",
87
+ "verify_dpop_proof",
88
+ "compute_jkt",
89
+ "compute_ath",
90
+ "normalize_htu",
91
+ "PAYMENT_EXECUTE_SCOPE",
92
+ "PAYMENT_RAR_TYPE_V1",
93
+ "PAYMENT_TERMS_DIGEST_DOMAIN",
94
+ "PaymentAuthorizationError",
95
+ "VerifiedPaymentAuthorization",
96
+ "payment_terms_canonical_bytes",
97
+ "payment_terms_digest",
98
+ "validate_payment_terms",
99
+ "verify_payment_authorization",
100
+ ]
@@ -0,0 +1,188 @@
1
+ """RFC 9728 challenge URL and explicit scope implication helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+ import re
7
+ from collections.abc import Mapping, Sequence
8
+ from urllib.parse import urlsplit
9
+
10
+ from .types import ScopeImplications, ScopeResolver
11
+
12
+ _SCOPE_TOKEN = re.compile(r"^[\x21\x23-\x5b\x5d-\x7e]+$")
13
+ _DOT_SEGMENT = re.compile(r"^(?:\.|%2e){1,2}$", re.IGNORECASE)
14
+ _URI_PATH = re.compile(
15
+ r"^(?:[a-z0-9\-._~!$&'()*+,;=:@/]|%[0-9a-f]{2})*$", re.IGNORECASE
16
+ )
17
+ _URI_QUERY = re.compile(
18
+ r"^(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*$", re.IGNORECASE
19
+ )
20
+ _CANONICAL_IPV4 = re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}$")
21
+ _NUMBERISH_HOST = re.compile(
22
+ r"^(?:0x[0-9a-f]+|\d+)(?:\.(?:0x[0-9a-f]+|\d+))*$", re.IGNORECASE
23
+ )
24
+ _PROTECTED_RESOURCE_WELL_KNOWN = "/.well-known/oauth-protected-resource"
25
+
26
+
27
+ def _validate_hostname(hostname: str, label: str) -> None:
28
+ if ":" in hostname:
29
+ try:
30
+ ipaddress.IPv6Address(hostname)
31
+ except ValueError as exc:
32
+ raise ValueError(f"{label} must use a valid IPv6 host") from exc
33
+ return
34
+ without_final_dot = hostname[:-1] if hostname.endswith(".") else hostname
35
+ labels = without_final_dot.split(".")
36
+ if any(
37
+ not part
38
+ or len(part) > 63
39
+ or re.fullmatch(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", part, re.IGNORECASE) is None
40
+ for part in labels
41
+ ):
42
+ raise ValueError(f"{label} must use a valid DNS host")
43
+
44
+
45
+ def _explicit_port(netloc: str) -> int | None:
46
+ if netloc.startswith("["):
47
+ suffix = netloc[netloc.index("]") + 1 :]
48
+ return int(suffix[1:]) if suffix.startswith(":") and len(suffix) > 1 else None
49
+ _, separator, port = netloc.rpartition(":")
50
+ return int(port) if separator and port else None
51
+
52
+
53
+ def _parse_https_url(value: str, label: str, allow_query: bool):
54
+ if (
55
+ not isinstance(value, str)
56
+ or not value
57
+ or any(ord(char) < 0x21 or ord(char) > 0x7E for char in value)
58
+ or '"' in value
59
+ or "\\" in value
60
+ ):
61
+ raise ValueError(f"{label} must contain only safe printable URI characters")
62
+ if re.match(r"^https://", value, re.IGNORECASE) is None:
63
+ raise ValueError(f"{label} must be an absolute HTTPS URL")
64
+
65
+ try:
66
+ parsed = urlsplit(value)
67
+ port = parsed.port
68
+ except ValueError as exc:
69
+ raise ValueError(f"{label} must be an absolute HTTPS URL") from exc
70
+ if parsed.scheme.lower() != "https" or not parsed.hostname:
71
+ raise ValueError(f"{label} must be an absolute HTTPS URL")
72
+ if parsed.username is not None or parsed.password is not None:
73
+ raise ValueError(f"{label} must not contain userinfo")
74
+ if "%" in parsed.netloc:
75
+ raise ValueError(f"{label} must not contain an encoded authority")
76
+ if (
77
+ _URI_PATH.fullmatch(parsed.path) is None
78
+ or _URI_QUERY.fullmatch(parsed.query) is None
79
+ ):
80
+ raise ValueError(f"{label} path and query must use valid RFC 3986 characters")
81
+ if "#" in value:
82
+ raise ValueError(f"{label} must not contain a fragment")
83
+ if not allow_query and "?" in value:
84
+ raise ValueError(f"{label} must not contain a query")
85
+ if not allow_query and any(
86
+ _DOT_SEGMENT.fullmatch(segment) for segment in parsed.path.split("/")
87
+ ):
88
+ raise ValueError(f"{label} must not contain dot path segments")
89
+ numeric_hostname = (
90
+ parsed.hostname[:-1] if parsed.hostname.endswith(".") else parsed.hostname
91
+ )
92
+ if _NUMBERISH_HOST.fullmatch(numeric_hostname):
93
+ parts = numeric_hostname.split(".")
94
+ if (
95
+ parsed.hostname.endswith(".")
96
+ or _CANONICAL_IPV4.fullmatch(numeric_hostname) is None
97
+ or any(int(part) > 255 for part in parts)
98
+ or any(len(part) > 1 and part.startswith("0") for part in parts)
99
+ ):
100
+ raise ValueError(f"{label} must use a canonical host")
101
+ _validate_hostname(parsed.hostname, label)
102
+ return parsed, port
103
+
104
+
105
+ def normalize_resource_id(resource_id: str) -> str:
106
+ """Validate and normalize the resource identifier used for exact audience checks."""
107
+ _parse_https_url(resource_id, "resource_id", allow_query=False)
108
+ return resource_id.rstrip("/")
109
+
110
+
111
+ def derive_resource_metadata_url(resource_id: str) -> str:
112
+ """Derive the RFC 9728 endpoint-path protected-resource metadata URL."""
113
+ normalized = normalize_resource_id(resource_id)
114
+ parsed, port = _parse_https_url(normalized, "resource_id", allow_query=False)
115
+ hostname = parsed.hostname.encode("idna").decode("ascii").lower()
116
+ if ":" in hostname:
117
+ hostname = f"[{ipaddress.IPv6Address(hostname).compressed}]"
118
+ configured_port = _explicit_port(parsed.netloc)
119
+ authority = hostname if configured_port is None else f"{hostname}:{configured_port}"
120
+ resource_path = parsed.path.rstrip("/")
121
+ if resource_path == "/":
122
+ resource_path = ""
123
+ return f"https://{authority}{_PROTECTED_RESOURCE_WELL_KNOWN}{resource_path}"
124
+
125
+
126
+ def validate_resource_metadata_url(resource_metadata_url: str) -> str:
127
+ """Validate an explicit challenge URL while preserving its configured spelling."""
128
+ _parse_https_url(resource_metadata_url, "resource_metadata_url", allow_query=True)
129
+ return resource_metadata_url
130
+
131
+
132
+ def validate_scope_token(scope: str) -> str:
133
+ """Validate one RFC 6749 scope-token before using it in a response header."""
134
+ if not isinstance(scope, str) or _SCOPE_TOKEN.fullmatch(scope) is None:
135
+ raise ValueError(
136
+ "scope values must be non-empty ASCII scope-token values without "
137
+ "whitespace, quotes, or backslashes"
138
+ )
139
+ return scope
140
+
141
+
142
+ def normalize_required_scopes(scopes: Sequence[str]) -> list[str]:
143
+ return [validate_scope_token(scope) for scope in scopes]
144
+
145
+
146
+ def create_scope_resolver(
147
+ implications: ScopeImplications | None = None,
148
+ ) -> ScopeResolver:
149
+ """Build a transitive resolver from explicit broader -> narrower declarations."""
150
+ source: Mapping[str, Sequence[str]] = implications or {}
151
+ graph: dict[str, set[str]] = {}
152
+ for broader, narrower_scopes in source.items():
153
+ validate_scope_token(broader)
154
+ graph[broader] = {validate_scope_token(scope) for scope in narrower_scopes}
155
+
156
+ visiting: set[str] = set()
157
+ visited: set[str] = set()
158
+
159
+ def visit(scope: str) -> None:
160
+ if scope in visiting:
161
+ raise ValueError(f"scope implication cycle includes {scope}")
162
+ if scope in visited:
163
+ return
164
+ visiting.add(scope)
165
+ for implied in graph.get(scope, set()):
166
+ visit(implied)
167
+ visiting.remove(scope)
168
+ visited.add(scope)
169
+
170
+ for scope in graph:
171
+ visit(scope)
172
+
173
+ def resolves(granted_scope: str, required_scope: str) -> bool:
174
+ if granted_scope == required_scope:
175
+ return True
176
+ pending = list(graph.get(granted_scope, set()))
177
+ seen: set[str] = set()
178
+ while pending:
179
+ candidate = pending.pop()
180
+ if candidate in seen:
181
+ continue
182
+ if candidate == required_scope:
183
+ return True
184
+ seen.add(candidate)
185
+ pending.extend(graph.get(candidate, set()))
186
+ return False
187
+
188
+ return resolves