multicloud-py-sts 0.1.6__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,206 @@
1
+ Apache License Version 2.0
2
+
3
+ Copyright (c) 2026 Salesforce, Inc.
4
+ All rights reserved.
5
+
6
+ Apache License
7
+ Version 2.0, January 2004
8
+ http://www.apache.org/licenses/
9
+
10
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
11
+
12
+ 1. Definitions.
13
+
14
+ "License" shall mean the terms and conditions for use, reproduction,
15
+ and distribution as defined by Sections 1 through 9 of this document.
16
+
17
+ "Licensor" shall mean the copyright owner or entity authorized by
18
+ the copyright owner that is granting the License.
19
+
20
+ "Legal Entity" shall mean the union of the acting entity and all
21
+ other entities that control, are controlled by, or are under common
22
+ control with that entity. For the purposes of this definition,
23
+ "control" means (i) the power, direct or indirect, to cause the
24
+ direction or management of such entity, whether by contract or
25
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
26
+ outstanding shares, or (iii) beneficial ownership of such entity.
27
+
28
+ "You" (or "Your") shall mean an individual or Legal Entity
29
+ exercising permissions granted by this License.
30
+
31
+ "Source" form shall mean the preferred form for making modifications,
32
+ including but not limited to software source code, documentation
33
+ source, and configuration files.
34
+
35
+ "Object" form shall mean any form resulting from mechanical
36
+ transformation or translation of a Source form, including but
37
+ not limited to compiled object code, generated documentation,
38
+ and conversions to other media types.
39
+
40
+ "Work" shall mean the work of authorship, whether in Source or
41
+ Object form, made available under the License, as indicated by a
42
+ copyright notice that is included in or attached to the work
43
+ (an example is provided in the Appendix below).
44
+
45
+ "Derivative Works" shall mean any work, whether in Source or Object
46
+ form, that is based on (or derived from) the Work and for which the
47
+ editorial revisions, annotations, elaborations, or other modifications
48
+ represent, as a whole, an original work of authorship. For the purposes
49
+ of this License, Derivative Works shall not include works that remain
50
+ separable from, or merely link (or bind by name) to the interfaces of,
51
+ the Work and Derivative Works thereof.
52
+
53
+ "Contribution" shall mean any work of authorship, including
54
+ the original version of the Work and any modifications or additions
55
+ to that Work or Derivative Works thereof, that is intentionally
56
+ submitted to Licensor for inclusion in the Work by the copyright owner
57
+ or by an individual or Legal Entity authorized to submit on behalf of
58
+ the copyright owner. For the purposes of this definition, "submitted"
59
+ means any form of electronic, verbal, or written communication sent
60
+ to the Licensor or its representatives, including but not limited to
61
+ communication on electronic mailing lists, source code control systems,
62
+ and issue tracking systems that are managed by, or on behalf of, the
63
+ Licensor for the purpose of discussing and improving the Work, but
64
+ excluding communication that is conspicuously marked or otherwise
65
+ designated in writing by the copyright owner as "Not a Contribution."
66
+
67
+ "Contributor" shall mean Licensor and any individual or Legal Entity
68
+ on behalf of whom a Contribution has been received by Licensor and
69
+ subsequently incorporated within the Work.
70
+
71
+ 2. Grant of Copyright License. Subject to the terms and conditions of
72
+ this License, each Contributor hereby grants to You a perpetual,
73
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
74
+ copyright license to reproduce, prepare Derivative Works of,
75
+ publicly display, publicly perform, sublicense, and distribute the
76
+ Work and such Derivative Works in Source or Object form.
77
+
78
+ 3. Grant of Patent License. Subject to the terms and conditions of
79
+ this License, each Contributor hereby grants to You a perpetual,
80
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
81
+ (except as stated in this section) patent license to make, have made,
82
+ use, offer to sell, sell, import, and otherwise transfer the Work,
83
+ where such license applies only to those patent claims licensable
84
+ by such Contributor that are necessarily infringed by their
85
+ Contribution(s) alone or by combination of their Contribution(s)
86
+ with the Work to which such Contribution(s) was submitted. If You
87
+ institute patent litigation against any entity (including a
88
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
89
+ or a Contribution incorporated within the Work constitutes direct
90
+ or contributory patent infringement, then any patent licenses
91
+ granted to You under this License for that Work shall terminate
92
+ as of the date such litigation is filed.
93
+
94
+ 4. Redistribution. You may reproduce and distribute copies of the
95
+ Work or Derivative Works thereof in any medium, with or without
96
+ modifications, and in Source or Object form, provided that You
97
+ meet the following conditions:
98
+
99
+ (a) You must give any other recipients of the Work or
100
+ Derivative Works a copy of this License; and
101
+
102
+ (b) You must cause any modified files to carry prominent notices
103
+ stating that You changed the files; and
104
+
105
+ (c) You must retain, in the Source form of any Derivative Works
106
+ that You distribute, all copyright, patent, trademark, and
107
+ attribution notices from the Source form of the Work,
108
+ excluding those notices that do not pertain to any part of
109
+ the Derivative Works; and
110
+
111
+ (d) If the Work includes a "NOTICE" text file as part of its
112
+ distribution, then any Derivative Works that You distribute must
113
+ include a readable copy of the attribution notices contained
114
+ within such NOTICE file, excluding those notices that do not
115
+ pertain to any part of the Derivative Works, in at least one
116
+ of the following places: within a NOTICE text file distributed
117
+ as part of the Derivative Works; within the Source form or
118
+ documentation, if provided along with the Derivative Works; or,
119
+ within a display generated by the Derivative Works, if and
120
+ wherever such third-party notices normally appear. The contents
121
+ of the NOTICE file are for informational purposes only and
122
+ do not modify the License. You may add Your own attribution
123
+ notices within Derivative Works that You distribute, alongside
124
+ or as an addendum to the NOTICE text from the Work, provided
125
+ that such additional attribution notices cannot be construed
126
+ as modifying the License.
127
+
128
+ You may add Your own copyright statement to Your modifications and
129
+ may provide additional or different license terms and conditions
130
+ for use, reproduction, or distribution of Your modifications, or
131
+ for any such Derivative Works as a whole, provided Your use,
132
+ reproduction, and distribution of the Work otherwise complies with
133
+ the conditions stated in this License.
134
+
135
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
136
+ any Contribution intentionally submitted for inclusion in the Work
137
+ by You to the Licensor shall be under the terms and conditions of
138
+ this License, without any additional terms or conditions.
139
+ Notwithstanding the above, nothing herein shall supersede or modify
140
+ the terms of any separate license agreement you may have executed
141
+ with Licensor regarding such Contributions.
142
+
143
+ 6. Trademarks. This License does not grant permission to use the trade
144
+ names, trademarks, service marks, or product names of the Licensor,
145
+ except as required for reasonable and customary use in describing the
146
+ origin of the Work and reproducing the content of the NOTICE file.
147
+
148
+ 7. Disclaimer of Warranty. Unless required by applicable law or
149
+ agreed to in writing, Licensor provides the Work (and each
150
+ Contributor provides its Contributions) on an "AS IS" BASIS,
151
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
152
+ implied, including, without limitation, any warranties or conditions
153
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
154
+ PARTICULAR PURPOSE. You are solely responsible for determining the
155
+ appropriateness of using or redistributing the Work and assume any
156
+ risks associated with Your exercise of permissions under this License.
157
+
158
+ 8. Limitation of Liability. In no event and under no legal theory,
159
+ whether in tort (including negligence), contract, or otherwise,
160
+ unless required by applicable law (such as deliberate and grossly
161
+ negligent acts) or agreed to in writing, shall any Contributor be
162
+ liable to You for damages, including any direct, indirect, special,
163
+ incidental, or consequential damages of any character arising as a
164
+ result of this License or out of the use or inability to use the
165
+ Work (including but not limited to damages for loss of goodwill,
166
+ work stoppage, computer failure or malfunction, or any and all
167
+ other commercial damages or losses), even if such Contributor
168
+ has been advised of the possibility of such damages.
169
+
170
+ 9. Accepting Warranty or Additional Liability. While redistributing
171
+ the Work or Derivative Works thereof, You may choose to offer,
172
+ and charge a fee for, acceptance of support, warranty, indemnity,
173
+ or other liability obligations and/or rights consistent with this
174
+ License. However, in accepting such obligations, You may act only
175
+ on Your own behalf and on Your sole responsibility, not on behalf
176
+ of any other Contributor, and only if You agree to indemnify,
177
+ defend, and hold each Contributor harmless for any liability
178
+ incurred by, or claims asserted against, such Contributor by reason
179
+ of your accepting any such warranty or additional liability.
180
+
181
+ END OF TERMS AND CONDITIONS
182
+
183
+ APPENDIX: How to apply the Apache License to your work.
184
+
185
+ To apply the Apache License to your work, attach the following
186
+ boilerplate notice, with the fields enclosed by brackets "{}"
187
+ replaced with your own identifying information. (Don't include
188
+ the brackets!) The text should be enclosed in the appropriate
189
+ comment syntax for the file format. We also recommend that a
190
+ file or class name and description of purpose be included on the
191
+ same "printed page" as the copyright notice for easier
192
+ identification within third-party archives.
193
+
194
+ Copyright {yyyy} {name of copyright owner}
195
+
196
+ Licensed under the Apache License, Version 2.0 (the "License");
197
+ you may not use this file except in compliance with the License.
198
+ You may obtain a copy of the License at
199
+
200
+ http://www.apache.org/licenses/LICENSE-2.0
201
+
202
+ Unless required by applicable law or agreed to in writing, software
203
+ distributed under the License is distributed on an "AS IS" BASIS,
204
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
205
+ See the License for the specific language governing permissions and
206
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.4
2
+ Name: multicloud-py-sts
3
+ Version: 0.1.6
4
+ Summary: Cloud-agnostic Security Token Service client for the python-multicloud SDK. Pair with a provider package (multicloud-sts-aws / -gcp / -alibaba) for actual cloud calls.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/salesforce/multicloud-py
7
+ Project-URL: Repository, https://github.com/salesforce/multicloud-py
8
+ Project-URL: Issues, https://github.com/salesforce/multicloud-py/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE.txt
14
+ Requires-Dist: multicloud-py-common>=0.1.6
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
17
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
18
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ MultiCloud Python SDK package.
@@ -0,0 +1,57 @@
1
+ """Cloud-agnostic STS client package.
2
+
3
+ Public entry point — :class:`StsClient`::
4
+
5
+ from multicloud.sts.sts_client import StsClient
6
+
7
+ with StsClient(provider="aws", region="us-west-2") as sts:
8
+ identity = sts.get_caller_identity()
9
+ creds = sts.assume_role(
10
+ "arn:aws:iam::123:role/MyRole",
11
+ session_name="dev",
12
+ )
13
+
14
+ Provider classes (``AwsSts``, ``GcpSts``, ...) live in sibling
15
+ distributions (``multicloud-sts-aws``, ``-gcp``, ``-alibaba``) and are
16
+ discovered at runtime via setuptools entry points. They are hidden
17
+ behind the registry; users never reference them directly.
18
+ """
19
+
20
+ from multicloud.sts.sts_client.client import StsClient, StsUtilities
21
+ from multicloud.sts.sts_client.driver import (
22
+ STS_REGISTRY,
23
+ AvailabilityCondition,
24
+ BaseSts,
25
+ CallerIdentity,
26
+ CredentialScope,
27
+ CredentialsOverrider,
28
+ CredentialsType,
29
+ ScopeRule,
30
+ StsCredentials,
31
+ StsValidator,
32
+ )
33
+ from multicloud.sts.sts_client.utilities import (
34
+ STS_UTILITIES_REGISTRY,
35
+ BaseStsUtilities,
36
+ SignedAuthRequest,
37
+ )
38
+
39
+ __all__ = [
40
+ "StsClient",
41
+ "StsUtilities",
42
+ "AvailabilityCondition",
43
+ "CallerIdentity",
44
+ "CredentialScope",
45
+ "CredentialsOverrider",
46
+ "CredentialsType",
47
+ "ScopeRule",
48
+ "SignedAuthRequest",
49
+ "StsCredentials",
50
+ # Internal: driver layer (re-exported for advanced/testing use; not
51
+ # part of the user-facing surface)
52
+ "BaseSts",
53
+ "BaseStsUtilities",
54
+ "STS_REGISTRY",
55
+ "STS_UTILITIES_REGISTRY",
56
+ "StsValidator",
57
+ ]
@@ -0,0 +1,304 @@
1
+ """User-facing :class:`StsClient` — the public entry point for STS ops.
2
+
3
+ Three-layer architecture:
4
+
5
+ 1. **Client** (this file) — what users import; provider-agnostic API.
6
+ 2. **Driver** (:class:`BaseSts` in ``driver.py``) — internal abstract
7
+ contract; defines public methods + provider hooks.
8
+ 3. **Provider** — concrete impls callers never reference directly.
9
+
10
+ User code stays cloud-agnostic; only the ``provider`` kwarg selects the
11
+ registered implementation::
12
+
13
+ from multicloud.sts.sts_client import StsClient
14
+
15
+ with StsClient(provider="<provider-id>", region="<region>") as sts:
16
+ identity = sts.get_caller_identity()
17
+ creds = sts.assume_role(
18
+ "<role-resource-identifier>",
19
+ session_name="dev",
20
+ )
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from typing import Any, Mapping, Optional
26
+
27
+ from multicloud.sts.sts_client.driver import (
28
+ STS_REGISTRY,
29
+ BaseSts,
30
+ CallerIdentity,
31
+ CredentialScope,
32
+ CredentialsOverrider,
33
+ StsCredentials,
34
+ )
35
+ from multicloud.sts.sts_client.utilities import (
36
+ STS_UTILITIES_REGISTRY,
37
+ BaseStsUtilities,
38
+ SignedAuthRequest,
39
+ )
40
+
41
+
42
+ class StsClient:
43
+ """Cloud-agnostic Security Token Service client.
44
+
45
+ Args:
46
+ provider: Registered provider id used to select the implementation.
47
+ region: Region (interpreted per provider). Optional; falls back
48
+ to provider defaults.
49
+ endpoint: Endpoint override URL. Optional.
50
+ credentials_overrider: Override default credential resolution.
51
+ Optional.
52
+ properties: Provider-specific extras passed through to the
53
+ driver constructor as keyword arguments.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ *,
59
+ provider: str,
60
+ region: Optional[str] = None,
61
+ endpoint: Optional[str] = None,
62
+ credentials_overrider: Optional[CredentialsOverrider] = None,
63
+ properties: Optional[Mapping[str, Any]] = None,
64
+ ) -> None:
65
+ sts_cls = STS_REGISTRY.get(provider)
66
+ kwargs: dict = {}
67
+ if region is not None:
68
+ kwargs["region"] = region
69
+ if endpoint is not None:
70
+ kwargs["endpoint_url"] = endpoint
71
+ if credentials_overrider is not None:
72
+ kwargs["credentials_overrider"] = credentials_overrider
73
+ if properties:
74
+ kwargs.update(properties)
75
+ self._sts: BaseSts = sts_cls(**kwargs)
76
+
77
+ # properties
78
+
79
+ @property
80
+ def provider(self) -> str:
81
+ return self._sts.get_provider_id()
82
+
83
+ @property
84
+ def region(self) -> Optional[str]:
85
+ return self._sts.region
86
+
87
+ # operations (forwarding to the driver)
88
+
89
+ def get_caller_identity(self, *, aud: Optional[str] = None) -> CallerIdentity:
90
+ """Return identity info for the current credentials.
91
+
92
+ Args:
93
+ aud: Target audience for the identity token. Some providers
94
+ use this for audience-scoped token generation; others
95
+ ignore it.
96
+ """
97
+ try:
98
+ return self._sts.get_caller_identity(aud=aud)
99
+ except Exception as exc:
100
+ raise self._sts.translate_error(exc) from exc
101
+
102
+ def assume_role(
103
+ self,
104
+ role: str,
105
+ *,
106
+ session_name: str = "",
107
+ expiration: int = 3600,
108
+ external_id: Optional[str] = None,
109
+ policy: Optional[str] = None,
110
+ tags: Optional[Mapping[str, str]] = None,
111
+ credential_scope: Optional[CredentialScope] = None,
112
+ ) -> StsCredentials:
113
+ """Assume a role and return temporary credentials.
114
+
115
+ Args:
116
+ role: Cloud resource name to assume.
117
+ session_name: Session identifier.
118
+ expiration: Duration in seconds (default 3600).
119
+ external_id: External ID for cross-account access (optional).
120
+ policy: Inline policy to scope down permissions (optional).
121
+ tags: Session tags (optional).
122
+ credential_scope: Optional scope to downscope credentials.
123
+ """
124
+ try:
125
+ return self._sts.assume_role(
126
+ role,
127
+ session_name=session_name,
128
+ expiration=expiration,
129
+ external_id=external_id,
130
+ policy=policy,
131
+ tags=tags,
132
+ credential_scope=credential_scope,
133
+ )
134
+ except Exception as exc:
135
+ raise self._sts.translate_error(exc) from exc
136
+
137
+ def get_access_token(
138
+ self,
139
+ *,
140
+ audience: Optional[str] = None,
141
+ scopes: Optional[list[str]] = None,
142
+ duration_seconds: Optional[int] = None,
143
+ ) -> StsCredentials:
144
+ """Retrieve a fresh access token from the provider.
145
+
146
+ Args:
147
+ audience: Target audience for an audience-scoped token.
148
+ Interpreted per provider; see the provider implementation
149
+ for details. Mutually exclusive with ``scopes``.
150
+ scopes: OAuth scopes for a scoped token. Interpreted per
151
+ provider; see the provider implementation for details.
152
+ Mutually exclusive with ``audience``.
153
+ duration_seconds: Requested token duration. Interpreted per
154
+ provider; some providers may ignore or cap this value
155
+ (optional).
156
+ """
157
+ try:
158
+ return self._sts.get_access_token(
159
+ audience=audience, scopes=scopes, duration_seconds=duration_seconds
160
+ )
161
+ except Exception as exc:
162
+ raise self._sts.translate_error(exc) from exc
163
+
164
+ def generate_service_account_token(
165
+ self,
166
+ target_principal: str,
167
+ *,
168
+ scopes: list[str],
169
+ lifetime: int = 3600,
170
+ ) -> StsCredentials:
171
+ """Generate a token for a target service account via impersonation.
172
+
173
+ Args:
174
+ target_principal: Service account to impersonate. Format is
175
+ interpreted per provider; see the provider implementation
176
+ for details.
177
+ scopes: OAuth scopes to request on the generated token.
178
+ lifetime: Token lifetime in seconds (default 3600). Supported
179
+ range and behaviour are provider-specific; see the provider
180
+ implementation for details.
181
+ """
182
+ try:
183
+ return self._sts.generate_service_account_token(
184
+ target_principal, scopes=scopes, lifetime=lifetime
185
+ )
186
+ except Exception as exc:
187
+ raise self._sts.translate_error(exc) from exc
188
+
189
+ def assume_role_with_web_identity(
190
+ self,
191
+ role: str,
192
+ web_identity_token: str,
193
+ *,
194
+ session_name: str = "",
195
+ expiration: int = 3600,
196
+ ) -> StsCredentials:
197
+ """Exchange a web identity (OIDC) token for temporary credentials.
198
+
199
+ Args:
200
+ role: Cloud resource identifier to assume (interpretation is
201
+ provider-specific).
202
+ web_identity_token: The OIDC/JWT token proving external identity.
203
+ session_name: Session identifier (optional; provider support
204
+ varies).
205
+ expiration: Requested duration in seconds (default 3600).
206
+ Provider support varies; some providers may ignore this
207
+ parameter.
208
+ """
209
+ try:
210
+ return self._sts.assume_role_with_web_identity(
211
+ role,
212
+ web_identity_token,
213
+ session_name=session_name,
214
+ expiration=expiration,
215
+ )
216
+ except Exception as exc:
217
+ raise self._sts.translate_error(exc) from exc
218
+
219
+ # lifecycle
220
+
221
+ def close(self) -> None:
222
+ """Release underlying resources."""
223
+ self._sts.close()
224
+
225
+ def __enter__(self) -> "StsClient":
226
+ return self
227
+
228
+ def __exit__(self, exc_type, exc, tb) -> None:
229
+ self.close()
230
+
231
+
232
+ class StsUtilities:
233
+ """Cloud-agnostic STS utility functions (offline request signing).
234
+
235
+ Companion to :class:`StsClient` for utilities that sign a request
236
+ locally instead of calling the provider. The signed request is handed
237
+ to another system that replays it to verify the caller's identity.
238
+
239
+ Args:
240
+ provider: Registered provider id used to select the implementation.
241
+ region: Region (interpreted per provider). Optional for some
242
+ providers; required by others for request signing.
243
+ credentials_overrider: Override default credential resolution.
244
+ Optional.
245
+ properties: Provider-specific extras passed through to the driver
246
+ constructor as keyword arguments.
247
+ """
248
+
249
+ def __init__(
250
+ self,
251
+ *,
252
+ provider: str,
253
+ region: Optional[str] = None,
254
+ credentials_overrider: Optional[CredentialsOverrider] = None,
255
+ properties: Optional[Mapping[str, Any]] = None,
256
+ ) -> None:
257
+ utils_cls = STS_UTILITIES_REGISTRY.get(provider)
258
+ kwargs: dict = {}
259
+ if region is not None:
260
+ kwargs["region"] = region
261
+ if credentials_overrider is not None:
262
+ kwargs["credentials_overrider"] = credentials_overrider
263
+ if properties:
264
+ kwargs.update(properties)
265
+ self._utils: BaseStsUtilities = utils_cls(**kwargs)
266
+
267
+ # properties
268
+
269
+ @property
270
+ def provider(self) -> str:
271
+ return self._utils.get_provider_id()
272
+
273
+ @property
274
+ def region(self) -> Optional[str]:
275
+ return self._utils.region
276
+
277
+ # operations (forwarding to the driver)
278
+
279
+ def create_signed_auth_request(
280
+ self,
281
+ *,
282
+ custom_headers: Optional[Mapping[str, str]] = None,
283
+ ) -> SignedAuthRequest:
284
+ """Produce a signed identity request for cloud-native auth.
285
+
286
+ Args:
287
+ custom_headers: Extra headers to fold into the signature so the
288
+ system replaying the request can bind them to the identity.
289
+ """
290
+ try:
291
+ return self._utils.create_signed_auth_request(custom_headers=custom_headers)
292
+ except Exception as exc:
293
+ raise self._utils.translate_error(exc) from exc
294
+
295
+ # lifecycle
296
+
297
+ def close(self) -> None:
298
+ self._utils.close()
299
+
300
+ def __enter__(self) -> "StsUtilities":
301
+ return self
302
+
303
+ def __exit__(self, exc_type, exc, tb) -> None:
304
+ self.close()
@@ -0,0 +1,398 @@
1
+ """Driver-level abstractions for the Security Token Service (STS).
2
+
3
+ Same ABC + template-method shape as
4
+ ``multicloud.blob.blob_client.driver.BaseBlobStore``: providers
5
+ implement ``do_*`` hooks; the public ``get_caller_identity`` /
6
+ ``assume_role`` / ``get_access_token`` methods on :class:`BaseSts`
7
+ validate input then delegate.
8
+
9
+ Users never reach this layer directly — they construct a
10
+ :class:`StsClient` (in ``client.py``), which holds a ``BaseSts``
11
+ instance internally.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from abc import ABC, abstractmethod
17
+ from dataclasses import dataclass
18
+ from typing import Mapping, Optional
19
+
20
+ from multicloud.common.credentials import (
21
+ CredentialsOverrider,
22
+ CredentialsType,
23
+ StsCredentials,
24
+ )
25
+ from multicloud.common.exceptions import InvalidArgumentException
26
+ from multicloud.common.provider import Provider, ProviderRegistry
27
+
28
+ # Service-scoped registry. Provider distributions advertise themselves
29
+ # under the ``multicloud.sts.providers`` entry-point group; the registry
30
+ # imports those modules lazily on first use, at which point each provider's
31
+ # ``@STS_REGISTRY.register("aws")`` decorator stamps the class.
32
+ STS_REGISTRY = ProviderRegistry(
33
+ service_name="sts",
34
+ entry_point_group="multicloud.sts.providers",
35
+ )
36
+
37
+ # Default session identifiers applied in the driver layer so every provider
38
+ # receives a non-empty, uniform session name regardless of provider support.
39
+ _DEFAULT_SESSION_NAME = "multicloud-session"
40
+ _DEFAULT_WEB_IDENTITY_SESSION_NAME = "multicloud-web-identity"
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class AvailabilityCondition:
45
+ """Condition that must be met for a ScopeRule to apply.
46
+
47
+ Currently supports prefix-based resource restriction.
48
+ """
49
+
50
+ resource_prefix: Optional[str] = None
51
+ title: Optional[str] = None
52
+ description: Optional[str] = None
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class ScopeRule:
57
+ """A single resource + permissions entry within a CredentialScope.
58
+
59
+ Attributes:
60
+ available_resource: URI of the resource.
61
+ available_permissions: Tuple of permission strings granted on the resource.
62
+ availability_condition: Optional condition to further narrow access.
63
+ """
64
+
65
+ available_resource: str
66
+ available_permissions: tuple[str, ...]
67
+ availability_condition: Optional[AvailabilityCondition] = None
68
+
69
+ def __post_init__(self) -> None:
70
+ object.__setattr__(
71
+ self, "available_permissions", tuple(self.available_permissions)
72
+ )
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class CredentialScope:
77
+ """Used with assume_role to downscope credentials.
78
+
79
+ Empty rules means no restrictions applied.
80
+ """
81
+
82
+ rules: tuple[ScopeRule, ...] = ()
83
+
84
+ def __post_init__(self) -> None:
85
+ object.__setattr__(self, "rules", tuple(self.rules))
86
+
87
+
88
+ # StsCredentials is defined in multicloud.common.credentials and re-exported
89
+ # here for backward compatibility.
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class CallerIdentity:
94
+ """Cloud-agnostic caller identity.
95
+
96
+ - ``user_id``: unique identifier of the calling entity
97
+ - ``cloud_resource_name``: cloud resource identifier or identity proof
98
+ - ``account_id``: cloud account/project that owns the identity
99
+ """
100
+
101
+ user_id: str = ""
102
+ cloud_resource_name: str = ""
103
+ account_id: str = ""
104
+
105
+
106
+ # CredentialsOverrider and CredentialsType are defined in
107
+ # multicloud.common.credentials and re-exported here for backward
108
+ # compatibility.
109
+
110
+
111
+ class StsValidator:
112
+ """Input validator; raises :class:`InvalidArgumentException`."""
113
+
114
+ def validate_assume_role(
115
+ self,
116
+ role: str,
117
+ expiration: int,
118
+ credential_scope: Optional[CredentialScope] = None,
119
+ ) -> None:
120
+ if not role:
121
+ raise InvalidArgumentException("assume_role: role is required")
122
+ if expiration <= 0:
123
+ raise InvalidArgumentException("assume_role: expiration must be positive")
124
+ if credential_scope is not None:
125
+ for rule in credential_scope.rules:
126
+ if not rule.available_permissions:
127
+ raise InvalidArgumentException(
128
+ "ScopeRule.available_permissions must not be empty"
129
+ )
130
+
131
+ def validate_get_access_token(
132
+ self,
133
+ audience: Optional[str],
134
+ scopes: Optional[list[str]],
135
+ ) -> None:
136
+ if audience is not None and scopes is not None:
137
+ raise InvalidArgumentException(
138
+ "get_access_token: audience and scopes are mutually exclusive"
139
+ )
140
+
141
+ def validate_generate_service_account_token(
142
+ self, target_principal: str, scopes: list[str]
143
+ ) -> None:
144
+ if not target_principal:
145
+ raise InvalidArgumentException(
146
+ "generate_service_account_token: target_principal is required"
147
+ )
148
+ if not scopes:
149
+ raise InvalidArgumentException(
150
+ "generate_service_account_token: scopes must be non-empty"
151
+ )
152
+
153
+ def validate_assume_role_with_web_identity(
154
+ self, role: str, web_identity_token: str
155
+ ) -> None:
156
+ # Note: expiration is intentionally not validated here. Providers
157
+ # either ignore it or enforce their own bounds, surfacing an
158
+ # out-of-range value as a provider error mapped to
159
+ # InvalidArgumentException. A blanket ``> 0`` check would be arbitrary.
160
+ if not role:
161
+ raise InvalidArgumentException(
162
+ "assume_role_with_web_identity: role is required"
163
+ )
164
+ if not web_identity_token:
165
+ raise InvalidArgumentException(
166
+ "assume_role_with_web_identity: web_identity_token is required"
167
+ )
168
+
169
+
170
+ class BaseSts(Provider, ABC):
171
+ """Base class for substrate-specific STS implementations.
172
+
173
+ Providers extend this class and implement :meth:`do_get_caller_identity`,
174
+ :meth:`do_assume_role`, :meth:`do_get_access_token`, and
175
+ :meth:`do_generate_service_account_token`.
176
+ All cross-cutting concerns (validation, default arg handling) happen in
177
+ the public methods so providers don't have to repeat them.
178
+ """
179
+
180
+ def __init__(
181
+ self,
182
+ region: Optional[str] = None,
183
+ *,
184
+ endpoint_url: Optional[str] = None,
185
+ credentials_overrider: Optional[CredentialsOverrider] = None,
186
+ validator: Optional[StsValidator] = None,
187
+ ) -> None:
188
+ self._region = region
189
+ self._endpoint_url = endpoint_url
190
+ self._credentials_overrider = credentials_overrider
191
+ self._validator = validator or StsValidator()
192
+
193
+ # properties
194
+ @property
195
+ def region(self) -> Optional[str]:
196
+ return self._region
197
+
198
+ # public API
199
+ def get_caller_identity(self, *, aud: Optional[str] = None) -> CallerIdentity:
200
+ """Return identity info for the current credentials.
201
+
202
+ Args:
203
+ aud: Target audience for the identity token. Some providers
204
+ use this for audience-scoped token generation; others
205
+ ignore it.
206
+ """
207
+ return self.do_get_caller_identity(aud=aud)
208
+
209
+ def assume_role(
210
+ self,
211
+ role: str,
212
+ *,
213
+ session_name: str = "",
214
+ expiration: int = 3600,
215
+ external_id: Optional[str] = None,
216
+ policy: Optional[str] = None,
217
+ tags: Optional[Mapping[str, str]] = None,
218
+ credential_scope: Optional[CredentialScope] = None,
219
+ ) -> StsCredentials:
220
+ """Assume a role and return temporary credentials.
221
+
222
+ Args:
223
+ role: Cloud resource name to assume.
224
+ session_name: Session identifier.
225
+ expiration: Duration in seconds (default 3600).
226
+ external_id: External ID for cross-account access (optional).
227
+ policy: Inline policy to scope down permissions (optional).
228
+ tags: Session tags (optional).
229
+ credential_scope: Optional scope to downscope credentials.
230
+
231
+ Returns:
232
+ StsCredentials with temporary access tokens.
233
+ """
234
+ self._validator.validate_assume_role(role, expiration, credential_scope)
235
+ return self.do_assume_role(
236
+ role=role,
237
+ session_name=session_name or _DEFAULT_SESSION_NAME,
238
+ expiration=expiration,
239
+ external_id=external_id,
240
+ policy=policy,
241
+ tags=tags or {},
242
+ credential_scope=credential_scope,
243
+ )
244
+
245
+ def get_access_token(
246
+ self,
247
+ *,
248
+ audience: Optional[str] = None,
249
+ scopes: Optional[list[str]] = None,
250
+ duration_seconds: Optional[int] = None,
251
+ ) -> StsCredentials:
252
+ """Retrieve a fresh access token from the provider.
253
+
254
+ Args:
255
+ audience: Target audience for an audience-scoped token.
256
+ Interpreted per provider; see the provider implementation
257
+ for details. Mutually exclusive with ``scopes``.
258
+ scopes: OAuth scopes for a scoped token. Interpreted per
259
+ provider; see the provider implementation for details.
260
+ Mutually exclusive with ``audience``.
261
+ duration_seconds: Requested token duration. Interpreted per
262
+ provider; some providers may ignore or cap this value
263
+ (optional).
264
+
265
+ Returns:
266
+ StsCredentials with the token in ``security_token``.
267
+ """
268
+ self._validator.validate_get_access_token(audience, scopes)
269
+ return self.do_get_access_token(
270
+ audience=audience, scopes=scopes, duration_seconds=duration_seconds
271
+ )
272
+
273
+ def generate_service_account_token(
274
+ self,
275
+ target_principal: str,
276
+ *,
277
+ scopes: list[str],
278
+ lifetime: int = 3600,
279
+ ) -> StsCredentials:
280
+ """Generate a token for a target service account via impersonation.
281
+
282
+ Behaviour, required permissions, and supported lifetime range are
283
+ provider-specific; see the provider ``do_generate_service_account_token``
284
+ implementation for details.
285
+
286
+ Args:
287
+ target_principal: Service account to impersonate. Format is
288
+ interpreted per provider; see the provider implementation
289
+ for details.
290
+ scopes: OAuth scopes to request on the generated token.
291
+ lifetime: Token lifetime in seconds (default 3600). Supported
292
+ range and behaviour are provider-specific; see the provider
293
+ implementation for details.
294
+
295
+ Returns:
296
+ StsCredentials with the impersonated token in ``security_token``.
297
+ """
298
+ self._validator.validate_generate_service_account_token(
299
+ target_principal, scopes
300
+ )
301
+ return self.do_generate_service_account_token(
302
+ target_principal, scopes=scopes, lifetime=lifetime
303
+ )
304
+
305
+ def assume_role_with_web_identity(
306
+ self,
307
+ role: str,
308
+ web_identity_token: str,
309
+ *,
310
+ session_name: str = "",
311
+ expiration: int = 3600,
312
+ ) -> StsCredentials:
313
+ """Exchange a web identity (OIDC) token for temporary credentials.
314
+
315
+ Federated sign-in: the caller presents an OIDC/JWT token minted by
316
+ an external identity provider and receives short-lived cloud
317
+ credentials in return — no long-lived cloud keys required.
318
+
319
+ Args:
320
+ role: Cloud resource name to assume, interpreted by each
321
+ provider as its federated-identity resource identifier.
322
+ web_identity_token: The OIDC/JWT token proving the caller's
323
+ external identity.
324
+ session_name: Session identifier (optional; provider may ignore).
325
+ expiration: Requested duration in seconds (default 3600).
326
+ Interpreted per provider; some providers may honor, cap,
327
+ or ignore it.
328
+
329
+ Returns:
330
+ StsCredentials with temporary access tokens.
331
+ """
332
+ self._validator.validate_assume_role_with_web_identity(role, web_identity_token)
333
+ return self.do_assume_role_with_web_identity(
334
+ role=role,
335
+ web_identity_token=web_identity_token,
336
+ session_name=session_name or _DEFAULT_WEB_IDENTITY_SESSION_NAME,
337
+ expiration=expiration,
338
+ )
339
+
340
+ # extension points (substrate-specific)
341
+ @abstractmethod
342
+ def do_get_caller_identity(self, *, aud: Optional[str] = None) -> CallerIdentity:
343
+ """Provider-specific implementation of ``get_caller_identity``."""
344
+
345
+ @abstractmethod
346
+ def do_assume_role(
347
+ self,
348
+ role: str,
349
+ *,
350
+ session_name: str,
351
+ expiration: int,
352
+ external_id: Optional[str],
353
+ policy: Optional[str],
354
+ tags: Mapping[str, str],
355
+ credential_scope: Optional[CredentialScope],
356
+ ) -> StsCredentials:
357
+ """Provider-specific implementation of ``assume_role``."""
358
+
359
+ @abstractmethod
360
+ def do_get_access_token(
361
+ self,
362
+ *,
363
+ audience: Optional[str] = None,
364
+ scopes: Optional[list[str]] = None,
365
+ duration_seconds: Optional[int] = None,
366
+ ) -> StsCredentials:
367
+ """Provider-specific implementation of ``get_access_token``."""
368
+
369
+ @abstractmethod
370
+ def do_generate_service_account_token(
371
+ self,
372
+ target_principal: str,
373
+ *,
374
+ scopes: list[str],
375
+ lifetime: int,
376
+ ) -> StsCredentials:
377
+ """Provider-specific implementation of ``generate_service_account_token``."""
378
+
379
+ @abstractmethod
380
+ def do_assume_role_with_web_identity(
381
+ self,
382
+ role: str,
383
+ web_identity_token: str,
384
+ *,
385
+ session_name: str,
386
+ expiration: int,
387
+ ) -> StsCredentials:
388
+ """Provider-specific implementation of ``assume_role_with_web_identity``."""
389
+
390
+ # lifecycle
391
+ def close(self) -> None:
392
+ """Release underlying resources. Default is a no-op."""
393
+
394
+ def __enter__(self) -> "BaseSts":
395
+ return self
396
+
397
+ def __exit__(self, exc_type, exc, tb) -> None: # noqa: D401
398
+ self.close()
@@ -0,0 +1,137 @@
1
+ """Driver-level abstractions for STS utility functions.
2
+
3
+ Offline signing helpers built on the Security Token Service. Unlike the
4
+ :class:`~multicloud.sts.sts_client.driver.BaseSts` operations, these do
5
+ not issue the identity request themselves — they produce a
6
+ signed-but-unsent identity request that the caller hands to another
7
+ system (e.g. an identity broker), which replays it to the provider to
8
+ verify the caller's identity. Resolving the signing credentials may
9
+ itself require a network call.
10
+
11
+ Same ABC + template-method shape as ``BaseSts``: providers implement the
12
+ ``do_*`` hook; the public ``create_signed_auth_request`` method on
13
+ :class:`BaseStsUtilities` normalizes input then delegates.
14
+
15
+ Users never reach this layer directly — they construct an
16
+ :class:`~multicloud.sts.sts_client.client.StsUtilities` (in
17
+ ``client.py``), which holds a ``BaseStsUtilities`` instance internally.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from abc import ABC, abstractmethod
23
+ from dataclasses import dataclass
24
+ from typing import Mapping, Optional
25
+
26
+ from multicloud.common.credentials import CredentialsOverrider, StsCredentials
27
+ from multicloud.common.provider import Provider, ProviderRegistry
28
+
29
+ # Utility-scoped registry. It shares the ``multicloud.sts.providers``
30
+ # entry-point group with ``STS_REGISTRY`` so a single provider-package
31
+ # import registers both the STS driver and its utility counterpart.
32
+ STS_UTILITIES_REGISTRY = ProviderRegistry(
33
+ service_name="sts-utilities",
34
+ entry_point_group="multicloud.sts.providers",
35
+ )
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class SignedAuthRequest:
40
+ """A signed-but-unsent identity request.
41
+
42
+ Produced by :meth:`BaseStsUtilities.create_signed_auth_request`. The
43
+ caller forwards the request itself — ``method``, ``url``, ``headers``,
44
+ and ``body`` — to an identity broker, which replays it to the provider
45
+ to prove the caller's identity.
46
+
47
+ Security: this is a **replayable identity proof** — the signed ``headers``
48
+ (and any session token on ``credentials``) let anyone holding them
49
+ impersonate the signer until the signature expires. Treat it as a secret:
50
+ ``__repr__`` redacts the sensitive parts, but ``dataclasses.asdict`` and
51
+ direct field access do not.
52
+
53
+ - ``method``: HTTP method of the signed request
54
+ - ``url``: fully-qualified request URL
55
+ - ``headers``: signed request headers; redacted in ``repr``
56
+ - ``body``: request body bytes
57
+ - ``credentials``: non-secret signer identity (key id + session token);
58
+ the long-term signing secret is omitted
59
+ """
60
+
61
+ method: str
62
+ url: str
63
+ headers: Mapping[str, str]
64
+ body: bytes
65
+ credentials: StsCredentials
66
+
67
+ def __repr__(self) -> str:
68
+ # Redact the signed headers (a replayable identity proof) so accidental
69
+ # logging can't leak them; ``credentials`` masks its own secrets.
70
+ return (
71
+ f"SignedAuthRequest(method={self.method!r}, url={self.url!r}, "
72
+ f"headers=<{len(self.headers)} signed headers; redacted>, "
73
+ f"body=<{len(self.body)} bytes>, credentials={self.credentials!r})"
74
+ )
75
+
76
+
77
+ class BaseStsUtilities(Provider, ABC):
78
+ """Base class for substrate-specific STS utility implementations.
79
+
80
+ Providers extend this class and implement
81
+ :meth:`do_create_signed_auth_request`. Cross-cutting concerns
82
+ (argument normalization) happen in the public method so providers
83
+ don't have to repeat them.
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ region: Optional[str] = None,
89
+ *,
90
+ credentials_overrider: Optional[CredentialsOverrider] = None,
91
+ ) -> None:
92
+ self._region = region
93
+ self._credentials_overrider = credentials_overrider
94
+
95
+ # properties
96
+ @property
97
+ def region(self) -> Optional[str]:
98
+ return self._region
99
+
100
+ # public API
101
+ def create_signed_auth_request(
102
+ self,
103
+ *,
104
+ custom_headers: Optional[Mapping[str, str]] = None,
105
+ ) -> SignedAuthRequest:
106
+ """Produce a signed identity request for cloud-native auth.
107
+
108
+ Args:
109
+ custom_headers: Extra headers to fold into the signature so the
110
+ broker replaying the request can bind them to the identity.
111
+
112
+ Returns:
113
+ SignedAuthRequest with the signed method, url, headers, body,
114
+ and the credentials used to sign it.
115
+ """
116
+ return self.do_create_signed_auth_request(
117
+ custom_headers=dict(custom_headers or {})
118
+ )
119
+
120
+ # extension point (substrate-specific)
121
+ @abstractmethod
122
+ def do_create_signed_auth_request(
123
+ self,
124
+ *,
125
+ custom_headers: Mapping[str, str],
126
+ ) -> SignedAuthRequest:
127
+ """Provider-specific implementation of ``create_signed_auth_request``."""
128
+
129
+ # lifecycle
130
+ def close(self) -> None:
131
+ """Release underlying resources. Default is a no-op."""
132
+
133
+ def __enter__(self) -> "BaseStsUtilities":
134
+ return self
135
+
136
+ def __exit__(self, exc_type, exc, tb) -> None:
137
+ self.close()
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.4
2
+ Name: multicloud-py-sts
3
+ Version: 0.1.6
4
+ Summary: Cloud-agnostic Security Token Service client for the python-multicloud SDK. Pair with a provider package (multicloud-sts-aws / -gcp / -alibaba) for actual cloud calls.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/salesforce/multicloud-py
7
+ Project-URL: Repository, https://github.com/salesforce/multicloud-py
8
+ Project-URL: Issues, https://github.com/salesforce/multicloud-py/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE.txt
14
+ Requires-Dist: multicloud-py-common>=0.1.6
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
17
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
18
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ MultiCloud Python SDK package.
@@ -0,0 +1,11 @@
1
+ LICENSE.txt
2
+ pyproject.toml
3
+ multicloud/sts/sts_client/__init__.py
4
+ multicloud/sts/sts_client/client.py
5
+ multicloud/sts/sts_client/driver.py
6
+ multicloud/sts/sts_client/utilities.py
7
+ multicloud_py_sts.egg-info/PKG-INFO
8
+ multicloud_py_sts.egg-info/SOURCES.txt
9
+ multicloud_py_sts.egg-info/dependency_links.txt
10
+ multicloud_py_sts.egg-info/requires.txt
11
+ multicloud_py_sts.egg-info/top_level.txt
@@ -0,0 +1,6 @@
1
+ multicloud-py-common>=0.1.6
2
+
3
+ [dev]
4
+ pytest>=7.0.0
5
+ pytest-cov>=4.0.0
6
+ mypy>=1.0.0
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "multicloud-py-sts"
7
+ version = "0.1.6"
8
+ license = "Apache-2.0"
9
+ description = "Cloud-agnostic Security Token Service client for the python-multicloud SDK. Pair with a provider package (multicloud-sts-aws / -gcp / -alibaba) for actual cloud calls."
10
+ readme = {text = "MultiCloud Python SDK package.", content-type = "text/markdown"}
11
+ requires-python = ">=3.10"
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "Operating System :: OS Independent",
15
+ ]
16
+ dependencies = [
17
+ "multicloud-py-common>=0.1.6",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/salesforce/multicloud-py"
22
+ Repository = "https://github.com/salesforce/multicloud-py"
23
+ Issues = "https://github.com/salesforce/multicloud-py/issues"
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest>=7.0.0", "pytest-cov>=4.0.0", "mypy>=1.0.0"]
27
+
28
+ [tool.setuptools]
29
+ license-files = ["LICENSE.txt"]
30
+
31
+ [tool.setuptools.packages.find]
32
+ include = ["multicloud*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+