swarmauri_auth_idp_gitlab 0.2.0.dev5__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.
- swarmauri_auth_idp_gitlab-0.2.0.dev5/LICENSE +201 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/PKG-INFO +123 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/README.md +94 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/pyproject.toml +87 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/swarmauri_auth_idp_gitlab/GitLabOAuth20AppClient.py +62 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/swarmauri_auth_idp_gitlab/GitLabOAuth20Login.py +30 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/swarmauri_auth_idp_gitlab/GitLabOAuth21AppClient.py +106 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/swarmauri_auth_idp_gitlab/GitLabOAuth21Login.py +31 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/swarmauri_auth_idp_gitlab/GitLabOAuthLoginMixin.py +94 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/swarmauri_auth_idp_gitlab/GitLabOIDC10AppClient.py +74 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/swarmauri_auth_idp_gitlab/GitLabOIDC10Login.py +31 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/swarmauri_auth_idp_gitlab/GitLabOIDCLoginMixin.py +142 -0
- swarmauri_auth_idp_gitlab-0.2.0.dev5/swarmauri_auth_idp_gitlab/__init__.py +17 -0
|
@@ -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 [2025] [Jacob Stewart @ Swarmauri]
|
|
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,123 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: swarmauri_auth_idp_gitlab
|
|
3
|
+
Version: 0.2.0.dev5
|
|
4
|
+
Summary: GitLab OAuth 2.0 / OAuth 2.1 / OIDC 1.0 identity provider implementations for Swarmauri
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: swarmauri,sdk,experimental,identity,oauth2,oauth21,oidc,gitlab,idp
|
|
8
|
+
Author: Jacob Stewart
|
|
9
|
+
Author-email: jacob@swarmauri.com
|
|
10
|
+
Requires-Python: >=3.10,<3.13
|
|
11
|
+
Classifier: Development Status :: 1 - Planning
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Natural Language :: English
|
|
15
|
+
Classifier: Programming Language :: Python
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
22
|
+
Classifier: Topic :: Security :: Cryptography
|
|
23
|
+
Requires-Dist: httpx (>=0.27)
|
|
24
|
+
Requires-Dist: pyjwt[crypto] (>=2.8)
|
|
25
|
+
Requires-Dist: swarmauri_base
|
|
26
|
+
Requires-Dist: swarmauri_core
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+

|
|
30
|
+
|
|
31
|
+
<p align="center">
|
|
32
|
+
<a href="https://pypi.org/project/swarmauri_auth_idp_gitlab/">
|
|
33
|
+
<img src="https://img.shields.io/pypi/dm/swarmauri_auth_idp_gitlab" alt="PyPI - Downloads"/></a>
|
|
34
|
+
<a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/swarmauri_auth_idp_gitlab/">
|
|
35
|
+
<img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/swarmauri_auth_idp_gitlab.svg"/></a>
|
|
36
|
+
<a href="https://pypi.org/project/swarmauri_auth_idp_gitlab/">
|
|
37
|
+
<img src="https://img.shields.io/pypi/pyversions/swarmauri_auth_idp_gitlab" alt="PyPI - Python Version"/></a>
|
|
38
|
+
<a href="https://pypi.org/project/swarmauri_auth_idp_gitlab/">
|
|
39
|
+
<img src="https://img.shields.io/pypi/l/swarmauri_auth_idp_gitlab" alt="PyPI - License"/></a>
|
|
40
|
+
<a href="https://pypi.org/project/swarmauri_auth_idp_gitlab/">
|
|
41
|
+
<img src="https://img.shields.io/pypi/v/swarmauri_auth_idp_gitlab?label=swarmauri_auth_idp_gitlab&color=green" alt="PyPI - swarmauri_auth_idp_gitlab"/></a>
|
|
42
|
+
</p>
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
# Swarmauri Auth IDP GitLab
|
|
47
|
+
|
|
48
|
+
GitLab OAuth 2.0 / OAuth 2.1 / OIDC 1.0 identity providers and app clients packaged for Swarmauri deployments.
|
|
49
|
+
|
|
50
|
+
## Features
|
|
51
|
+
|
|
52
|
+
- Authorization Code flows with PKCE and HMAC-signed state payloads for GitLab SaaS or self-managed.
|
|
53
|
+
- Discovery-driven OAuth 2.1 & OIDC login that validates ID tokens and hydrates profile details.
|
|
54
|
+
- Client credentials helpers that support shared secrets and JWT assertions.
|
|
55
|
+
- Retry-aware HTTP integration with GitLab REST API v4 and OIDC endpoints.
|
|
56
|
+
- ComponentBase-compatible models registered under `swarmauri.auth_idp` entry points.
|
|
57
|
+
|
|
58
|
+
## Installation
|
|
59
|
+
|
|
60
|
+
### pip
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install swarmauri_auth_idp_gitlab
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### uv (project)
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
uv add swarmauri_auth_idp_gitlab
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### uv (environment)
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
uv pip install swarmauri_auth_idp_gitlab
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Usage
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
import asyncio
|
|
82
|
+
from pydantic import SecretBytes, SecretStr
|
|
83
|
+
from swarmauri_auth_idp_gitlab import GitLabOAuth20Login
|
|
84
|
+
|
|
85
|
+
login = GitLabOAuth20Login(
|
|
86
|
+
base_url="https://gitlab.example",
|
|
87
|
+
client_id="gitlab-client-id",
|
|
88
|
+
client_secret=SecretStr("gitlab-client-secret"),
|
|
89
|
+
redirect_uri="https://app.example.com/callback",
|
|
90
|
+
state_secret=SecretBytes(b"replace-with-random-bytes"),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
async def run_flow() -> None:
|
|
94
|
+
auth = await login.auth_url()
|
|
95
|
+
print(auth["url"])
|
|
96
|
+
# Redirect the browser to `auth["url"]`, then capture the callback `code` and `state`.
|
|
97
|
+
# Later, call `login.exchange_and_identity(code, state)` inside your callback handler.
|
|
98
|
+
|
|
99
|
+
asyncio.run(run_flow())
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Workflow Summary
|
|
103
|
+
|
|
104
|
+
1. Call `auth_url()` and redirect the browser to the returned URL.
|
|
105
|
+
2. Persist the `state` and verify it during the callback handler.
|
|
106
|
+
3. Exchange the authorization code through `exchange_and_identity()` to obtain tokens and profile metadata.
|
|
107
|
+
4. Instantiate `GitLabOAuth21AppClient` or `GitLabOIDC10AppClient` to fetch service tokens for background jobs.
|
|
108
|
+
|
|
109
|
+
## Entry Points
|
|
110
|
+
|
|
111
|
+
- `swarmauri.auth_idp:GitLabOAuth20Login`
|
|
112
|
+
- `swarmauri.auth_idp:GitLabOAuth21Login`
|
|
113
|
+
- `swarmauri.auth_idp:GitLabOIDC10Login`
|
|
114
|
+
- `swarmauri.auth_idp:GitLabOAuth20AppClient`
|
|
115
|
+
- `swarmauri.auth_idp:GitLabOAuth21AppClient`
|
|
116
|
+
- `swarmauri.auth_idp:GitLabOIDC10AppClient`
|
|
117
|
+
|
|
118
|
+
## Contributing
|
|
119
|
+
|
|
120
|
+
To contribute to swarmauri-sdk, review the
|
|
121
|
+
[guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/CONTRIBUTING.md)
|
|
122
|
+
which cover development workflow, testing, and coding standards.
|
|
123
|
+
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://pypi.org/project/swarmauri_auth_idp_gitlab/">
|
|
5
|
+
<img src="https://img.shields.io/pypi/dm/swarmauri_auth_idp_gitlab" alt="PyPI - Downloads"/></a>
|
|
6
|
+
<a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/swarmauri_auth_idp_gitlab/">
|
|
7
|
+
<img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/swarmauri_auth_idp_gitlab.svg"/></a>
|
|
8
|
+
<a href="https://pypi.org/project/swarmauri_auth_idp_gitlab/">
|
|
9
|
+
<img src="https://img.shields.io/pypi/pyversions/swarmauri_auth_idp_gitlab" alt="PyPI - Python Version"/></a>
|
|
10
|
+
<a href="https://pypi.org/project/swarmauri_auth_idp_gitlab/">
|
|
11
|
+
<img src="https://img.shields.io/pypi/l/swarmauri_auth_idp_gitlab" alt="PyPI - License"/></a>
|
|
12
|
+
<a href="https://pypi.org/project/swarmauri_auth_idp_gitlab/">
|
|
13
|
+
<img src="https://img.shields.io/pypi/v/swarmauri_auth_idp_gitlab?label=swarmauri_auth_idp_gitlab&color=green" alt="PyPI - swarmauri_auth_idp_gitlab"/></a>
|
|
14
|
+
</p>
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
# Swarmauri Auth IDP GitLab
|
|
19
|
+
|
|
20
|
+
GitLab OAuth 2.0 / OAuth 2.1 / OIDC 1.0 identity providers and app clients packaged for Swarmauri deployments.
|
|
21
|
+
|
|
22
|
+
## Features
|
|
23
|
+
|
|
24
|
+
- Authorization Code flows with PKCE and HMAC-signed state payloads for GitLab SaaS or self-managed.
|
|
25
|
+
- Discovery-driven OAuth 2.1 & OIDC login that validates ID tokens and hydrates profile details.
|
|
26
|
+
- Client credentials helpers that support shared secrets and JWT assertions.
|
|
27
|
+
- Retry-aware HTTP integration with GitLab REST API v4 and OIDC endpoints.
|
|
28
|
+
- ComponentBase-compatible models registered under `swarmauri.auth_idp` entry points.
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
### pip
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install swarmauri_auth_idp_gitlab
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### uv (project)
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
uv add swarmauri_auth_idp_gitlab
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### uv (environment)
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
uv pip install swarmauri_auth_idp_gitlab
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import asyncio
|
|
54
|
+
from pydantic import SecretBytes, SecretStr
|
|
55
|
+
from swarmauri_auth_idp_gitlab import GitLabOAuth20Login
|
|
56
|
+
|
|
57
|
+
login = GitLabOAuth20Login(
|
|
58
|
+
base_url="https://gitlab.example",
|
|
59
|
+
client_id="gitlab-client-id",
|
|
60
|
+
client_secret=SecretStr("gitlab-client-secret"),
|
|
61
|
+
redirect_uri="https://app.example.com/callback",
|
|
62
|
+
state_secret=SecretBytes(b"replace-with-random-bytes"),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
async def run_flow() -> None:
|
|
66
|
+
auth = await login.auth_url()
|
|
67
|
+
print(auth["url"])
|
|
68
|
+
# Redirect the browser to `auth["url"]`, then capture the callback `code` and `state`.
|
|
69
|
+
# Later, call `login.exchange_and_identity(code, state)` inside your callback handler.
|
|
70
|
+
|
|
71
|
+
asyncio.run(run_flow())
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Workflow Summary
|
|
75
|
+
|
|
76
|
+
1. Call `auth_url()` and redirect the browser to the returned URL.
|
|
77
|
+
2. Persist the `state` and verify it during the callback handler.
|
|
78
|
+
3. Exchange the authorization code through `exchange_and_identity()` to obtain tokens and profile metadata.
|
|
79
|
+
4. Instantiate `GitLabOAuth21AppClient` or `GitLabOIDC10AppClient` to fetch service tokens for background jobs.
|
|
80
|
+
|
|
81
|
+
## Entry Points
|
|
82
|
+
|
|
83
|
+
- `swarmauri.auth_idp:GitLabOAuth20Login`
|
|
84
|
+
- `swarmauri.auth_idp:GitLabOAuth21Login`
|
|
85
|
+
- `swarmauri.auth_idp:GitLabOIDC10Login`
|
|
86
|
+
- `swarmauri.auth_idp:GitLabOAuth20AppClient`
|
|
87
|
+
- `swarmauri.auth_idp:GitLabOAuth21AppClient`
|
|
88
|
+
- `swarmauri.auth_idp:GitLabOIDC10AppClient`
|
|
89
|
+
|
|
90
|
+
## Contributing
|
|
91
|
+
|
|
92
|
+
To contribute to swarmauri-sdk, review the
|
|
93
|
+
[guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/CONTRIBUTING.md)
|
|
94
|
+
which cover development workflow, testing, and coding standards.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "swarmauri_auth_idp_gitlab"
|
|
3
|
+
version = "0.2.0.dev5"
|
|
4
|
+
description = "GitLab OAuth 2.0 / OAuth 2.1 / OIDC 1.0 identity provider implementations for Swarmauri"
|
|
5
|
+
license = "Apache-2.0"
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
requires-python = ">=3.10,<3.13"
|
|
8
|
+
repository = "https://github.com/swarmauri/swarmauri-sdk"
|
|
9
|
+
authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 1 - Planning",
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"License :: OSI Approved :: Apache Software License",
|
|
14
|
+
"Natural Language :: English",
|
|
15
|
+
"Programming Language :: Python",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
22
|
+
"Topic :: Security :: Cryptography",
|
|
23
|
+
]
|
|
24
|
+
keywords = [
|
|
25
|
+
"swarmauri",
|
|
26
|
+
"sdk",
|
|
27
|
+
"experimental",
|
|
28
|
+
"identity",
|
|
29
|
+
"oauth2",
|
|
30
|
+
"oauth21",
|
|
31
|
+
"oidc",
|
|
32
|
+
"gitlab",
|
|
33
|
+
"idp",
|
|
34
|
+
]
|
|
35
|
+
dependencies = [
|
|
36
|
+
"swarmauri_core",
|
|
37
|
+
"swarmauri_base",
|
|
38
|
+
"httpx>=0.27",
|
|
39
|
+
"pyjwt[crypto]>=2.8",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[project.entry-points.'swarmauri.auth_idp']
|
|
43
|
+
GitLabOAuth20Login = "swarmauri_auth_idp_gitlab:GitLabOAuth20Login"
|
|
44
|
+
GitLabOAuth21Login = "swarmauri_auth_idp_gitlab:GitLabOAuth21Login"
|
|
45
|
+
GitLabOIDC10Login = "swarmauri_auth_idp_gitlab:GitLabOIDC10Login"
|
|
46
|
+
GitLabOAuth20AppClient = "swarmauri_auth_idp_gitlab:GitLabOAuth20AppClient"
|
|
47
|
+
GitLabOAuth21AppClient = "swarmauri_auth_idp_gitlab:GitLabOAuth21AppClient"
|
|
48
|
+
GitLabOIDC10AppClient = "swarmauri_auth_idp_gitlab:GitLabOIDC10AppClient"
|
|
49
|
+
|
|
50
|
+
[tool.uv.sources]
|
|
51
|
+
swarmauri_tests_pylicense = { workspace = true }
|
|
52
|
+
swarmauri_core = { workspace = true }
|
|
53
|
+
swarmauri_base = { workspace = true }
|
|
54
|
+
|
|
55
|
+
[tool.pytest.ini_options]
|
|
56
|
+
markers = [
|
|
57
|
+
"test: standard test",
|
|
58
|
+
"unit: Unit tests",
|
|
59
|
+
"i9n: Integration tests",
|
|
60
|
+
"r8n: Regression tests",
|
|
61
|
+
"acceptance: Acceptance tests",
|
|
62
|
+
"perf: Performance tests",
|
|
63
|
+
"example: Documentation examples",
|
|
64
|
+
]
|
|
65
|
+
timeout = 300
|
|
66
|
+
log_cli = true
|
|
67
|
+
log_cli_level = "INFO"
|
|
68
|
+
log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
|
|
69
|
+
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
|
|
70
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
71
|
+
addopts = "--pylicense-accept-deps=sniffio"
|
|
72
|
+
|
|
73
|
+
[dependency-groups]
|
|
74
|
+
dev = [
|
|
75
|
+
"pytest>=8.0",
|
|
76
|
+
"pytest-asyncio>=0.24.0",
|
|
77
|
+
"pytest-xdist>=3.6.1",
|
|
78
|
+
"pytest-json-report>=1.5.0",
|
|
79
|
+
"pytest-timeout>=2.3.1",
|
|
80
|
+
"pytest-benchmark>=4.0.0",
|
|
81
|
+
"ruff>=0.9.9",
|
|
82
|
+
"swarmauri_tests_pylicense",
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
[build-system]
|
|
86
|
+
requires = ["poetry-core>=1.0.0"]
|
|
87
|
+
build-backend = "poetry.core.masonry.api"
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""GitLab OAuth 2.0 client credentials app client implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Callable, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
from pydantic import ConfigDict, Field, SecretStr
|
|
9
|
+
|
|
10
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
11
|
+
from swarmauri_base.auth_idp import OAuth20AppClientBase
|
|
12
|
+
from swarmauri_base.auth_idp.http import RetryingAsyncClient
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@ComponentBase.register_type(OAuth20AppClientBase, "GitLabOAuth20AppClient")
|
|
16
|
+
class GitLabOAuth20AppClient(OAuth20AppClientBase):
|
|
17
|
+
"""Request machine-to-machine tokens from the GitLab OAuth 2.0 endpoint."""
|
|
18
|
+
|
|
19
|
+
model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
|
|
20
|
+
|
|
21
|
+
base_url: str
|
|
22
|
+
client_id: str
|
|
23
|
+
client_secret: SecretStr
|
|
24
|
+
cache_skew_seconds: int = Field(default=30, ge=0)
|
|
25
|
+
http_client_factory: Callable[[], RetryingAsyncClient] = Field(
|
|
26
|
+
default=RetryingAsyncClient, exclude=True, repr=False
|
|
27
|
+
)
|
|
28
|
+
cached_token: Optional[Tuple[str, float]] = Field(
|
|
29
|
+
default=None, exclude=True, repr=False
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
def _token_endpoint(self) -> str:
|
|
33
|
+
return f"{self.base_url.rstrip('/')}/oauth/token"
|
|
34
|
+
|
|
35
|
+
def _client_secret_value(self) -> str:
|
|
36
|
+
return self.client_secret.get_secret_value()
|
|
37
|
+
|
|
38
|
+
async def _fetch_token(self, scope: Optional[str]) -> Tuple[str, float]:
|
|
39
|
+
form = {"grant_type": "client_credentials"}
|
|
40
|
+
if scope:
|
|
41
|
+
form["scope"] = scope
|
|
42
|
+
auth = (self.client_id, self._client_secret_value())
|
|
43
|
+
async with self.http_client_factory() as client:
|
|
44
|
+
response = await client.post_retry(
|
|
45
|
+
self._token_endpoint(),
|
|
46
|
+
data=form,
|
|
47
|
+
auth=auth,
|
|
48
|
+
headers={"Accept": "application/json"},
|
|
49
|
+
)
|
|
50
|
+
response.raise_for_status()
|
|
51
|
+
payload = response.json()
|
|
52
|
+
expires_at = time.time() + int(payload.get("expires_in", 3600))
|
|
53
|
+
return payload["access_token"], expires_at
|
|
54
|
+
|
|
55
|
+
async def access_token(self, scope: Optional[str] = None) -> str:
|
|
56
|
+
cached = self.cached_token
|
|
57
|
+
now = time.time()
|
|
58
|
+
if cached and now < cached[1] - self.cache_skew_seconds:
|
|
59
|
+
return cached[0]
|
|
60
|
+
token, expires_at = await self._fetch_token(scope)
|
|
61
|
+
self.cached_token = (token, expires_at)
|
|
62
|
+
return token
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""GitLab OAuth 2.0 Authorization Code login implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Mapping
|
|
6
|
+
|
|
7
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
8
|
+
from swarmauri_base.auth_idp import OAuth20LoginBase
|
|
9
|
+
|
|
10
|
+
from .GitLabOAuthLoginMixin import GitLabOAuthLoginMixin
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@ComponentBase.register_type(OAuth20LoginBase, "GitLabOAuth20Login")
|
|
14
|
+
class GitLabOAuth20Login(GitLabOAuthLoginMixin, OAuth20LoginBase):
|
|
15
|
+
"""Implement the GitLab OAuth 2.0 PKCE flow with identity hydration."""
|
|
16
|
+
|
|
17
|
+
async def auth_url(self) -> Mapping[str, str]:
|
|
18
|
+
payload = await self._auth_payload()
|
|
19
|
+
return {"url": payload["url"], "state": payload["state"]}
|
|
20
|
+
|
|
21
|
+
async def exchange_and_identity(self, code: str, state: str) -> Mapping[str, Any]:
|
|
22
|
+
tokens = await self._exchange_tokens(code, state)
|
|
23
|
+
profile = await self._fetch_profile(tokens["access_token"])
|
|
24
|
+
return {
|
|
25
|
+
"issuer": "gitlab-oauth20",
|
|
26
|
+
"sub": str(profile.get("id")),
|
|
27
|
+
"email": profile.get("email") or profile.get("public_email"),
|
|
28
|
+
"name": profile.get("name") or profile.get("username"),
|
|
29
|
+
"raw": {"tokens": tokens, "user": profile},
|
|
30
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""GitLab OAuth 2.1 client credentials app client implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Callable, Dict, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
import jwt
|
|
10
|
+
from pydantic import ConfigDict, Field, SecretStr
|
|
11
|
+
|
|
12
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
13
|
+
from swarmauri_base.auth_idp import OAuth21AppClientBase
|
|
14
|
+
from swarmauri_base.auth_idp.http import RetryingAsyncClient
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@ComponentBase.register_type(OAuth21AppClientBase, "GitLabOAuth21AppClient")
|
|
18
|
+
class GitLabOAuth21AppClient(OAuth21AppClientBase):
|
|
19
|
+
"""Request OAuth 2.1 client credentials tokens from GitLab."""
|
|
20
|
+
|
|
21
|
+
model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
|
|
22
|
+
|
|
23
|
+
base_url: str
|
|
24
|
+
client_id: str
|
|
25
|
+
client_secret: Optional[SecretStr] = None
|
|
26
|
+
private_key_jwk: Optional[Dict[str, Any]] = None
|
|
27
|
+
cache_skew_seconds: int = Field(default=30, ge=0)
|
|
28
|
+
http_client_factory: Callable[[], RetryingAsyncClient] = Field(
|
|
29
|
+
default=RetryingAsyncClient, exclude=True, repr=False
|
|
30
|
+
)
|
|
31
|
+
cached_token: Optional[Tuple[str, float]] = Field(
|
|
32
|
+
default=None, exclude=True, repr=False
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
def _token_endpoint(self) -> str:
|
|
36
|
+
return f"{self.base_url.rstrip('/')}/oauth/token"
|
|
37
|
+
|
|
38
|
+
def _client_secret_value(self) -> Optional[str]:
|
|
39
|
+
return self.client_secret.get_secret_value() if self.client_secret else None
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def _load_private_key(jwk_payload: Dict[str, Any], algorithm: str) -> Any:
|
|
43
|
+
serialized = json.dumps(jwk_payload)
|
|
44
|
+
if algorithm.upper().startswith("ES"):
|
|
45
|
+
return jwt.algorithms.ECAlgorithm.from_jwk(serialized)
|
|
46
|
+
return jwt.algorithms.RSAAlgorithm.from_jwk(serialized)
|
|
47
|
+
|
|
48
|
+
def _client_assertion_body(self) -> Dict[str, str]:
|
|
49
|
+
if not self.private_key_jwk:
|
|
50
|
+
return {}
|
|
51
|
+
algorithm = self.private_key_jwk.get("alg", "RS256")
|
|
52
|
+
key = self._load_private_key(self.private_key_jwk, algorithm)
|
|
53
|
+
now = int(time.time())
|
|
54
|
+
headers: Dict[str, str] = {}
|
|
55
|
+
if kid := self.private_key_jwk.get("kid"):
|
|
56
|
+
headers["kid"] = kid
|
|
57
|
+
payload = {
|
|
58
|
+
"iss": self.client_id,
|
|
59
|
+
"sub": self.client_id,
|
|
60
|
+
"aud": self._token_endpoint(),
|
|
61
|
+
"iat": now,
|
|
62
|
+
"exp": now + 300,
|
|
63
|
+
"jti": str(now),
|
|
64
|
+
}
|
|
65
|
+
assertion = jwt.encode(
|
|
66
|
+
payload, key=key, algorithm=algorithm, headers=headers or None
|
|
67
|
+
)
|
|
68
|
+
return {
|
|
69
|
+
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
|
|
70
|
+
"client_assertion": assertion,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async def _fetch_token(self, scope: Optional[str]) -> Tuple[str, float]:
|
|
74
|
+
form = {"grant_type": "client_credentials"}
|
|
75
|
+
if scope:
|
|
76
|
+
form["scope"] = scope
|
|
77
|
+
body = self._client_assertion_body()
|
|
78
|
+
auth = None
|
|
79
|
+
if body:
|
|
80
|
+
form["client_id"] = self.client_id
|
|
81
|
+
else:
|
|
82
|
+
secret = self._client_secret_value()
|
|
83
|
+
if not secret:
|
|
84
|
+
raise ValueError("client_secret or private_key_jwk must be provided")
|
|
85
|
+
auth = (self.client_id, secret)
|
|
86
|
+
payload = {**form, **body}
|
|
87
|
+
async with self.http_client_factory() as client:
|
|
88
|
+
response = await client.post_retry(
|
|
89
|
+
self._token_endpoint(),
|
|
90
|
+
data=payload,
|
|
91
|
+
auth=auth,
|
|
92
|
+
headers={"Accept": "application/json"},
|
|
93
|
+
)
|
|
94
|
+
response.raise_for_status()
|
|
95
|
+
data = response.json()
|
|
96
|
+
expires_at = time.time() + int(data.get("expires_in", 3600))
|
|
97
|
+
return data["access_token"], expires_at
|
|
98
|
+
|
|
99
|
+
async def access_token(self, scope: Optional[str] = None) -> str:
|
|
100
|
+
cached = self.cached_token
|
|
101
|
+
now = time.time()
|
|
102
|
+
if cached and now < cached[1] - self.cache_skew_seconds:
|
|
103
|
+
return cached[0]
|
|
104
|
+
token, expires_at = await self._fetch_token(scope)
|
|
105
|
+
self.cached_token = (token, expires_at)
|
|
106
|
+
return token
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""GitLab OAuth 2.1 Authorization Code login implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Mapping
|
|
6
|
+
|
|
7
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
8
|
+
from swarmauri_base.auth_idp import OAuth21LoginBase
|
|
9
|
+
|
|
10
|
+
from .GitLabOIDCLoginMixin import GitLabOIDCLoginMixin
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@ComponentBase.register_type(OAuth21LoginBase, "GitLabOAuth21Login")
|
|
14
|
+
class GitLabOAuth21Login(GitLabOIDCLoginMixin, OAuth21LoginBase):
|
|
15
|
+
"""Implement the GitLab OAuth 2.1 Authorization Code flow via OIDC discovery."""
|
|
16
|
+
|
|
17
|
+
async def auth_url(self) -> Mapping[str, str]:
|
|
18
|
+
payload = await self._auth_payload()
|
|
19
|
+
return {"url": payload["url"], "state": payload["state"]}
|
|
20
|
+
|
|
21
|
+
async def exchange_and_identity(self, code: str, state: str) -> Mapping[str, Any]:
|
|
22
|
+
result = await self._exchange_tokens(code, state)
|
|
23
|
+
tokens = result["tokens"]
|
|
24
|
+
claims = result["claims"]
|
|
25
|
+
return {
|
|
26
|
+
"issuer": "gitlab-oauth21",
|
|
27
|
+
"sub": claims["sub"],
|
|
28
|
+
"email": claims.get("email"),
|
|
29
|
+
"name": claims.get("name") or claims.get("preferred_username"),
|
|
30
|
+
"raw": {"tokens": tokens, "claims": claims},
|
|
31
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Shared helpers for GitLab OAuth user login implementations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Callable, Mapping, Optional
|
|
6
|
+
|
|
7
|
+
from pydantic import ConfigDict, Field, SecretBytes, SecretStr
|
|
8
|
+
|
|
9
|
+
from swarmauri_base.auth_idp import (
|
|
10
|
+
RetryingAsyncClient,
|
|
11
|
+
make_pkce_pair,
|
|
12
|
+
sign_state,
|
|
13
|
+
verify_state,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class GitLabOAuthLoginMixin:
|
|
18
|
+
"""Reusable PKCE, token exchange, and profile helpers for GitLab logins."""
|
|
19
|
+
|
|
20
|
+
model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
|
|
21
|
+
|
|
22
|
+
base_url: str
|
|
23
|
+
client_id: str
|
|
24
|
+
client_secret: SecretStr
|
|
25
|
+
redirect_uri: str
|
|
26
|
+
state_secret: SecretBytes
|
|
27
|
+
scope: str = Field(default="read_user")
|
|
28
|
+
api_base: Optional[str] = Field(default=None)
|
|
29
|
+
http_client_factory: Callable[[], RetryingAsyncClient] = Field(
|
|
30
|
+
default=RetryingAsyncClient, exclude=True, repr=False
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def _client_secret_value(self) -> str:
|
|
34
|
+
return self.client_secret.get_secret_value()
|
|
35
|
+
|
|
36
|
+
def _state_secret_value(self) -> bytes:
|
|
37
|
+
return self.state_secret.get_secret_value()
|
|
38
|
+
|
|
39
|
+
def _authorization_endpoint(self) -> str:
|
|
40
|
+
return f"{self.base_url.rstrip('/')}/oauth/authorize"
|
|
41
|
+
|
|
42
|
+
def _token_endpoint(self) -> str:
|
|
43
|
+
return f"{self.base_url.rstrip('/')}/oauth/token"
|
|
44
|
+
|
|
45
|
+
def _api_base_url(self) -> str:
|
|
46
|
+
return self.api_base or f"{self.base_url.rstrip('/')}/api/v4"
|
|
47
|
+
|
|
48
|
+
async def _auth_payload(self) -> Mapping[str, str]:
|
|
49
|
+
verifier, challenge = make_pkce_pair()
|
|
50
|
+
state = sign_state(self._state_secret_value(), {"verifier": verifier})
|
|
51
|
+
url = (
|
|
52
|
+
f"{self._authorization_endpoint()}?response_type=code"
|
|
53
|
+
f"&client_id={self.client_id}&redirect_uri={self.redirect_uri}"
|
|
54
|
+
f"&scope={self.scope}&state={state}"
|
|
55
|
+
f"&code_challenge={challenge}&code_challenge_method=S256"
|
|
56
|
+
)
|
|
57
|
+
return {"url": url, "state": state, "verifier": verifier}
|
|
58
|
+
|
|
59
|
+
async def _exchange_tokens(self, code: str, state: str) -> Mapping[str, Any]:
|
|
60
|
+
payload = verify_state(self._state_secret_value(), state)
|
|
61
|
+
form = {
|
|
62
|
+
"grant_type": "authorization_code",
|
|
63
|
+
"code": code,
|
|
64
|
+
"redirect_uri": self.redirect_uri,
|
|
65
|
+
"client_id": self.client_id,
|
|
66
|
+
"client_secret": self._client_secret_value(),
|
|
67
|
+
"code_verifier": payload["verifier"],
|
|
68
|
+
}
|
|
69
|
+
async with self.http_client_factory() as client:
|
|
70
|
+
response = await client.post_retry(
|
|
71
|
+
self._token_endpoint(),
|
|
72
|
+
data=form,
|
|
73
|
+
headers={"Accept": "application/json"},
|
|
74
|
+
)
|
|
75
|
+
response.raise_for_status()
|
|
76
|
+
return response.json()
|
|
77
|
+
|
|
78
|
+
async def _fetch_profile(self, access_token: str) -> Mapping[str, Any]:
|
|
79
|
+
headers = {
|
|
80
|
+
"Authorization": f"Bearer {access_token}",
|
|
81
|
+
"Accept": "application/json",
|
|
82
|
+
}
|
|
83
|
+
api_base = self._api_base_url()
|
|
84
|
+
async with self.http_client_factory() as client:
|
|
85
|
+
response = await client.get_retry(f"{api_base}/user", headers=headers)
|
|
86
|
+
response.raise_for_status()
|
|
87
|
+
profile = response.json()
|
|
88
|
+
email = profile.get("public_email") or profile.get("email")
|
|
89
|
+
if email and not profile.get("email"):
|
|
90
|
+
profile["email"] = email
|
|
91
|
+
return profile
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
__all__ = ["GitLabOAuthLoginMixin"]
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""GitLab OIDC 1.0 client credentials app client implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Callable, Mapping, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
from pydantic import ConfigDict, Field, SecretStr
|
|
9
|
+
|
|
10
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
11
|
+
from swarmauri_base.auth_idp import OIDC10AppClientBase
|
|
12
|
+
from swarmauri_base.auth_idp.http import RetryingAsyncClient
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@ComponentBase.register_type(OIDC10AppClientBase, "GitLabOIDC10AppClient")
|
|
16
|
+
class GitLabOIDC10AppClient(OIDC10AppClientBase):
|
|
17
|
+
"""Request client credentials tokens using GitLab's OIDC discovery metadata."""
|
|
18
|
+
|
|
19
|
+
model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
|
|
20
|
+
|
|
21
|
+
issuer: str
|
|
22
|
+
client_id: str
|
|
23
|
+
client_secret: SecretStr
|
|
24
|
+
cache_skew_seconds: int = Field(default=30, ge=0)
|
|
25
|
+
http_client_factory: Callable[[], RetryingAsyncClient] = Field(
|
|
26
|
+
default=RetryingAsyncClient, exclude=True, repr=False
|
|
27
|
+
)
|
|
28
|
+
cached_token: Optional[Tuple[str, float]] = Field(
|
|
29
|
+
default=None, exclude=True, repr=False
|
|
30
|
+
)
|
|
31
|
+
discovery_cache: Optional[Mapping[str, Any]] = Field(
|
|
32
|
+
default=None, exclude=True, repr=False
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
def _client_secret_value(self) -> str:
|
|
36
|
+
return self.client_secret.get_secret_value()
|
|
37
|
+
|
|
38
|
+
async def _metadata(self) -> Mapping[str, Any]:
|
|
39
|
+
if self.discovery_cache is None:
|
|
40
|
+
url = f"{self.issuer.rstrip('/')}/.well-known/openid-configuration"
|
|
41
|
+
async with self.http_client_factory() as client:
|
|
42
|
+
response = await client.get_retry(
|
|
43
|
+
url, headers={"Accept": "application/json"}
|
|
44
|
+
)
|
|
45
|
+
response.raise_for_status()
|
|
46
|
+
self.discovery_cache = response.json()
|
|
47
|
+
return self.discovery_cache
|
|
48
|
+
|
|
49
|
+
async def _fetch_token(self, scope: Optional[str]) -> Tuple[str, float]:
|
|
50
|
+
metadata = await self._metadata()
|
|
51
|
+
form = {"grant_type": "client_credentials"}
|
|
52
|
+
if scope:
|
|
53
|
+
form["scope"] = scope
|
|
54
|
+
auth = (self.client_id, self._client_secret_value())
|
|
55
|
+
async with self.http_client_factory() as client:
|
|
56
|
+
response = await client.post_retry(
|
|
57
|
+
metadata["token_endpoint"],
|
|
58
|
+
data=form,
|
|
59
|
+
auth=auth,
|
|
60
|
+
headers={"Accept": "application/json"},
|
|
61
|
+
)
|
|
62
|
+
response.raise_for_status()
|
|
63
|
+
payload = response.json()
|
|
64
|
+
expires_at = time.time() + int(payload.get("expires_in", 3600))
|
|
65
|
+
return payload["access_token"], expires_at
|
|
66
|
+
|
|
67
|
+
async def access_token(self, scope: Optional[str] = None) -> str:
|
|
68
|
+
cached = self.cached_token
|
|
69
|
+
now = time.time()
|
|
70
|
+
if cached and now < cached[1] - self.cache_skew_seconds:
|
|
71
|
+
return cached[0]
|
|
72
|
+
token, expires_at = await self._fetch_token(scope)
|
|
73
|
+
self.cached_token = (token, expires_at)
|
|
74
|
+
return token
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""GitLab OpenID Connect 1.0 Authorization Code login implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Mapping
|
|
6
|
+
|
|
7
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
8
|
+
from swarmauri_base.auth_idp import OIDC10LoginBase
|
|
9
|
+
|
|
10
|
+
from .GitLabOIDCLoginMixin import GitLabOIDCLoginMixin
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@ComponentBase.register_type(OIDC10LoginBase, "GitLabOIDC10Login")
|
|
14
|
+
class GitLabOIDC10Login(GitLabOIDCLoginMixin, OIDC10LoginBase):
|
|
15
|
+
"""Implement OIDC 1.0 Authorization Code with PKCE for GitLab."""
|
|
16
|
+
|
|
17
|
+
async def auth_url(self) -> Mapping[str, str]:
|
|
18
|
+
payload = await self._auth_payload()
|
|
19
|
+
return {"url": payload["url"], "state": payload["state"]}
|
|
20
|
+
|
|
21
|
+
async def exchange(self, code: str, state: str) -> Mapping[str, Any]:
|
|
22
|
+
result = await self._exchange_tokens(code, state)
|
|
23
|
+
tokens = result["tokens"]
|
|
24
|
+
claims = result["claims"]
|
|
25
|
+
return {
|
|
26
|
+
"issuer": "gitlab-oidc",
|
|
27
|
+
"sub": claims["sub"],
|
|
28
|
+
"email": claims.get("email"),
|
|
29
|
+
"name": claims.get("name") or claims.get("preferred_username"),
|
|
30
|
+
"raw": {"tokens": tokens, "claims": claims},
|
|
31
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Shared helpers for GitLab OIDC-based login implementations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Callable, Mapping, Optional
|
|
6
|
+
|
|
7
|
+
import jwt
|
|
8
|
+
from pydantic import ConfigDict, Field, SecretBytes, SecretStr
|
|
9
|
+
|
|
10
|
+
from swarmauri_base.auth_idp import (
|
|
11
|
+
RetryingAsyncClient,
|
|
12
|
+
make_pkce_pair,
|
|
13
|
+
sign_state,
|
|
14
|
+
verify_state,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GitLabOIDCLoginMixin:
|
|
19
|
+
"""Reusable discovery, PKCE, and ID token helpers for GitLab OIDC logins."""
|
|
20
|
+
|
|
21
|
+
model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
|
|
22
|
+
|
|
23
|
+
issuer: str
|
|
24
|
+
client_id: str
|
|
25
|
+
client_secret: SecretStr
|
|
26
|
+
redirect_uri: str
|
|
27
|
+
state_secret: SecretBytes
|
|
28
|
+
scope: str = Field(default="openid email profile")
|
|
29
|
+
http_client_factory: Callable[[], RetryingAsyncClient] = Field(
|
|
30
|
+
default=RetryingAsyncClient, exclude=True, repr=False
|
|
31
|
+
)
|
|
32
|
+
discovery_cache: Optional[Mapping[str, Any]] = Field(
|
|
33
|
+
default=None, exclude=True, repr=False
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def _client_secret_value(self) -> str:
|
|
37
|
+
return self.client_secret.get_secret_value()
|
|
38
|
+
|
|
39
|
+
def _state_secret_value(self) -> bytes:
|
|
40
|
+
return self.state_secret.get_secret_value()
|
|
41
|
+
|
|
42
|
+
async def _metadata(self) -> Mapping[str, Any]:
|
|
43
|
+
if self.discovery_cache is None:
|
|
44
|
+
url = f"{self.issuer.rstrip('/')}/.well-known/openid-configuration"
|
|
45
|
+
async with self.http_client_factory() as client:
|
|
46
|
+
response = await client.get_retry(
|
|
47
|
+
url, headers={"Accept": "application/json"}
|
|
48
|
+
)
|
|
49
|
+
response.raise_for_status()
|
|
50
|
+
self.discovery_cache = response.json()
|
|
51
|
+
return self.discovery_cache
|
|
52
|
+
|
|
53
|
+
async def _auth_payload(self) -> Mapping[str, str]:
|
|
54
|
+
metadata = await self._metadata()
|
|
55
|
+
verifier, challenge = make_pkce_pair()
|
|
56
|
+
state = sign_state(self._state_secret_value(), {"verifier": verifier})
|
|
57
|
+
endpoint = metadata["authorization_endpoint"]
|
|
58
|
+
url = (
|
|
59
|
+
f"{endpoint}?response_type=code"
|
|
60
|
+
f"&client_id={self.client_id}&redirect_uri={self.redirect_uri}"
|
|
61
|
+
f"&scope={self.scope}&state={state}"
|
|
62
|
+
f"&code_challenge={challenge}&code_challenge_method=S256"
|
|
63
|
+
)
|
|
64
|
+
return {"url": url, "state": state, "verifier": verifier}
|
|
65
|
+
|
|
66
|
+
async def _exchange_tokens(self, code: str, state: str) -> Mapping[str, Any]:
|
|
67
|
+
payload = verify_state(self._state_secret_value(), state)
|
|
68
|
+
metadata = await self._metadata()
|
|
69
|
+
form = {
|
|
70
|
+
"grant_type": "authorization_code",
|
|
71
|
+
"code": code,
|
|
72
|
+
"redirect_uri": self.redirect_uri,
|
|
73
|
+
"client_id": self.client_id,
|
|
74
|
+
"client_secret": self._client_secret_value(),
|
|
75
|
+
"code_verifier": payload["verifier"],
|
|
76
|
+
}
|
|
77
|
+
async with self.http_client_factory() as client:
|
|
78
|
+
response = await client.post_retry(
|
|
79
|
+
metadata["token_endpoint"],
|
|
80
|
+
data=form,
|
|
81
|
+
headers={"Accept": "application/json"},
|
|
82
|
+
)
|
|
83
|
+
response.raise_for_status()
|
|
84
|
+
tokens = response.json()
|
|
85
|
+
jwks_response = await client.get_retry(
|
|
86
|
+
metadata["jwks_uri"], headers={"Accept": "application/json"}
|
|
87
|
+
)
|
|
88
|
+
jwks_response.raise_for_status()
|
|
89
|
+
jwks = jwks_response.json()
|
|
90
|
+
claims = await self._decode_id_token(tokens, jwks, metadata)
|
|
91
|
+
if metadata.get("userinfo_endpoint"):
|
|
92
|
+
email = claims.get("email")
|
|
93
|
+
name = claims.get("name") or claims.get("preferred_username")
|
|
94
|
+
if not email or not name:
|
|
95
|
+
async with self.http_client_factory() as client:
|
|
96
|
+
userinfo_response = await client.get_retry(
|
|
97
|
+
metadata["userinfo_endpoint"],
|
|
98
|
+
headers={
|
|
99
|
+
"Authorization": f"Bearer {tokens['access_token']}",
|
|
100
|
+
"Accept": "application/json",
|
|
101
|
+
},
|
|
102
|
+
)
|
|
103
|
+
userinfo_response.raise_for_status()
|
|
104
|
+
userinfo = userinfo_response.json()
|
|
105
|
+
claims = {**userinfo, **claims}
|
|
106
|
+
return {"tokens": tokens, "claims": claims}
|
|
107
|
+
|
|
108
|
+
async def _decode_id_token(
|
|
109
|
+
self,
|
|
110
|
+
tokens: Mapping[str, Any],
|
|
111
|
+
jwks: Mapping[str, Any],
|
|
112
|
+
metadata: Mapping[str, Any],
|
|
113
|
+
) -> Mapping[str, Any]:
|
|
114
|
+
id_token = tokens.get("id_token")
|
|
115
|
+
if not id_token:
|
|
116
|
+
raise ValueError("no id_token in response")
|
|
117
|
+
header = jwt.get_unverified_header(id_token)
|
|
118
|
+
kid = header.get("kid")
|
|
119
|
+
if not kid:
|
|
120
|
+
raise ValueError("missing kid in id_token header")
|
|
121
|
+
key_entry = next(
|
|
122
|
+
(entry for entry in jwks.get("keys", []) if entry.get("kid") == kid),
|
|
123
|
+
None,
|
|
124
|
+
)
|
|
125
|
+
if not key_entry:
|
|
126
|
+
raise ValueError("signing key not found")
|
|
127
|
+
algorithm = header.get("alg", "RS256")
|
|
128
|
+
signer = (
|
|
129
|
+
jwt.algorithms.ECAlgorithm.from_jwk(key_entry)
|
|
130
|
+
if algorithm.upper().startswith("ES")
|
|
131
|
+
else jwt.algorithms.RSAAlgorithm.from_jwk(key_entry)
|
|
132
|
+
)
|
|
133
|
+
return jwt.decode(
|
|
134
|
+
id_token,
|
|
135
|
+
signer,
|
|
136
|
+
algorithms=[algorithm],
|
|
137
|
+
audience=self.client_id,
|
|
138
|
+
issuer=metadata.get("issuer", self.issuer),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
__all__ = ["GitLabOIDCLoginMixin"]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""GitLab identity provider implementations for Swarmauri."""
|
|
2
|
+
|
|
3
|
+
from .GitLabOAuth20AppClient import GitLabOAuth20AppClient
|
|
4
|
+
from .GitLabOAuth20Login import GitLabOAuth20Login
|
|
5
|
+
from .GitLabOAuth21AppClient import GitLabOAuth21AppClient
|
|
6
|
+
from .GitLabOAuth21Login import GitLabOAuth21Login
|
|
7
|
+
from .GitLabOIDC10AppClient import GitLabOIDC10AppClient
|
|
8
|
+
from .GitLabOIDC10Login import GitLabOIDC10Login
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"GitLabOAuth20AppClient",
|
|
12
|
+
"GitLabOAuth20Login",
|
|
13
|
+
"GitLabOAuth21AppClient",
|
|
14
|
+
"GitLabOAuth21Login",
|
|
15
|
+
"GitLabOIDC10AppClient",
|
|
16
|
+
"GitLabOIDC10Login",
|
|
17
|
+
]
|