swarmauri_auth_idp_salesforce 0.11.0.dev2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [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,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_auth_idp_salesforce
3
+ Version: 0.11.0.dev2
4
+ Summary: Salesforce 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,salesforce,idp
8
+ Author: Jacob Stewart
9
+ Author-email: jacob@swarmauri.com
10
+ Requires-Python: >=3.10,<3.15
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: Topic :: Internet :: WWW/HTTP
16
+ Classifier: Topic :: Security :: Cryptography
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Requires-Dist: httpx (>=0.27)
26
+ Requires-Dist: pyjwt[crypto] (>=2.8)
27
+ Requires-Dist: swarmauri_base
28
+ Requires-Dist: swarmauri_core
29
+ Description-Content-Type: text/markdown
30
+
31
+ ![Swarmauri Logo](https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/swarmauri_sdk_brand.png)
32
+
33
+ <p align="center">
34
+ <a href="https://pepy.tech/project/swarmauri_auth_idp_salesforce/">
35
+ <img src="https://static.pepy.tech/badge/swarmauri_auth_idp_salesforce/month" alt="PyPI - Downloads"/></a>
36
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_auth_idp_salesforce/">
37
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_auth_idp_salesforce.svg"/></a>
38
+ <a href="https://pypi.org/project/swarmauri_auth_idp_salesforce/">
39
+ <img src="https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14-blue" alt="PyPI - Python Version"/></a>
40
+ <a href="https://pypi.org/project/swarmauri_auth_idp_salesforce/">
41
+ <img src="https://img.shields.io/pypi/l/swarmauri_auth_idp_salesforce" alt="PyPI - License"/></a>
42
+ <a href="https://pypi.org/project/swarmauri_auth_idp_salesforce/">
43
+ <img src="https://img.shields.io/pypi/v/swarmauri_auth_idp_salesforce?label=swarmauri_auth_idp_salesforce&color=green" alt="PyPI - swarmauri_auth_idp_salesforce"/></a>
44
+ <a href="https://discord.gg/N4UpBuQv8T">
45
+ <img src="https://img.shields.io/badge/Discord-Join%20Chat-5865F2?logo=discord&logoColor=white" alt="Discord"/></a></p>
46
+
47
+ # Swarmauri Auth IDP Salesforce
48
+
49
+ Salesforce OAuth 2.0 / OAuth 2.1 / OIDC 1.0 identity providers packaged for Swarmauri deployments.
50
+
51
+ ## Features
52
+
53
+ - PKCE-enabled Authorization Code flows that integrate with Salesforce authorization servers.
54
+ - JWT bearer app clients for Salesforce OAuth 2.0, OAuth 2.1, and OIDC 1.0 machine identities.
55
+ - Discovery-driven OAuth 2.1/OIDC login that verifies ID tokens against Salesforce JWKS.
56
+ - UserInfo and Identity URL fallbacks for normalized profile payloads.
57
+ - Retry-aware HTTP integration tuned for Salesforce REST endpoints.
58
+ - ComponentBase-compatible models registered under `swarmauri.auth_idp` entry points.
59
+
60
+ ## Installation
61
+
62
+ ### pip
63
+
64
+ ```bash
65
+ pip install swarmauri_auth_idp_salesforce
66
+ ```
67
+
68
+ ### uv (project)
69
+
70
+ ```bash
71
+ uv add swarmauri_auth_idp_salesforce
72
+ ```
73
+
74
+ ### uv (environment)
75
+
76
+ ```bash
77
+ uv pip install swarmauri_auth_idp_salesforce
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ ### Authorization Code logins
83
+
84
+ ```python
85
+ import asyncio
86
+ from pydantic import SecretBytes, SecretStr
87
+ from swarmauri_auth_idp_salesforce import SalesforceOAuth20Login
88
+
89
+ login = SalesforceOAuth20Login(
90
+ base_url="https://login.salesforce.com",
91
+ client_id="salesforce-client-id",
92
+ client_secret=SecretStr("salesforce-client-secret"),
93
+ redirect_uri="https://app.example.com/callback",
94
+ state_secret=SecretBytes(b"replace-with-random-bytes"),
95
+ )
96
+
97
+ # Optional discovery cache when running without network access.
98
+ login.discovery_cache = {
99
+ "authorization_endpoint": "https://login.salesforce.com/services/oauth2/authorize",
100
+ "token_endpoint": "https://login.salesforce.com/services/oauth2/token",
101
+ "userinfo_endpoint": "https://login.salesforce.com/services/oauth2/userinfo",
102
+ }
103
+
104
+ async def run_flow() -> None:
105
+ auth = await login.auth_url()
106
+ print(auth["url"])
107
+ # Redirect the browser to `auth["url"]`, then capture the callback `code` and `state`.
108
+ # Later, call `login.exchange_and_identity(code, state)` inside your callback handler.
109
+
110
+ asyncio.run(run_flow())
111
+ ```
112
+
113
+ ### Workflow Summary
114
+
115
+ 1. Call `auth_url()` and redirect the browser to the returned URL.
116
+ 2. Persist the `state` and verify it during the callback handler.
117
+ 3. Exchange the authorization code through `exchange_and_identity()` to obtain tokens and profile metadata.
118
+
119
+ ### Server-to-server JWT bearer tokens
120
+
121
+ ```python
122
+ import asyncio
123
+ from pydantic import SecretStr
124
+ from swarmauri_auth_idp_salesforce import SalesforceOAuth20AppClient
125
+
126
+ client = SalesforceOAuth20AppClient(
127
+ token_endpoint="https://login.salesforce.com/services/oauth2/token",
128
+ client_id="connected-app-id",
129
+ user="integration.user@example.com",
130
+ private_key_pem=SecretStr("-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"),
131
+ )
132
+
133
+ async def fetch_token() -> None:
134
+ access_token = await client.access_token()
135
+ print(access_token)
136
+
137
+ asyncio.run(fetch_token())
138
+ ```
139
+
140
+ Use `SalesforceOAuth21AppClient` when your integration manages keys as JWKs, or
141
+ `SalesforceOIDC10AppClient` to discover tenant-specific endpoints before
142
+ requesting JWT bearer tokens.
143
+
144
+ ## Entry Points
145
+
146
+ - `swarmauri.auth_idp:SalesforceOAuth20AppClient`
147
+ - `swarmauri.auth_idp:SalesforceOAuth20Login`
148
+ - `swarmauri.auth_idp:SalesforceOAuth21AppClient`
149
+ - `swarmauri.auth_idp:SalesforceOAuth21Login`
150
+ - `swarmauri.auth_idp:SalesforceOIDC10AppClient`
151
+ - `swarmauri.auth_idp:SalesforceOIDC10Login`
152
+
153
+ ## Contributing
154
+
155
+ To contribute to swarmauri-sdk, review the
156
+ [guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/CONTRIBUTING.md)
157
+ which cover development workflow, testing, and coding standards.
158
+
159
+
160
+
@@ -0,0 +1,129 @@
1
+ ![Swarmauri Logo](https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/swarmauri_sdk_brand.png)
2
+
3
+ <p align="center">
4
+ <a href="https://pepy.tech/project/swarmauri_auth_idp_salesforce/">
5
+ <img src="https://static.pepy.tech/badge/swarmauri_auth_idp_salesforce/month" alt="PyPI - Downloads"/></a>
6
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_auth_idp_salesforce/">
7
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_auth_idp_salesforce.svg"/></a>
8
+ <a href="https://pypi.org/project/swarmauri_auth_idp_salesforce/">
9
+ <img src="https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14-blue" alt="PyPI - Python Version"/></a>
10
+ <a href="https://pypi.org/project/swarmauri_auth_idp_salesforce/">
11
+ <img src="https://img.shields.io/pypi/l/swarmauri_auth_idp_salesforce" alt="PyPI - License"/></a>
12
+ <a href="https://pypi.org/project/swarmauri_auth_idp_salesforce/">
13
+ <img src="https://img.shields.io/pypi/v/swarmauri_auth_idp_salesforce?label=swarmauri_auth_idp_salesforce&color=green" alt="PyPI - swarmauri_auth_idp_salesforce"/></a>
14
+ <a href="https://discord.gg/N4UpBuQv8T">
15
+ <img src="https://img.shields.io/badge/Discord-Join%20Chat-5865F2?logo=discord&logoColor=white" alt="Discord"/></a></p>
16
+
17
+ # Swarmauri Auth IDP Salesforce
18
+
19
+ Salesforce OAuth 2.0 / OAuth 2.1 / OIDC 1.0 identity providers packaged for Swarmauri deployments.
20
+
21
+ ## Features
22
+
23
+ - PKCE-enabled Authorization Code flows that integrate with Salesforce authorization servers.
24
+ - JWT bearer app clients for Salesforce OAuth 2.0, OAuth 2.1, and OIDC 1.0 machine identities.
25
+ - Discovery-driven OAuth 2.1/OIDC login that verifies ID tokens against Salesforce JWKS.
26
+ - UserInfo and Identity URL fallbacks for normalized profile payloads.
27
+ - Retry-aware HTTP integration tuned for Salesforce REST 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_salesforce
36
+ ```
37
+
38
+ ### uv (project)
39
+
40
+ ```bash
41
+ uv add swarmauri_auth_idp_salesforce
42
+ ```
43
+
44
+ ### uv (environment)
45
+
46
+ ```bash
47
+ uv pip install swarmauri_auth_idp_salesforce
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ ### Authorization Code logins
53
+
54
+ ```python
55
+ import asyncio
56
+ from pydantic import SecretBytes, SecretStr
57
+ from swarmauri_auth_idp_salesforce import SalesforceOAuth20Login
58
+
59
+ login = SalesforceOAuth20Login(
60
+ base_url="https://login.salesforce.com",
61
+ client_id="salesforce-client-id",
62
+ client_secret=SecretStr("salesforce-client-secret"),
63
+ redirect_uri="https://app.example.com/callback",
64
+ state_secret=SecretBytes(b"replace-with-random-bytes"),
65
+ )
66
+
67
+ # Optional discovery cache when running without network access.
68
+ login.discovery_cache = {
69
+ "authorization_endpoint": "https://login.salesforce.com/services/oauth2/authorize",
70
+ "token_endpoint": "https://login.salesforce.com/services/oauth2/token",
71
+ "userinfo_endpoint": "https://login.salesforce.com/services/oauth2/userinfo",
72
+ }
73
+
74
+ async def run_flow() -> None:
75
+ auth = await login.auth_url()
76
+ print(auth["url"])
77
+ # Redirect the browser to `auth["url"]`, then capture the callback `code` and `state`.
78
+ # Later, call `login.exchange_and_identity(code, state)` inside your callback handler.
79
+
80
+ asyncio.run(run_flow())
81
+ ```
82
+
83
+ ### Workflow Summary
84
+
85
+ 1. Call `auth_url()` and redirect the browser to the returned URL.
86
+ 2. Persist the `state` and verify it during the callback handler.
87
+ 3. Exchange the authorization code through `exchange_and_identity()` to obtain tokens and profile metadata.
88
+
89
+ ### Server-to-server JWT bearer tokens
90
+
91
+ ```python
92
+ import asyncio
93
+ from pydantic import SecretStr
94
+ from swarmauri_auth_idp_salesforce import SalesforceOAuth20AppClient
95
+
96
+ client = SalesforceOAuth20AppClient(
97
+ token_endpoint="https://login.salesforce.com/services/oauth2/token",
98
+ client_id="connected-app-id",
99
+ user="integration.user@example.com",
100
+ private_key_pem=SecretStr("-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"),
101
+ )
102
+
103
+ async def fetch_token() -> None:
104
+ access_token = await client.access_token()
105
+ print(access_token)
106
+
107
+ asyncio.run(fetch_token())
108
+ ```
109
+
110
+ Use `SalesforceOAuth21AppClient` when your integration manages keys as JWKs, or
111
+ `SalesforceOIDC10AppClient` to discover tenant-specific endpoints before
112
+ requesting JWT bearer tokens.
113
+
114
+ ## Entry Points
115
+
116
+ - `swarmauri.auth_idp:SalesforceOAuth20AppClient`
117
+ - `swarmauri.auth_idp:SalesforceOAuth20Login`
118
+ - `swarmauri.auth_idp:SalesforceOAuth21AppClient`
119
+ - `swarmauri.auth_idp:SalesforceOAuth21Login`
120
+ - `swarmauri.auth_idp:SalesforceOIDC10AppClient`
121
+ - `swarmauri.auth_idp:SalesforceOIDC10Login`
122
+
123
+ ## Contributing
124
+
125
+ To contribute to swarmauri-sdk, review the
126
+ [guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/CONTRIBUTING.md)
127
+ which cover development workflow, testing, and coding standards.
128
+
129
+
@@ -0,0 +1,89 @@
1
+ [project]
2
+ name = "swarmauri_auth_idp_salesforce"
3
+ version = "0.11.0.dev2"
4
+ description = "Salesforce 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.15"
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
+ "Topic :: Internet :: WWW/HTTP",
16
+ "Topic :: Security :: Cryptography",
17
+ "Programming Language :: Python",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Programming Language :: Python :: 3.14",
25
+ ]
26
+ keywords = [
27
+ "swarmauri",
28
+ "sdk",
29
+ "experimental",
30
+ "identity",
31
+ "oauth2",
32
+ "oauth21",
33
+ "oidc",
34
+ "salesforce",
35
+ "idp",
36
+ ]
37
+ dependencies = [
38
+ "swarmauri_core",
39
+ "swarmauri_base",
40
+ "httpx>=0.27",
41
+ "pyjwt[crypto]>=2.8",
42
+ ]
43
+
44
+ [project.entry-points.'swarmauri.auth_idp']
45
+ SalesforceOAuth20AppClient = "swarmauri_auth_idp_salesforce:SalesforceOAuth20AppClient"
46
+ SalesforceOAuth20Login = "swarmauri_auth_idp_salesforce:SalesforceOAuth20Login"
47
+ SalesforceOAuth21AppClient = "swarmauri_auth_idp_salesforce:SalesforceOAuth21AppClient"
48
+ SalesforceOAuth21Login = "swarmauri_auth_idp_salesforce:SalesforceOAuth21Login"
49
+ SalesforceOIDC10AppClient = "swarmauri_auth_idp_salesforce:SalesforceOIDC10AppClient"
50
+ SalesforceOIDC10Login = "swarmauri_auth_idp_salesforce:SalesforceOIDC10Login"
51
+
52
+ [tool.uv.sources]
53
+ swarmauri_tests_pylicense = { workspace = true }
54
+ swarmauri_core = { workspace = true }
55
+ swarmauri_base = { workspace = true }
56
+
57
+ [tool.pytest.ini_options]
58
+ markers = [
59
+ "test: standard test",
60
+ "unit: Unit tests",
61
+ "i9n: Integration tests",
62
+ "r8n: Regression tests",
63
+ "acceptance: Acceptance tests",
64
+ "perf: Performance tests",
65
+ "example: Documentation examples",
66
+ ]
67
+ timeout = 300
68
+ log_cli = true
69
+ log_cli_level = "INFO"
70
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
71
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
72
+ asyncio_default_fixture_loop_scope = "function"
73
+ addopts = "--pylicense-accept-deps=sniffio"
74
+
75
+ [dependency-groups]
76
+ dev = [
77
+ "pytest>=8.0",
78
+ "pytest-asyncio>=0.24.0",
79
+ "pytest-xdist>=3.6.1",
80
+ "pytest-json-report>=1.5.0",
81
+ "pytest-timeout>=2.3.1",
82
+ "pytest-benchmark>=4.0.0",
83
+ "ruff>=0.9.9",
84
+ "swarmauri_tests_pylicense",
85
+ ]
86
+
87
+ [build-system]
88
+ requires = ["poetry-core>=1.0.0"]
89
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,149 @@
1
+ """Salesforce OAuth 2.0 JWT bearer app client implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import (
7
+ Any,
8
+ Callable,
9
+ ClassVar,
10
+ Dict,
11
+ Literal,
12
+ Mapping,
13
+ Optional,
14
+ Tuple,
15
+ )
16
+
17
+ import jwt
18
+ from pydantic import ConfigDict, Field, PrivateAttr, SecretBytes, SecretStr
19
+
20
+ from swarmauri_base.ComponentBase import ComponentBase
21
+ from swarmauri_base.auth_idp import OAuth20AppClientBase, RetryingAsyncClient
22
+
23
+
24
+ PrivateKeySecret = SecretStr | SecretBytes
25
+
26
+
27
+ @ComponentBase.register_type(
28
+ OAuth20AppClientBase, "SalesforceOAuth20AppClient"
29
+ )
30
+ class SalesforceOAuth20AppClient(OAuth20AppClientBase):
31
+ """Request machine-to-machine access tokens using Salesforce's JWT bearer
32
+ flow."""
33
+
34
+ model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
35
+
36
+ JWT_GRANT: ClassVar[str] = "urn:ietf:params:oauth:grant-type:jwt-bearer"
37
+
38
+ token_endpoint: str
39
+ client_id: str
40
+ user: str
41
+ private_key_pem: Optional[PrivateKeySecret] = Field(
42
+ default=None, repr=False
43
+ )
44
+ private_key_jwk: Optional[Mapping[str, Any]] = Field(
45
+ default=None, repr=False
46
+ )
47
+ aud: Optional[str] = None
48
+ scope: Optional[str] = None
49
+ jwt_lifetime_seconds: int = Field(default=180, ge=1)
50
+ cache_ttl_seconds: Optional[int] = Field(default=None, ge=1)
51
+ cache_skew_seconds: int = Field(default=30, ge=0)
52
+ http_client_factory: Callable[[], RetryingAsyncClient] = Field(
53
+ default=RetryingAsyncClient, exclude=True, repr=False
54
+ )
55
+
56
+ type: Literal["SalesforceOAuth20AppClient"] = "SalesforceOAuth20AppClient"
57
+
58
+ _token_cache: Optional[Tuple[Dict[str, Any], float]] = PrivateAttr(
59
+ default=None
60
+ )
61
+
62
+ def model_post_init(self, __context: Any) -> None:
63
+ if not self.private_key_jwk and not self.private_key_pem:
64
+ raise ValueError(
65
+ (
66
+ "private key (PEM or JWK) required for Salesforce JWT "
67
+ "bearer "
68
+ "flow"
69
+ )
70
+ )
71
+
72
+ def _audience_value(self) -> str:
73
+ if self.aud:
74
+ return self.aud.rstrip("/")
75
+ base, _, _ = self.token_endpoint.partition("/services/")
76
+ candidate = base or self.token_endpoint
77
+ return candidate.split("?")[0].rstrip("/")
78
+
79
+ def _private_key_value(self) -> Mapping[str, Any] | str | bytes:
80
+ if self.private_key_jwk:
81
+ return dict(self.private_key_jwk)
82
+ if isinstance(self.private_key_pem, SecretStr):
83
+ return self.private_key_pem.get_secret_value()
84
+ if isinstance(self.private_key_pem, SecretBytes):
85
+ return self.private_key_pem.get_secret_value()
86
+ raise ValueError(
87
+ "private key (PEM or JWK) required for Salesforce JWT bearer flow"
88
+ )
89
+
90
+ def _effective_scope(self, scope: Optional[str]) -> Optional[str]:
91
+ return scope if scope is not None else self.scope
92
+
93
+ def _jwt_assertion(self) -> str:
94
+ now = int(time.time())
95
+ payload = {
96
+ "iss": self.client_id,
97
+ "sub": self.user,
98
+ "aud": self._audience_value(),
99
+ "iat": now,
100
+ "exp": now + self.jwt_lifetime_seconds,
101
+ }
102
+ key = self._private_key_value()
103
+ return jwt.encode(payload, key=key, algorithm="RS256")
104
+
105
+ async def _request_token(self, scope: Optional[str]) -> Dict[str, Any]:
106
+ form = {
107
+ "grant_type": self.JWT_GRANT,
108
+ "assertion": self._jwt_assertion(),
109
+ }
110
+ effective_scope = self._effective_scope(scope)
111
+ if effective_scope:
112
+ form["scope"] = effective_scope
113
+ async with self.http_client_factory() as client:
114
+ response = await client.post_retry(
115
+ self.token_endpoint,
116
+ data=form,
117
+ headers={"Accept": "application/json"},
118
+ )
119
+ response.raise_for_status()
120
+ return response.json()
121
+
122
+ async def access_token_payload(
123
+ self, scope: Optional[str] = None
124
+ ) -> Dict[str, Any]:
125
+ now = time.time()
126
+ if self.cache_ttl_seconds and self._token_cache:
127
+ cached_payload, expires_at = self._token_cache
128
+ if now < expires_at - self.cache_skew_seconds:
129
+ return dict(cached_payload)
130
+
131
+ payload = dict(await self._request_token(scope))
132
+ if "access_token" not in payload:
133
+ raise ValueError("access_token missing from Salesforce response")
134
+
135
+ if self.cache_ttl_seconds:
136
+ expiry = now + self.cache_ttl_seconds
137
+ self._token_cache = (dict(payload), expiry)
138
+
139
+ return payload
140
+
141
+ async def access_token(self, scope: Optional[str] = None) -> str:
142
+ payload = await self.access_token_payload(scope=scope)
143
+ token = payload.get("access_token")
144
+ if not isinstance(token, str):
145
+ raise ValueError("access_token missing from Salesforce response")
146
+ return token
147
+
148
+
149
+ __all__ = ["SalesforceOAuth20AppClient"]
@@ -0,0 +1,60 @@
1
+ """Salesforce 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 .SalesforceOAuthLoginMixin import SalesforceOAuthLoginMixin
11
+
12
+
13
+ @ComponentBase.register_type(OAuth20LoginBase, "SalesforceOAuth20Login")
14
+ class SalesforceOAuth20Login(SalesforceOAuthLoginMixin, OAuth20LoginBase):
15
+ """Implement the Salesforce OAuth 2.0 Authorization Code flow with PKCE."""
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(
22
+ self, code: str, state: str
23
+ ) -> Mapping[str, Any]:
24
+ tokens = await self._exchange_tokens(code, state)
25
+ profile = {}
26
+ try:
27
+ profile = await self._fetch_userinfo(tokens["access_token"])
28
+ except Exception: # pragma: no cover - fallback to identity endpoint
29
+ profile = {}
30
+ if not profile:
31
+ identity = await self._fetch_identity_profile(
32
+ tokens.get("id"), tokens["access_token"]
33
+ )
34
+ else:
35
+ identity = profile
36
+ subject = (
37
+ profile.get("sub")
38
+ or profile.get("user_id")
39
+ or identity.get("user_id")
40
+ or identity.get("id")
41
+ )
42
+ email = profile.get("email") or identity.get("email")
43
+ name = (
44
+ profile.get("name")
45
+ or identity.get("display_name")
46
+ or identity.get("preferred_username")
47
+ or identity.get("username")
48
+ or "Unknown"
49
+ )
50
+ return {
51
+ "issuer": "salesforce-oauth20",
52
+ "sub": subject,
53
+ "email": email,
54
+ "name": name,
55
+ "raw": {
56
+ "tokens": tokens,
57
+ "userinfo": profile,
58
+ "identity": identity,
59
+ },
60
+ }
@@ -0,0 +1,63 @@
1
+ """Salesforce OAuth 2.1 JWT bearer app client wrapper."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Dict, Literal, Mapping, Optional
6
+
7
+ from pydantic import ConfigDict, Field
8
+
9
+ from swarmauri_base.ComponentBase import ComponentBase
10
+ from swarmauri_base.auth_idp import OAuth21AppClientBase, RetryingAsyncClient
11
+
12
+ from .SalesforceOAuth20AppClient import SalesforceOAuth20AppClient
13
+
14
+
15
+ @ComponentBase.register_type(
16
+ OAuth21AppClientBase, "SalesforceOAuth21AppClient"
17
+ )
18
+ class SalesforceOAuth21AppClient(OAuth21AppClientBase):
19
+ """Reuse the OAuth 2.0 JWT bearer client with OAuth 2.1 semantics."""
20
+
21
+ model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
22
+
23
+ token_endpoint: str
24
+ client_id: str
25
+ user: str
26
+ private_key_jwk: Mapping[str, Any]
27
+ aud: Optional[str] = None
28
+ scope: Optional[str] = None
29
+ jwt_lifetime_seconds: int = Field(default=180, ge=1)
30
+ cache_ttl_seconds: Optional[int] = Field(default=None, ge=1)
31
+ cache_skew_seconds: int = Field(default=30, ge=0)
32
+ http_client_factory: Callable[[], RetryingAsyncClient] = Field(
33
+ default=RetryingAsyncClient, exclude=True, repr=False
34
+ )
35
+
36
+ type: Literal["SalesforceOAuth21AppClient"] = "SalesforceOAuth21AppClient"
37
+
38
+ async def access_token_payload(
39
+ self, scope: Optional[str] = None
40
+ ) -> Dict[str, Any]:
41
+ client = SalesforceOAuth20AppClient(
42
+ token_endpoint=self.token_endpoint,
43
+ client_id=self.client_id,
44
+ user=self.user,
45
+ private_key_jwk=self.private_key_jwk,
46
+ aud=self.aud,
47
+ scope=self.scope,
48
+ jwt_lifetime_seconds=self.jwt_lifetime_seconds,
49
+ cache_ttl_seconds=self.cache_ttl_seconds,
50
+ cache_skew_seconds=self.cache_skew_seconds,
51
+ http_client_factory=self.http_client_factory,
52
+ )
53
+ return await client.access_token_payload(scope=scope)
54
+
55
+ async def access_token(self, scope: Optional[str] = None) -> str:
56
+ payload = await self.access_token_payload(scope=scope)
57
+ token = payload.get("access_token")
58
+ if not isinstance(token, str):
59
+ raise ValueError("access_token missing from Salesforce response")
60
+ return token
61
+
62
+
63
+ __all__ = ["SalesforceOAuth21AppClient"]
@@ -0,0 +1,57 @@
1
+ """Salesforce 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 .SalesforceOIDCLoginMixin import SalesforceOIDCLoginMixin
11
+
12
+
13
+ @ComponentBase.register_type(OAuth21LoginBase, "SalesforceOAuth21Login")
14
+ class SalesforceOAuth21Login(SalesforceOIDCLoginMixin, OAuth21LoginBase):
15
+ """Implement the Salesforce OAuth 2.1 Authorization Code flow with PKCE."""
16
+
17
+ async def auth_url(self) -> Mapping[str, str]:
18
+ metadata = await self._metadata()
19
+ # Update endpoints based on discovery for auth_url usage
20
+ self.discovery_cache = metadata
21
+ payload = await self._auth_payload()
22
+ return {"url": payload["url"], "state": payload["state"]}
23
+
24
+ async def exchange_and_identity(
25
+ self, code: str, state: str
26
+ ) -> Mapping[str, Any]:
27
+ metadata = await self._metadata()
28
+ self.discovery_cache = metadata
29
+ tokens = await self._exchange_tokens(code, state)
30
+ claims = {}
31
+ try:
32
+ claims = await self._decode_id_token(tokens, metadata)
33
+ except Exception:
34
+ claims = {}
35
+ email = claims.get("email")
36
+ name = (
37
+ claims.get("name") or claims.get("preferred_username") or "Unknown"
38
+ )
39
+ subject = claims.get("sub")
40
+ if (not email or not subject) and metadata.get("userinfo_endpoint"):
41
+ profile = await self._fetch_userinfo(tokens["access_token"])
42
+ email = email or profile.get("email")
43
+ name = (
44
+ name
45
+ if name != "Unknown"
46
+ else profile.get("name")
47
+ or profile.get("preferred_username")
48
+ or "Unknown"
49
+ )
50
+ subject = subject or profile.get("sub") or profile.get("user_id")
51
+ return {
52
+ "issuer": "salesforce-oauth21",
53
+ "sub": subject,
54
+ "email": email,
55
+ "name": name,
56
+ "raw": {"tokens": tokens, "claims": claims},
57
+ }
@@ -0,0 +1,117 @@
1
+ """Shared helpers for Salesforce 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 SalesforceOAuthLoginMixin:
18
+ """Reusable PKCE, token exchange, and profile helpers for Salesforce
19
+ logins."""
20
+
21
+ model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
22
+
23
+ base_url: str
24
+ client_id: str
25
+ client_secret: SecretStr
26
+ redirect_uri: str
27
+ state_secret: SecretBytes
28
+ scope: str = Field(default="refresh_token")
29
+ http_client_factory: Callable[[], RetryingAsyncClient] = Field(
30
+ default=RetryingAsyncClient, exclude=True, repr=False
31
+ )
32
+
33
+ AUTH_PATH: str = Field(
34
+ default="/services/oauth2/authorize", exclude=True, repr=False
35
+ )
36
+ TOKEN_PATH: str = Field(
37
+ default="/services/oauth2/token", exclude=True, repr=False
38
+ )
39
+ USERINFO_PATH: str = Field(
40
+ default="/services/oauth2/userinfo", exclude=True, repr=False
41
+ )
42
+
43
+ def _client_secret_value(self) -> str:
44
+ return self.client_secret.get_secret_value()
45
+
46
+ def _state_secret_value(self) -> bytes:
47
+ return self.state_secret.get_secret_value()
48
+
49
+ def _authorization_endpoint(self) -> str:
50
+ return f"{self.base_url.rstrip('/')}{self.AUTH_PATH}"
51
+
52
+ def _token_endpoint(self) -> str:
53
+ return f"{self.base_url.rstrip('/')}{self.TOKEN_PATH}"
54
+
55
+ def _userinfo_endpoint(self) -> str:
56
+ return f"{self.base_url.rstrip('/')}{self.USERINFO_PATH}"
57
+
58
+ async def _auth_payload(self) -> Mapping[str, str]:
59
+ verifier, challenge = make_pkce_pair()
60
+ state = sign_state(self._state_secret_value(), {"verifier": verifier})
61
+ url = (
62
+ f"{self._authorization_endpoint()}?response_type=code"
63
+ f"&client_id={self.client_id}&redirect_uri={self.redirect_uri}"
64
+ f"&scope={self.scope}&state={state}"
65
+ f"&code_challenge={challenge}&code_challenge_method=S256"
66
+ )
67
+ return {"url": url, "state": state, "verifier": verifier}
68
+
69
+ async def _exchange_tokens(
70
+ self, code: str, state: str
71
+ ) -> Mapping[str, Any]:
72
+ payload = verify_state(self._state_secret_value(), state)
73
+ form = {
74
+ "grant_type": "authorization_code",
75
+ "code": code,
76
+ "redirect_uri": self.redirect_uri,
77
+ "client_id": self.client_id,
78
+ "client_secret": self._client_secret_value(),
79
+ "code_verifier": payload["verifier"],
80
+ }
81
+ async with self.http_client_factory() as client:
82
+ response = await client.post_retry(
83
+ self._token_endpoint(),
84
+ data=form,
85
+ headers={"Accept": "application/json"},
86
+ )
87
+ response.raise_for_status()
88
+ return response.json()
89
+
90
+ async def _fetch_userinfo(self, access_token: str) -> Mapping[str, Any]:
91
+ headers = {
92
+ "Authorization": f"Bearer {access_token}",
93
+ "Accept": "application/json",
94
+ }
95
+ async with self.http_client_factory() as client:
96
+ response = await client.get_retry(
97
+ self._userinfo_endpoint(), headers=headers
98
+ )
99
+ response.raise_for_status()
100
+ return response.json()
101
+
102
+ async def _fetch_identity_profile(
103
+ self, identity_url: Optional[str], access_token: str
104
+ ) -> Mapping[str, Any]:
105
+ if not identity_url:
106
+ return {}
107
+ headers = {
108
+ "Authorization": f"Bearer {access_token}",
109
+ "Accept": "application/json",
110
+ }
111
+ async with self.http_client_factory() as client:
112
+ response = await client.get_retry(identity_url, headers=headers)
113
+ response.raise_for_status()
114
+ return response.json()
115
+
116
+
117
+ __all__ = ["SalesforceOAuthLoginMixin"]
@@ -0,0 +1,126 @@
1
+ """Salesforce OpenID Connect 1.0 JWT bearer app client wrapper."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Callable, Dict, Literal, Mapping, Optional, Tuple
7
+
8
+ from pydantic import ConfigDict, Field, PrivateAttr
9
+
10
+ from swarmauri_base.ComponentBase import ComponentBase
11
+ from swarmauri_base.auth_idp import OIDC10AppClientBase, RetryingAsyncClient
12
+
13
+ from .SalesforceOAuth20AppClient import (
14
+ SalesforceOAuth20AppClient,
15
+ PrivateKeySecret,
16
+ )
17
+
18
+
19
+ @ComponentBase.register_type(OIDC10AppClientBase, "SalesforceOIDC10AppClient")
20
+ class SalesforceOIDC10AppClient(OIDC10AppClientBase):
21
+ """Discover Salesforce endpoints and request machine tokens over JWT
22
+ bearer."""
23
+
24
+ model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
25
+
26
+ issuer: str
27
+ client_id: str
28
+ user: str
29
+ private_key_pem: Optional[PrivateKeySecret] = Field(
30
+ default=None, repr=False
31
+ )
32
+ private_key_jwk: Optional[Mapping[str, Any]] = Field(
33
+ default=None, repr=False
34
+ )
35
+ aud: Optional[str] = None
36
+ scope: Optional[str] = None
37
+ jwt_lifetime_seconds: int = Field(default=180, ge=1)
38
+ cache_ttl_seconds: Optional[int] = Field(default=None, ge=1)
39
+ cache_skew_seconds: int = Field(default=30, ge=0)
40
+ discovery_path: str = Field(default="/.well-known/openid-configuration")
41
+ discovery_cache_ttl_seconds: int = Field(default=3600, ge=0)
42
+ http_client_factory: Callable[[], RetryingAsyncClient] = Field(
43
+ default=RetryingAsyncClient, exclude=True, repr=False
44
+ )
45
+
46
+ type: Literal["SalesforceOIDC10AppClient"] = "SalesforceOIDC10AppClient"
47
+
48
+ _discovery_cache: Optional[Tuple[Dict[str, Any], float]] = PrivateAttr(
49
+ default=None
50
+ )
51
+ _token_client: Optional[SalesforceOAuth20AppClient] = PrivateAttr(
52
+ default=None
53
+ )
54
+ _token_endpoint: Optional[str] = PrivateAttr(default=None)
55
+
56
+ async def access_token_payload(
57
+ self, scope: Optional[str] = None
58
+ ) -> Dict[str, Any]:
59
+ discovery = await self._discover()
60
+ token_endpoint = self._resolve_token_endpoint(discovery)
61
+ client = self._ensure_token_client(token_endpoint)
62
+ effective_scope = scope if scope is not None else self.scope
63
+ return await client.access_token_payload(scope=effective_scope)
64
+
65
+ async def access_token(self, scope: Optional[str] = None) -> str:
66
+ payload = await self.access_token_payload(scope=scope)
67
+ token = payload.get("access_token")
68
+ if not isinstance(token, str):
69
+ raise ValueError("access_token missing from Salesforce response")
70
+ return token
71
+
72
+ async def _discover(self) -> Dict[str, Any]:
73
+ now = time.time()
74
+ cached = self._discovery_cache
75
+ if cached and self.discovery_cache_ttl_seconds > 0:
76
+ payload, expires_at = cached
77
+ if now < expires_at:
78
+ return dict(payload)
79
+
80
+ url = f"{self.issuer.rstrip('/')}{self.discovery_path}"
81
+ async with self.http_client_factory() as client:
82
+ response = await client.get_retry(
83
+ url, headers={"Accept": "application/json"}
84
+ )
85
+ response.raise_for_status()
86
+ data = dict(response.json())
87
+
88
+ if self.discovery_cache_ttl_seconds > 0:
89
+ self._discovery_cache = (
90
+ data,
91
+ now + self.discovery_cache_ttl_seconds,
92
+ )
93
+
94
+ return data
95
+
96
+ def _resolve_token_endpoint(self, discovery: Mapping[str, Any]) -> str:
97
+ endpoint = discovery.get("token_endpoint")
98
+ if isinstance(endpoint, str) and endpoint:
99
+ return endpoint
100
+ return f"{self.issuer.rstrip('/')}/services/oauth2/token"
101
+
102
+ def _ensure_token_client(
103
+ self, token_endpoint: str
104
+ ) -> SalesforceOAuth20AppClient:
105
+ if self._token_client and self._token_endpoint == token_endpoint:
106
+ return self._token_client
107
+
108
+ client = SalesforceOAuth20AppClient(
109
+ token_endpoint=token_endpoint,
110
+ client_id=self.client_id,
111
+ user=self.user,
112
+ private_key_pem=self.private_key_pem,
113
+ private_key_jwk=self.private_key_jwk,
114
+ aud=self.aud or self.issuer.rstrip("/"),
115
+ scope=self.scope,
116
+ jwt_lifetime_seconds=self.jwt_lifetime_seconds,
117
+ cache_ttl_seconds=self.cache_ttl_seconds,
118
+ cache_skew_seconds=self.cache_skew_seconds,
119
+ http_client_factory=self.http_client_factory,
120
+ )
121
+ self._token_client = client
122
+ self._token_endpoint = token_endpoint
123
+ return client
124
+
125
+
126
+ __all__ = ["SalesforceOIDC10AppClient"]
@@ -0,0 +1,50 @@
1
+ """Salesforce 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 .SalesforceOIDCLoginMixin import SalesforceOIDCLoginMixin
11
+
12
+
13
+ @ComponentBase.register_type(OIDC10LoginBase, "SalesforceOIDC10Login")
14
+ class SalesforceOIDC10Login(SalesforceOIDCLoginMixin, OIDC10LoginBase):
15
+ """Implement Salesforce OIDC 1.0 Authorization Code flow with PKCE."""
16
+
17
+ async def auth_url(self) -> Mapping[str, str]:
18
+ metadata = await self._metadata()
19
+ self.discovery_cache = metadata
20
+ payload = await self._auth_payload()
21
+ return {"url": payload["url"], "state": payload["state"]}
22
+
23
+ async def exchange(self, code: str, state: str) -> Mapping[str, Any]:
24
+ metadata = await self._metadata()
25
+ self.discovery_cache = metadata
26
+ tokens = await self._exchange_tokens(code, state)
27
+ claims = await self._decode_id_token(tokens, metadata)
28
+ email = claims.get("email")
29
+ name = (
30
+ claims.get("name") or claims.get("preferred_username") or "Unknown"
31
+ )
32
+ if (not email or name == "Unknown") and metadata.get(
33
+ "userinfo_endpoint"
34
+ ):
35
+ profile = await self._fetch_userinfo(tokens["access_token"])
36
+ email = email or profile.get("email")
37
+ name = (
38
+ name
39
+ if name != "Unknown"
40
+ else profile.get("name")
41
+ or profile.get("preferred_username")
42
+ or "Unknown"
43
+ )
44
+ return {
45
+ "issuer": "salesforce-oidc",
46
+ "sub": claims["sub"],
47
+ "email": email,
48
+ "name": name,
49
+ "raw": {"tokens": tokens, "claims": claims},
50
+ }
@@ -0,0 +1,91 @@
1
+ """Shared helpers for Salesforce OIDC-based login implementations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Mapping, Optional
6
+
7
+ import jwt
8
+
9
+ from .SalesforceOAuthLoginMixin import SalesforceOAuthLoginMixin
10
+
11
+
12
+ class SalesforceOIDCLoginMixin(SalesforceOAuthLoginMixin):
13
+ """Extend the Salesforce OAuth mixin with discovery and ID token
14
+ verification."""
15
+
16
+ discovery_cache: Optional[Mapping[str, Any]] = None
17
+
18
+ DISCOVERY_PATH = "/.well-known/openid-configuration"
19
+
20
+ async def _metadata(self) -> Mapping[str, Any]: # type: ignore[override]
21
+ if self.discovery_cache is None:
22
+ url = f"{self.base_url.rstrip('/')}{self.DISCOVERY_PATH}"
23
+ async with self.http_client_factory() as client:
24
+ response = await client.get_retry(
25
+ url, headers={"Accept": "application/json"}
26
+ )
27
+ response.raise_for_status()
28
+ self.discovery_cache = response.json()
29
+ return self.discovery_cache
30
+
31
+ def _authorization_endpoint(self) -> str: # type: ignore[override]
32
+ metadata = self.discovery_cache
33
+ if metadata and metadata.get("authorization_endpoint"):
34
+ return metadata["authorization_endpoint"]
35
+ return super()._authorization_endpoint()
36
+
37
+ def _token_endpoint(self) -> str: # type: ignore[override]
38
+ metadata = self.discovery_cache
39
+ if metadata and metadata.get("token_endpoint"):
40
+ return metadata["token_endpoint"]
41
+ return super()._token_endpoint()
42
+
43
+ def _userinfo_endpoint(self) -> str: # type: ignore[override]
44
+ metadata = self.discovery_cache
45
+ if metadata and metadata.get("userinfo_endpoint"):
46
+ return metadata["userinfo_endpoint"]
47
+ return super()._userinfo_endpoint()
48
+
49
+ async def _decode_id_token(
50
+ self,
51
+ tokens: Mapping[str, Any],
52
+ metadata: Mapping[str, Any],
53
+ ) -> Mapping[str, Any]:
54
+ id_token = tokens.get("id_token")
55
+ if not id_token:
56
+ raise ValueError("no id_token in response")
57
+ header = jwt.get_unverified_header(id_token)
58
+ kid = header.get("kid")
59
+ if not kid:
60
+ raise ValueError("missing kid in id_token header")
61
+ jwks_uri = metadata.get("jwks_uri")
62
+ if not jwks_uri:
63
+ raise ValueError("no jwks_uri in discovery metadata")
64
+ async with self.http_client_factory() as client:
65
+ response = await client.get_retry(
66
+ jwks_uri, headers={"Accept": "application/json"}
67
+ )
68
+ response.raise_for_status()
69
+ jwks = response.json()
70
+ key_entry = next(
71
+ (
72
+ entry
73
+ for entry in jwks.get("keys", [])
74
+ if entry.get("kid") == kid
75
+ ),
76
+ None,
77
+ )
78
+ if not key_entry:
79
+ raise ValueError("signing key not found")
80
+ algorithm = header.get("alg", "RS256")
81
+ signer = jwt.algorithms.RSAAlgorithm.from_jwk(key_entry)
82
+ return jwt.decode(
83
+ id_token,
84
+ signer,
85
+ algorithms=[algorithm],
86
+ audience=self.client_id,
87
+ issuer=metadata.get("issuer", self.base_url),
88
+ )
89
+
90
+
91
+ __all__ = ["SalesforceOIDCLoginMixin"]
@@ -0,0 +1,17 @@
1
+ """Salesforce identity provider implementations for Swarmauri."""
2
+
3
+ from .SalesforceOAuth20AppClient import SalesforceOAuth20AppClient
4
+ from .SalesforceOAuth20Login import SalesforceOAuth20Login
5
+ from .SalesforceOAuth21AppClient import SalesforceOAuth21AppClient
6
+ from .SalesforceOAuth21Login import SalesforceOAuth21Login
7
+ from .SalesforceOIDC10AppClient import SalesforceOIDC10AppClient
8
+ from .SalesforceOIDC10Login import SalesforceOIDC10Login
9
+
10
+ __all__ = [
11
+ "SalesforceOAuth20AppClient",
12
+ "SalesforceOAuth20Login",
13
+ "SalesforceOAuth21AppClient",
14
+ "SalesforceOAuth21Login",
15
+ "SalesforceOIDC10AppClient",
16
+ "SalesforceOIDC10Login",
17
+ ]