buwigs-auth-sdk 0.2.0a1__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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,13 @@
1
+ include LICENSE
2
+ include NOTICE
3
+ include README.md
4
+ include pyproject.toml
5
+ recursive-include src/buwigs_auth_sdk *.py
6
+ prune tests
7
+ prune examples
8
+ prune artifacts
9
+ prune .venv
10
+ prune .pytest_cache
11
+ prune src/buwigs_auth_sdk.egg-info
12
+ exclude setup.cfg
13
+ global-exclude *.py[cod] *.pem *.key .env .env.*
@@ -0,0 +1,11 @@
1
+ Buwigs Auth SDK
2
+ Copyright 2026 Buwigs.
3
+
4
+ This distribution contains SDK source code authored and maintained by Buwigs.
5
+ No third-party implementation source is bundled in this package. Runtime
6
+ libraries are declared as package dependencies, distributed separately, and
7
+ remain subject to their own license terms and notices.
8
+
9
+ The Buwigs Auth server implementation and its private repository are separate
10
+ works and are not licensed under this notice or the Apache License 2.0 copy
11
+ accompanying this SDK package.
@@ -0,0 +1,132 @@
1
+ Metadata-Version: 2.4
2
+ Name: buwigs-auth-sdk
3
+ Version: 0.2.0a1
4
+ Summary: Buwigs Auth OIDC integration helpers
5
+ License-Expression: Apache-2.0
6
+ Classifier: Development Status :: 3 - Alpha
7
+ Classifier: Intended Audience :: Developers
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Topic :: Internet :: WWW/HTTP
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ License-File: NOTICE
18
+ Requires-Dist: PyJWT[crypto]==2.15.1
19
+ Requires-Dist: requests==2.34.2
20
+ Provides-Extra: fastapi
21
+ Requires-Dist: fastapi<1,>=0.115; extra == "fastapi"
22
+ Dynamic: license-file
23
+
24
+ # Buwigs Auth Python SDK
25
+
26
+ **Version 0.2.0a1 · alpha · Python 3.10+**
27
+
28
+ This package provides OIDC client and resource-server helpers for Python
29
+ applications. It validates Buwigs Auth tokens and returns an immutable
30
+ `(issuer, subject)` principal. Your application remains responsible for
31
+ mapping that identity to its own account, tenant, and permissions.
32
+
33
+ ## Install
34
+
35
+ ```sh
36
+ pip install buwigs-auth-sdk==0.2.0a1
37
+ ```
38
+
39
+ FastAPI support is optional:
40
+
41
+ ```sh
42
+ pip install 'buwigs-auth-sdk[fastapi]'
43
+ ```
44
+
45
+ ## Authorization Code + PKCE
46
+
47
+ Create a client with the exact issuer, client ID, API audience, and registered
48
+ redirect URI. Store state, nonce, and the PKCE verifier in a short-lived,
49
+ server-side transaction bound to the browser session. Consume the transaction
50
+ once in the callback.
51
+
52
+ ```python
53
+ from buwigs_auth_sdk import OidcClient
54
+
55
+ oidc = OidcClient(
56
+ issuer="https://auth.buwigs.com/realms/buwigs-local",
57
+ client_id="your-registered-client-id",
58
+ api_audience="your-api-audience",
59
+ redirect_uri="https://app.example.com/auth/callback",
60
+ )
61
+ transaction = oidc.authorization_request()
62
+ # Save transaction state, nonce, and verifier server-side before redirecting.
63
+ ```
64
+
65
+ At the callback, validate state, exchange the code, validate the ID token and
66
+ nonce, then establish your application's session:
67
+
68
+ ```python
69
+ oidc.validate_state(saved_state, returned_state)
70
+ tokens = oidc.exchange_code(code, saved_verifier, client_secret=server_secret)
71
+ principal = oidc.verify_id_token(tokens["id_token"], expected_nonce=saved_nonce)
72
+ api_principal = oidc.verify_access_token(tokens["access_token"])
73
+ ```
74
+
75
+ Only use `client_secret` in a trusted server process. Never send it to browser
76
+ or Electron code. Public clients must not have a client secret. Validate the
77
+ ID token before creating an application session and validate access tokens on
78
+ each protected resource request.
79
+
80
+ ## FastAPI resource-server validation
81
+
82
+ ```python
83
+ from fastapi import Depends, FastAPI
84
+ from buwigs_auth_sdk import OidcClient, Principal
85
+ from buwigs_auth_sdk.fastapi import principal_dependency
86
+
87
+ oidc = OidcClient(
88
+ issuer="https://auth.buwigs.com/realms/buwigs-local",
89
+ client_id="your-client-id",
90
+ api_audience="your-api-audience",
91
+ redirect_uri="https://app.example.com/auth/callback",
92
+ )
93
+ require_principal = principal_dependency(oidc)
94
+ app = FastAPI()
95
+
96
+ @app.get("/api/me")
97
+ def me(principal: Principal = Depends(require_principal)):
98
+ # Resolve subject in this application's own database and authorize there.
99
+ return {"auth_subject": principal.subject}
100
+ ```
101
+
102
+ The dependency validates a Bearer access token against the configured issuer,
103
+ RS256 signing keys, and API audience. It returns a generic unauthorized
104
+ response for missing or invalid tokens. It does not assign application roles.
105
+
106
+ ## Other OIDC helpers
107
+
108
+ The client also provides refresh-token exchange, token revocation, UserInfo
109
+ subject checking, and an RP-initiated logout URL. Persist rotated refresh
110
+ tokens atomically in your server-side session store. The SDK does not store
111
+ tokens, create sessions, or implement a login UI.
112
+
113
+ ## Security and support
114
+
115
+ - Use HTTPS issuer and redirect URLs in deployed applications.
116
+ - Bind state, nonce, and PKCE verifier to one browser transaction and consume
117
+ them once.
118
+ - Keep confidential client credentials in backend secret storage.
119
+ - Do not accept identity claims or roles from request bodies.
120
+ - Do not use email or phone as a substitute for the immutable subject.
121
+ - Pin the package version and review release notes before upgrading.
122
+
123
+ The service URL is the intended Buwigs issuer; verify its discovery document
124
+ and supported API version before integration. This alpha SDK is not a browser
125
+ authentication/session SDK and does not imply a security audit or OIDC
126
+ conformance certification.
127
+
128
+ ## License
129
+
130
+ This SDK source is licensed under Apache-2.0. See the bundled `LICENSE` and
131
+ `NOTICE`. Its runtime dependencies are distributed separately under their
132
+ respective licenses. The Buwigs Auth server is separate proprietary software.
@@ -0,0 +1,109 @@
1
+ # Buwigs Auth Python SDK
2
+
3
+ **Version 0.2.0a1 · alpha · Python 3.10+**
4
+
5
+ This package provides OIDC client and resource-server helpers for Python
6
+ applications. It validates Buwigs Auth tokens and returns an immutable
7
+ `(issuer, subject)` principal. Your application remains responsible for
8
+ mapping that identity to its own account, tenant, and permissions.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ pip install buwigs-auth-sdk==0.2.0a1
14
+ ```
15
+
16
+ FastAPI support is optional:
17
+
18
+ ```sh
19
+ pip install 'buwigs-auth-sdk[fastapi]'
20
+ ```
21
+
22
+ ## Authorization Code + PKCE
23
+
24
+ Create a client with the exact issuer, client ID, API audience, and registered
25
+ redirect URI. Store state, nonce, and the PKCE verifier in a short-lived,
26
+ server-side transaction bound to the browser session. Consume the transaction
27
+ once in the callback.
28
+
29
+ ```python
30
+ from buwigs_auth_sdk import OidcClient
31
+
32
+ oidc = OidcClient(
33
+ issuer="https://auth.buwigs.com/realms/buwigs-local",
34
+ client_id="your-registered-client-id",
35
+ api_audience="your-api-audience",
36
+ redirect_uri="https://app.example.com/auth/callback",
37
+ )
38
+ transaction = oidc.authorization_request()
39
+ # Save transaction state, nonce, and verifier server-side before redirecting.
40
+ ```
41
+
42
+ At the callback, validate state, exchange the code, validate the ID token and
43
+ nonce, then establish your application's session:
44
+
45
+ ```python
46
+ oidc.validate_state(saved_state, returned_state)
47
+ tokens = oidc.exchange_code(code, saved_verifier, client_secret=server_secret)
48
+ principal = oidc.verify_id_token(tokens["id_token"], expected_nonce=saved_nonce)
49
+ api_principal = oidc.verify_access_token(tokens["access_token"])
50
+ ```
51
+
52
+ Only use `client_secret` in a trusted server process. Never send it to browser
53
+ or Electron code. Public clients must not have a client secret. Validate the
54
+ ID token before creating an application session and validate access tokens on
55
+ each protected resource request.
56
+
57
+ ## FastAPI resource-server validation
58
+
59
+ ```python
60
+ from fastapi import Depends, FastAPI
61
+ from buwigs_auth_sdk import OidcClient, Principal
62
+ from buwigs_auth_sdk.fastapi import principal_dependency
63
+
64
+ oidc = OidcClient(
65
+ issuer="https://auth.buwigs.com/realms/buwigs-local",
66
+ client_id="your-client-id",
67
+ api_audience="your-api-audience",
68
+ redirect_uri="https://app.example.com/auth/callback",
69
+ )
70
+ require_principal = principal_dependency(oidc)
71
+ app = FastAPI()
72
+
73
+ @app.get("/api/me")
74
+ def me(principal: Principal = Depends(require_principal)):
75
+ # Resolve subject in this application's own database and authorize there.
76
+ return {"auth_subject": principal.subject}
77
+ ```
78
+
79
+ The dependency validates a Bearer access token against the configured issuer,
80
+ RS256 signing keys, and API audience. It returns a generic unauthorized
81
+ response for missing or invalid tokens. It does not assign application roles.
82
+
83
+ ## Other OIDC helpers
84
+
85
+ The client also provides refresh-token exchange, token revocation, UserInfo
86
+ subject checking, and an RP-initiated logout URL. Persist rotated refresh
87
+ tokens atomically in your server-side session store. The SDK does not store
88
+ tokens, create sessions, or implement a login UI.
89
+
90
+ ## Security and support
91
+
92
+ - Use HTTPS issuer and redirect URLs in deployed applications.
93
+ - Bind state, nonce, and PKCE verifier to one browser transaction and consume
94
+ them once.
95
+ - Keep confidential client credentials in backend secret storage.
96
+ - Do not accept identity claims or roles from request bodies.
97
+ - Do not use email or phone as a substitute for the immutable subject.
98
+ - Pin the package version and review release notes before upgrading.
99
+
100
+ The service URL is the intended Buwigs issuer; verify its discovery document
101
+ and supported API version before integration. This alpha SDK is not a browser
102
+ authentication/session SDK and does not imply a security audit or OIDC
103
+ conformance certification.
104
+
105
+ ## License
106
+
107
+ This SDK source is licensed under Apache-2.0. See the bundled `LICENSE` and
108
+ `NOTICE`. Its runtime dependencies are distributed separately under their
109
+ respective licenses. The Buwigs Auth server is separate proprietary software.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools==80.9.0", "wheel==0.45.1"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "buwigs-auth-sdk"
7
+ version = "0.2.0a1"
8
+ description = "Buwigs Auth OIDC integration helpers"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ requires-python = ">=3.10"
13
+ dependencies = ["PyJWT[crypto]==2.15.1", "requests==2.34.2"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Internet :: WWW/HTTP",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ fastapi = ["fastapi>=0.115,<1"]
27
+
28
+ [dependency-groups]
29
+ test = ["pytest>=8,<10", "fastapi>=0.115,<1", "httpx>=0.27,<1"]
30
+
31
+ [tool.setuptools]
32
+ packages = ["buwigs_auth_sdk"]
33
+ package-dir = { "" = "src" }
34
+ include-package-data = false
@@ -0,0 +1,5 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Buwigs Auth OIDC helpers. Authentication only; product authorization stays local."""
3
+ from .oidc import OidcClient, Principal, SdkError, create_pkce_pair, verify_access_token
4
+
5
+ __all__ = ["OidcClient", "Principal", "SdkError", "create_pkce_pair", "verify_access_token"]
@@ -0,0 +1,51 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """FastAPI helpers for validating Buwigs Auth access tokens.
3
+
4
+ FastAPI is an optional dependency. Import this module only in FastAPI services.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from typing import Annotated, Callable
10
+
11
+ from fastapi import Header, HTTPException
12
+
13
+ from .oidc import OidcClient, Principal, SdkError
14
+
15
+ _BEARER = re.compile(r"(?i)^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$")
16
+
17
+
18
+ def principal_dependency(client: OidcClient) -> Callable[..., Principal]:
19
+ """Create a FastAPI dependency that returns a cryptographically verified principal.
20
+
21
+ ``client`` must be configured with the trusted issuer and API audience for this
22
+ service. The sync dependency lets FastAPI run synchronous JWKS refreshes in its
23
+ worker pool. It never accepts identity values from request data.
24
+ """
25
+
26
+ def require_principal(authorization: Annotated[str | None, Header()] = None) -> Principal:
27
+ if authorization is None:
28
+ raise HTTPException(
29
+ status_code=401,
30
+ detail="authentication_required",
31
+ headers={"WWW-Authenticate": 'Bearer realm="buwigs-auth"'},
32
+ )
33
+ match = _BEARER.fullmatch(authorization)
34
+ if match is None:
35
+ raise HTTPException(
36
+ status_code=401,
37
+ detail="invalid_token",
38
+ headers={"WWW-Authenticate": 'Bearer error="invalid_token"'},
39
+ )
40
+ try:
41
+ return client.verify_access_token(match.group(1))
42
+ except SdkError as exc:
43
+ # The response deliberately hides issuer, key, parsing, and signature details.
44
+ raise HTTPException(
45
+ status_code=401,
46
+ detail="invalid_token",
47
+ headers={"WWW-Authenticate": 'Bearer error="invalid_token"'},
48
+ ) from exc
49
+
50
+ require_principal.__name__ = "require_buwigs_principal"
51
+ return require_principal
@@ -0,0 +1,360 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import hashlib
6
+ import secrets
7
+ import threading
8
+ import time
9
+ from dataclasses import dataclass
10
+ from hmac import compare_digest
11
+ from typing import Any
12
+ from urllib.parse import urlencode, urlsplit
13
+
14
+ import jwt
15
+ import requests
16
+
17
+
18
+ class SdkError(ValueError):
19
+ """Configuration, discovery, protocol, or token validation failed."""
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Principal:
24
+ issuer: str
25
+ subject: str
26
+ audience: tuple[str, ...]
27
+ claims: dict[str, Any]
28
+
29
+
30
+ def _https_url(value: str, *, allow_local_http: bool = False) -> bool:
31
+ parsed = urlsplit(value)
32
+ return parsed.scheme == "https" or (
33
+ allow_local_http and parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1"}
34
+ )
35
+
36
+
37
+ def create_pkce_pair() -> tuple[str, str]:
38
+ verifier = secrets.token_urlsafe(48)
39
+ digest = hashlib.sha256(verifier.encode("ascii")).digest()
40
+ challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
41
+ return verifier, challenge
42
+
43
+
44
+ class RefreshingJwks:
45
+ """Bounded cache with a serialized refresh and throttled unknown-kid misses."""
46
+
47
+ def __init__(self, uri: str, *, fetcher=None):
48
+ self.uri = uri
49
+ self.fetcher = fetcher or self._fetch_http
50
+ self._lock = threading.Lock()
51
+ self._keys: dict[str, jwt.PyJWK] = {}
52
+ self._expires_at = 0.0
53
+ self._last_refresh = 0.0
54
+
55
+ @staticmethod
56
+ def _fetch_http(uri: str):
57
+ response = requests.get(uri, timeout=5, allow_redirects=False)
58
+ if response.status_code != 200:
59
+ raise SdkError("JWKS endpoint unavailable")
60
+ if int(response.headers.get("Content-Length", "0") or 0) > 1_048_576:
61
+ raise SdkError("JWKS response is too large")
62
+ return response.json(), response.headers.get("Cache-Control", "")
63
+
64
+ def get_signing_key_from_jwt(self, token: str) -> jwt.PyJWK:
65
+ try:
66
+ header = jwt.get_unverified_header(token)
67
+ except Exception as exc:
68
+ raise SdkError("invalid JWT header") from exc
69
+ kid = header.get("kid")
70
+ if header.get("alg") != "RS256" or not isinstance(kid, str) or not kid:
71
+ raise SdkError("unknown signing key")
72
+ now = time.monotonic()
73
+ with self._lock:
74
+ if self._expires_at > now and kid in self._keys:
75
+ return self._keys[kid]
76
+ if self._last_refresh and now - self._last_refresh < 5:
77
+ raise SdkError("unknown signing key")
78
+ try:
79
+ jwks, cache_control = self.fetcher(self.uri)
80
+ if not isinstance(jwks, dict) or not isinstance(jwks.get("keys"), list) or len(jwks["keys"]) > 100:
81
+ raise SdkError("invalid JWKS document")
82
+ keys: dict[str, jwt.PyJWK] = {}
83
+ for item in jwks["keys"]:
84
+ if not isinstance(item, dict) or item.get("kty") != "RSA" or item.get("use", "sig") != "sig" or item.get("alg", "RS256") != "RS256":
85
+ continue
86
+ key_id = item.get("kid")
87
+ if isinstance(key_id, str) and key_id:
88
+ if any(private_member in item for private_member in ("d", "p", "q", "dp", "dq", "qi", "oth", "k")):
89
+ raise SdkError("JWKS unexpectedly contains private key material")
90
+ if key_id in keys:
91
+ raise SdkError("JWKS contains duplicate key identifiers")
92
+ keys[key_id] = jwt.PyJWK.from_dict(item, algorithm="RS256")
93
+ max_age = 300
94
+ for part in cache_control.split(","):
95
+ name, _, value = part.strip().partition("=")
96
+ if name.lower() == "max-age" and value.isdigit():
97
+ max_age = int(value)
98
+ self._keys = keys
99
+ self._expires_at = now + min(max(max_age, 30), 600)
100
+ self._last_refresh = now
101
+ except Exception as exc:
102
+ self._last_refresh = now
103
+ if isinstance(exc, SdkError):
104
+ raise
105
+ raise SdkError("JWKS endpoint unavailable") from exc
106
+ if kid not in self._keys:
107
+ raise SdkError("unknown signing key")
108
+ return self._keys[kid]
109
+
110
+
111
+ class OidcClient:
112
+ def __init__(self, issuer: str, client_id: str, api_audience: str, redirect_uri: str,
113
+ *, allow_local_http: bool = False):
114
+ if not issuer or not _https_url(issuer, allow_local_http=allow_local_http) or not client_id.strip() or not api_audience.strip():
115
+ raise SdkError("invalid OIDC configuration")
116
+ if not isinstance(redirect_uri, str) or not _https_url(redirect_uri, allow_local_http=allow_local_http):
117
+ raise SdkError("redirect URI must use HTTPS (except loopback development)")
118
+ self.issuer = issuer.rstrip("/")
119
+ self.client_id = client_id
120
+ self.api_audience = api_audience
121
+ self.redirect_uri = redirect_uri
122
+ self.allow_local_http = allow_local_http
123
+ issuer_parts = urlsplit(self.issuer)
124
+ redirect_parts = urlsplit(redirect_uri)
125
+ if issuer_parts.query or issuer_parts.fragment or issuer_parts.username or issuer_parts.password:
126
+ raise SdkError("invalid issuer URL")
127
+ if redirect_parts.query or redirect_parts.fragment or redirect_parts.username or redirect_parts.password:
128
+ raise SdkError("redirect URI cannot contain credentials, query, or fragment")
129
+ discovery_url = self.issuer + "/.well-known/openid-configuration"
130
+ response = requests.get(discovery_url, timeout=5, allow_redirects=False)
131
+ if response.status_code != 200:
132
+ raise SdkError("OIDC discovery failed")
133
+ discovery = response.json()
134
+ if discovery.get("issuer") != self.issuer:
135
+ raise SdkError("discovery issuer mismatch")
136
+ for endpoint in ("authorization_endpoint", "token_endpoint", "jwks_uri"):
137
+ url = discovery.get(endpoint, "")
138
+ if not _https_url(url, allow_local_http=allow_local_http):
139
+ raise SdkError("discovery contains an insecure endpoint")
140
+ endpoint_parts = urlsplit(url)
141
+ if (endpoint_parts.scheme, endpoint_parts.netloc) != (issuer_parts.scheme, issuer_parts.netloc) or endpoint_parts.query or endpoint_parts.fragment or endpoint_parts.username or endpoint_parts.password:
142
+ raise SdkError("discovery endpoint must use the configured issuer origin without credentials, query, or fragment")
143
+ if not endpoint_parts.path.startswith(issuer_parts.path.rstrip("/") + "/"):
144
+ raise SdkError("discovery endpoint must remain under the configured issuer path")
145
+ for endpoint in ("userinfo_endpoint", "revocation_endpoint", "end_session_endpoint"):
146
+ url = discovery.get(endpoint)
147
+ if url is None:
148
+ continue
149
+ if not isinstance(url, str) or not _https_url(url, allow_local_http=allow_local_http):
150
+ raise SdkError("discovery contains an insecure optional endpoint")
151
+ endpoint_parts = urlsplit(url)
152
+ if (endpoint_parts.scheme, endpoint_parts.netloc) != (issuer_parts.scheme, issuer_parts.netloc) or endpoint_parts.query or endpoint_parts.fragment or endpoint_parts.username or endpoint_parts.password:
153
+ raise SdkError("optional discovery endpoint must use the configured issuer origin")
154
+ if not endpoint_parts.path.startswith(issuer_parts.path.rstrip("/") + "/"):
155
+ raise SdkError("optional discovery endpoint must remain under the configured issuer path")
156
+ self.discovery = discovery
157
+ self.jwks = RefreshingJwks(discovery["jwks_uri"])
158
+
159
+ def authorization_request(
160
+ self,
161
+ scopes: tuple[str, ...] = ("openid", "profile"),
162
+ *,
163
+ require_fresh_authentication: bool = False,
164
+ ) -> dict[str, str]:
165
+ if not isinstance(require_fresh_authentication, bool):
166
+ raise SdkError("fresh-authentication option must be boolean")
167
+ verifier, challenge = create_pkce_pair()
168
+ state, nonce = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
169
+ parameters = {
170
+ "client_id": self.client_id, "redirect_uri": self.redirect_uri,
171
+ "response_type": "code", "response_mode": "query", "scope": " ".join(scopes),
172
+ "state": state, "nonce": nonce, "code_challenge": challenge,
173
+ "code_challenge_method": "S256",
174
+ }
175
+ if require_fresh_authentication:
176
+ parameters.update({"prompt": "login", "max_age": "0"})
177
+ query = urlencode(parameters)
178
+ return {"url": self.discovery["authorization_endpoint"] + "?" + query,
179
+ "state": state, "nonce": nonce, "verifier": verifier}
180
+
181
+ def validate_state(self, expected: str, received: str) -> None:
182
+ if not expected or not compare_digest(expected, received):
183
+ raise SdkError("OIDC state mismatch")
184
+
185
+ def exchange_code(self, code: str, verifier: str, client_secret: str | None = None) -> dict[str, Any]:
186
+ if not code or len(verifier) < 43 or len(verifier) > 128:
187
+ raise SdkError("invalid authorization response")
188
+ data: dict[str, str] = {"grant_type": "authorization_code", "code": code,
189
+ "redirect_uri": self.redirect_uri, "client_id": self.client_id,
190
+ "code_verifier": verifier}
191
+ auth = None
192
+ if client_secret is not None:
193
+ auth = (self.client_id, client_secret)
194
+ data.pop("client_id")
195
+ response = requests.post(self.discovery["token_endpoint"], data=data, auth=auth,
196
+ timeout=5, allow_redirects=False)
197
+ if response.status_code != 200:
198
+ raise SdkError("authorization code exchange failed")
199
+ return response.json()
200
+
201
+ def refresh_token(self, refresh_token: str, client_secret: str | None = None) -> dict[str, Any]:
202
+ """Exchange one refresh token and return the provider's rotation response unchanged.
203
+
204
+ The caller must atomically replace its securely stored refresh token. This
205
+ method intentionally does not store, retry, or serialize credentials.
206
+ """
207
+ if not isinstance(refresh_token, str) or not refresh_token:
208
+ raise SdkError("refresh token is required")
209
+ data = {"grant_type": "refresh_token", "refresh_token": refresh_token,
210
+ "client_id": self.client_id}
211
+ auth = None
212
+ if client_secret is not None:
213
+ auth = (self.client_id, client_secret)
214
+ data.pop("client_id")
215
+ response = requests.post(self.discovery["token_endpoint"], data=data, auth=auth,
216
+ timeout=5, allow_redirects=False)
217
+ if response.status_code != 200:
218
+ raise SdkError("refresh token exchange failed")
219
+ return response.json()
220
+
221
+ def revoke_token(self, token: str, *, token_type_hint: str = "refresh_token",
222
+ client_secret: str | None = None) -> None:
223
+ """Revoke a token through an advertised revocation endpoint, without retry."""
224
+ endpoint = self.discovery.get("revocation_endpoint")
225
+ if not endpoint:
226
+ raise SdkError("provider does not advertise token revocation")
227
+ if not isinstance(token, str) or not token or token_type_hint not in {"access_token", "refresh_token"}:
228
+ raise SdkError("invalid token revocation request")
229
+ data = {"token": token, "token_type_hint": token_type_hint,
230
+ "client_id": self.client_id}
231
+ auth = None
232
+ if client_secret is not None:
233
+ auth = (self.client_id, client_secret)
234
+ data.pop("client_id")
235
+ response = requests.post(endpoint, data=data, auth=auth, timeout=5,
236
+ allow_redirects=False)
237
+ if response.status_code != 200:
238
+ raise SdkError("token revocation failed")
239
+
240
+ def get_userinfo(self, access_token: str, authenticated_principal: Principal) -> dict[str, Any]:
241
+ """Fetch UserInfo and bind its subject to a previously verified principal."""
242
+ endpoint = self.discovery.get("userinfo_endpoint")
243
+ if not endpoint:
244
+ raise SdkError("provider does not advertise UserInfo")
245
+ if not isinstance(access_token, str) or not access_token:
246
+ raise SdkError("access token is required for UserInfo")
247
+ if authenticated_principal.issuer != self.issuer:
248
+ raise SdkError("UserInfo principal issuer mismatch")
249
+ response = requests.get(endpoint, headers={"Authorization": f"Bearer {access_token}"},
250
+ timeout=5, allow_redirects=False)
251
+ if response.status_code != 200:
252
+ raise SdkError("UserInfo request failed")
253
+ try:
254
+ claims = response.json()
255
+ except Exception as exc:
256
+ raise SdkError("UserInfo response is invalid") from exc
257
+ if not isinstance(claims, dict) or not isinstance(claims.get("sub"), str) or not compare_digest(claims["sub"], authenticated_principal.subject):
258
+ raise SdkError("UserInfo subject does not match the authenticated principal")
259
+ return claims
260
+
261
+ def end_session_url(self, *, id_token_hint: str | None = None,
262
+ post_logout_redirect_uri: str | None = None,
263
+ state: str | None = None) -> str:
264
+ """Build the advertised OIDC end-session URL; caller performs navigation."""
265
+ endpoint = self.discovery.get("end_session_endpoint")
266
+ if not endpoint:
267
+ raise SdkError("provider does not advertise an end-session endpoint")
268
+ if id_token_hint is not None and (not isinstance(id_token_hint, str) or not id_token_hint):
269
+ raise SdkError("invalid ID token hint")
270
+ if post_logout_redirect_uri is not None:
271
+ if not isinstance(post_logout_redirect_uri, str) or not _https_url(
272
+ post_logout_redirect_uri, allow_local_http=self.allow_local_http
273
+ ):
274
+ raise SdkError("post-logout redirect must use HTTPS (except loopback development)")
275
+ parsed = urlsplit(post_logout_redirect_uri)
276
+ if parsed.username or parsed.password or parsed.query or parsed.fragment or not state or len(state) < 16:
277
+ raise SdkError("post-logout redirect requires an exact URI and a strong state value")
278
+ if (parsed.scheme, parsed.netloc) != (urlsplit(self.redirect_uri).scheme, urlsplit(self.redirect_uri).netloc):
279
+ raise SdkError("post-logout redirect must use the configured client origin")
280
+ elif state is not None:
281
+ raise SdkError("logout state requires a post-logout redirect URI")
282
+ if id_token_hint is None and post_logout_redirect_uri is None:
283
+ raise SdkError("logout requires an ID token hint or post-logout redirect URI")
284
+ parameters = {}
285
+ if id_token_hint is not None:
286
+ parameters["id_token_hint"] = id_token_hint
287
+ if post_logout_redirect_uri is not None:
288
+ parameters["post_logout_redirect_uri"] = post_logout_redirect_uri
289
+ parameters["state"] = state or ""
290
+ separator = "&" if "?" in endpoint else "?"
291
+ return endpoint + separator + urlencode(parameters)
292
+
293
+ def verify_access_token(self, token: str, audience: str | None = None) -> Principal:
294
+ configured_audience = audience or self.api_audience
295
+ if configured_audience != self.api_audience:
296
+ raise SdkError("requested audience differs from configured audience")
297
+ return verify_access_token(token, issuer=self.issuer, audience=configured_audience,
298
+ jwks_client=self.jwks, allow_local_http=self.allow_local_http)
299
+
300
+ def verify_id_token(self, token: str, *, expected_nonce: str | None = None,
301
+ expected_nonce_hash: str | None = None,
302
+ max_auth_age_seconds: int | None = None) -> Principal:
303
+ if (expected_nonce is None) == (expected_nonce_hash is None):
304
+ raise SdkError("provide exactly one nonce expectation")
305
+ if max_auth_age_seconds is not None and (
306
+ isinstance(max_auth_age_seconds, bool)
307
+ or not isinstance(max_auth_age_seconds, int)
308
+ or max_auth_age_seconds < 0
309
+ ):
310
+ raise SdkError("maximum authentication age must be a non-negative integer")
311
+ try:
312
+ signing_key = self.jwks.get_signing_key_from_jwt(token)
313
+ claims = jwt.decode(token, signing_key.key, algorithms=["RS256"], issuer=self.issuer,
314
+ audience=self.client_id,
315
+ options={"require": ["exp", "iss", "aud", "sub", "nonce"],
316
+ "verify_exp": True, "verify_nbf": True}, leeway=0)
317
+ except Exception as exc:
318
+ raise SdkError("ID token validation failed") from exc
319
+ nonce = str(claims.get("nonce", ""))
320
+ matches = (
321
+ compare_digest(hashlib.sha256(nonce.encode("utf-8")).hexdigest(), expected_nonce_hash)
322
+ if expected_nonce_hash is not None
323
+ else compare_digest(nonce, expected_nonce or "")
324
+ )
325
+ if not matches:
326
+ raise SdkError("ID token nonce mismatch")
327
+ if max_auth_age_seconds is not None:
328
+ auth_time = claims.get("auth_time")
329
+ now = time.time()
330
+ if isinstance(auth_time, bool) or not isinstance(auth_time, int):
331
+ raise SdkError("ID token does not contain a valid auth_time")
332
+ if auth_time > now or now - auth_time > max_auth_age_seconds:
333
+ raise SdkError("ID token authentication is not recent")
334
+ raw_audience = claims.get("aud")
335
+ audiences = (raw_audience,) if isinstance(raw_audience, str) else tuple(raw_audience or ())
336
+ if (len(audiences) > 1 or claims.get("azp") is not None) and claims.get("azp") != self.client_id:
337
+ raise SdkError("ID token authorized party mismatch")
338
+ return Principal(self.issuer, claims["sub"], audiences, claims)
339
+
340
+
341
+ def verify_access_token(token: str, *, issuer: str, audience: str,
342
+ jwks_client: RefreshingJwks | None = None,
343
+ allow_local_http: bool = False) -> Principal:
344
+ if not _https_url(issuer, allow_local_http=allow_local_http) or not audience:
345
+ raise SdkError("trusted issuer and audience are required")
346
+ client = jwks_client or RefreshingJwks(issuer.rstrip("/") + "/protocol/openid-connect/certs")
347
+ try:
348
+ signing_key = client.get_signing_key_from_jwt(token)
349
+ claims = jwt.decode(token, signing_key.key, algorithms=["RS256"], issuer=issuer,
350
+ audience=audience, options={"require": ["exp", "iss", "aud", "sub"],
351
+ "verify_exp": True, "verify_nbf": True},
352
+ leeway=0)
353
+ except Exception as exc:
354
+ raise SdkError("access token validation failed") from exc
355
+ subject = claims.get("sub")
356
+ raw_audience = claims.get("aud")
357
+ audiences = (raw_audience,) if isinstance(raw_audience, str) else tuple(raw_audience or ())
358
+ if not isinstance(subject, str) or not subject or audience not in audiences:
359
+ raise SdkError("access token lacks a valid subject or audience")
360
+ return Principal(issuer=issuer, subject=subject, audience=audiences, claims=claims)