-
Notifications
You must be signed in to change notification settings - Fork 31
Add modular credential chain for AWS identity resolution #749
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| { | ||
| "type": "feature", | ||
| "description": "Added a modular credential chain for AWS identity resolution. `IdentityChain.create()` discovers installed chain providers via entry points, orders them by precedence, and assembles a resolver chain. Initially ships with the Environment, SharedConfig, ProfileSessionKeys, and ProfileStaticKeys providers." | ||
| } |
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,228 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| import logging | ||
| from collections.abc import Callable, Mapping, Sequence | ||
| from importlib import metadata | ||
| from typing import Any, cast | ||
|
|
||
| from smithy_core.aio.interfaces.identity import IdentityResolver | ||
| from smithy_core.exceptions import SmithyIdentityError | ||
| from smithy_core.interfaces.identity import Identity | ||
|
|
||
| from ...config.merged_config import MergedConfig | ||
| from .exceptions import ( | ||
| IdentityChainConfigurationError, | ||
| IdentityChainError, | ||
| IdentityResolverFailure, | ||
| UnclaimedSource, | ||
| ) | ||
| from .ordering import ( | ||
| After, | ||
| Before, | ||
| OrderingConstraint, | ||
| Standard, | ||
| StandardProvider, | ||
| ) | ||
| from .provider import ( | ||
| ChainIdentityProvider, | ||
| ChainSetup, | ||
| NamedResolver, | ||
| ) | ||
|
|
||
| __all__ = ( | ||
| "After", | ||
| "Before", | ||
| "ChainIdentityProvider", | ||
| "ChainSetup", | ||
| "IdentityChain", | ||
| "IdentityChainConfigurationError", | ||
| "IdentityChainError", | ||
| "IdentityResolverFailure", | ||
| "OrderingConstraint", | ||
| "Standard", | ||
| "StandardProvider", | ||
| "UnclaimedSource", | ||
| ) | ||
|
|
||
| _CHAIN_PROVIDER_ENTRY_POINT_GROUP = "smithy_aws_core.identity.chain_providers" | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _discover_chain_identity_providers() -> tuple[ChainIdentityProvider, ...]: | ||
| discovered: list[ChainIdentityProvider] = [] | ||
| for entry_point in metadata.entry_points(group=_CHAIN_PROVIDER_ENTRY_POINT_GROUP): | ||
| provider_factory = cast( | ||
| Callable[[], ChainIdentityProvider], | ||
| entry_point.load(), | ||
| ) | ||
| discovered.append(provider_factory()) | ||
| return tuple(discovered) | ||
|
|
||
|
|
||
| def _sort_by_ordering( | ||
| providers: Sequence[ChainIdentityProvider], | ||
| ) -> tuple[ChainIdentityProvider, ...]: | ||
| if not providers: | ||
| return () | ||
| slot_indexes = {slot: index for index, slot in enumerate(StandardProvider)} | ||
|
|
||
| def sort_key( | ||
| indexed_provider: tuple[int, ChainIdentityProvider], | ||
| ) -> tuple[int, int, int]: | ||
| discovery_index, provider = indexed_provider | ||
| ordering = provider.ordering | ||
|
|
||
| match ordering: | ||
| case Before(): | ||
| constraint_precedence = 0 | ||
| case Standard(): | ||
| constraint_precedence = 1 | ||
| case After(): | ||
| constraint_precedence = 2 | ||
| case _: | ||
| raise IdentityChainConfigurationError( | ||
| f"Provider {type(provider).__name__} returned an unsupported " | ||
| f"ordering constraint: {ordering!r}." | ||
| ) | ||
|
|
||
| # Slot precedence, constraint precedence, then discovery order | ||
| return (slot_indexes[ordering.slot], constraint_precedence, discovery_index) | ||
|
|
||
| indexed_providers = enumerate(providers) | ||
| ordered_providers = sorted(indexed_providers, key=sort_key) | ||
| return tuple(provider for _, provider in ordered_providers) | ||
|
|
||
|
|
||
| def _validate_providers(providers: Sequence[ChainIdentityProvider]) -> None: | ||
| discovered_names: dict[str, ChainIdentityProvider] = {} | ||
| discovered_standard_slots: dict[StandardProvider, ChainIdentityProvider] = {} | ||
|
|
||
| for provider in providers: | ||
| if (previous := discovered_names.get(provider.name)) is not None: | ||
| raise IdentityChainConfigurationError( | ||
| f"Credential providers {type(previous).__name__} and " | ||
| f"{type(provider).__name__} use the same name: {provider.name}." | ||
| ) | ||
| discovered_names[provider.name] = provider | ||
|
|
||
| ordering = provider.ordering | ||
| if isinstance(ordering, Standard): | ||
| if (previous := discovered_standard_slots.get(ordering.slot)) is not None: | ||
| raise IdentityChainConfigurationError( | ||
| f"Credential providers {type(previous).__name__} and " | ||
| f"{type(provider).__name__} both claim standard slot: " | ||
| f"{ordering.slot.name}." | ||
| ) | ||
| discovered_standard_slots[ordering.slot] = provider | ||
|
|
||
|
|
||
| def _find_unclaimed_sources( | ||
| providers: Sequence[ChainIdentityProvider], | ||
| ) -> tuple[UnclaimedSource, ...]: | ||
| claimed_slots = { | ||
| provider.ordering.slot | ||
| for provider in providers | ||
| if isinstance(provider.ordering, Standard) | ||
| } | ||
| unclaimed_sources: list[UnclaimedSource] = [] | ||
|
|
||
| for slot in StandardProvider: | ||
| if slot in claimed_slots or not slot.is_detected(): | ||
| continue | ||
| package = slot.module_suggestion | ||
| if package: | ||
| unclaimed_sources.append( | ||
| UnclaimedSource(source_name=slot.canonical_name, package=package) | ||
| ) | ||
|
|
||
| return tuple(unclaimed_sources) | ||
|
|
||
|
|
||
| class IdentityChain[I: Identity](IdentityResolver[I, Mapping[str, Any]]): | ||
| """Resolves identities from an assembled sequence of resolvers.""" | ||
|
|
||
| _resolvers: tuple[IdentityResolver[I, Any], ...] | ||
| _identity_type: type[I] | None | ||
| _unclaimed_sources: tuple[UnclaimedSource, ...] | ||
|
|
||
| def __init__( | ||
| self, | ||
| resolvers: Sequence[IdentityResolver[I, Any]], | ||
| *, | ||
| identity_type: type[I] | None = None, | ||
| unclaimed_sources: Sequence[UnclaimedSource] = (), | ||
| ) -> None: | ||
| """Initialize the chain with resolvers in precedence order. | ||
|
|
||
| :param resolvers: Identity resolvers to iterate in precedence order. | ||
| :param identity_type: The identity type this chain resolves, or None when | ||
| constructing a chain directly without declaring one. | ||
| :param unclaimed_sources: Detected-but-unclaimed sources discovered during | ||
| chain assembly. This parameter is used by :meth:`create`; omit it when | ||
| constructing a chain directly. | ||
| """ | ||
| self._resolvers = tuple(resolvers) | ||
| self._identity_type = identity_type | ||
| self._unclaimed_sources = tuple(unclaimed_sources) | ||
|
|
||
| @property | ||
| def identity_type(self) -> type[I] | None: | ||
| """The identity type this chain resolves, or None if not declared.""" | ||
| return self._identity_type | ||
|
|
||
| @staticmethod | ||
| async def create[ChainIdentity: Identity]( | ||
| identity_type: type[ChainIdentity], | ||
| *, | ||
| profile_file: MergedConfig | None = None, | ||
| profile_name_override: str | None = None, | ||
| ) -> "IdentityChain[ChainIdentity]": | ||
| """Create an identity chain from discovered providers.""" | ||
| discovered_providers = _discover_chain_identity_providers() | ||
| _validate_providers(discovered_providers) | ||
| providers = _sort_by_ordering(discovered_providers) | ||
| setup = ChainSetup( | ||
| profile_file=profile_file, | ||
| profile_name_override=profile_name_override, | ||
| ) | ||
| unclaimed_sources = _find_unclaimed_sources(discovered_providers) | ||
|
|
||
| for provider in providers: | ||
| setup.set_current_provider(provider) | ||
| await provider.setup(identity_type, setup) | ||
| if setup.terminal: | ||
| break | ||
|
|
||
| for source in unclaimed_sources: | ||
| logger.warning(str(source)) | ||
| return IdentityChain( | ||
| setup.resolvers, | ||
| identity_type=identity_type, | ||
| unclaimed_sources=unclaimed_sources, | ||
| ) | ||
|
|
||
| async def get_identity(self, *, properties: Mapping[str, Any]) -> I: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit - Can we make properties optional and default to (smithy-python) $ python -m asyncio
asyncio REPL 3.12.6 (main, Sep 24 2024, 21:09:37) [Clang 16.0.0 (clang-1600.0.26.3)] on darwin
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> from smithy_aws_core.identity.chain import IdentityChain
>>> from smithy_aws_core.identity.components import AWSCredentialsIdentity
>>> chain = await IdentityChain.create(AWSCredentialsIdentity)
>>> await chain.get_identity(properties={})
AWSCredentialsIdentity(access_key_id='...', secret_access_key='.', session_token=None, expiration=None, account_id=None)
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. After offline discussion, we can do this as a follow up to allow for a more thorough investigation on whether we do this at the base Either way, this is a two-way door. We can always make it optional for |
||
| """Return the first identity resolved by the chain.""" | ||
| failures: list[IdentityResolverFailure] = [] | ||
| for resolver in self._resolvers: | ||
| try: | ||
| return await resolver.get_identity(properties=properties) | ||
| except SmithyIdentityError as error: | ||
| if isinstance(resolver, NamedResolver): | ||
| provider_name = resolver.provider_name | ||
| failed_resolver = resolver.resolver | ||
| else: | ||
| provider_name = type(resolver).__name__ | ||
| failed_resolver = resolver | ||
| failures.append( | ||
| IdentityResolverFailure( | ||
| provider_name=provider_name, | ||
| resolver=failed_resolver, | ||
| error=error, | ||
| ) | ||
| ) | ||
|
|
||
| raise IdentityChainError( | ||
| failures=tuple(failures), | ||
| unclaimed_sources=self._unclaimed_sources, | ||
| ) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| from dataclasses import dataclass | ||
| from typing import Any | ||
|
|
||
| from smithy_core.aio.interfaces.identity import IdentityResolver | ||
| from smithy_core.exceptions import SmithyError, SmithyIdentityError | ||
|
|
||
|
|
||
| class IdentityChainConfigurationError(SmithyError): | ||
| """Raised when discovered providers violate an assembly invariant.""" | ||
|
|
||
|
|
||
| @dataclass(frozen=True, kw_only=True) | ||
| class UnclaimedSource: | ||
| """A detected credential source that no registered provider claims. | ||
|
|
||
| Carries the installable package to suggest so the caller can add the provider | ||
| that would claim the source. | ||
| """ | ||
|
|
||
| source_name: str | ||
| package: str | ||
|
|
||
| def __str__(self) -> str: | ||
| return ( | ||
| f"{self.source_name} credential source was detected but no provider " | ||
| f"claims it; install '{self.package}'." | ||
| ) | ||
|
|
||
|
|
||
| @dataclass(frozen=True, kw_only=True) | ||
| class IdentityResolverFailure: | ||
| """A failed identity resolution attempt.""" | ||
|
|
||
| provider_name: str | ||
| resolver: IdentityResolver[Any, Any] | ||
| error: SmithyIdentityError | ||
|
|
||
|
|
||
| class IdentityChainError(SmithyIdentityError): | ||
| """Raised when every resolver in an identity chain misses.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| failures: tuple[IdentityResolverFailure, ...], | ||
| unclaimed_sources: tuple[UnclaimedSource, ...] = (), | ||
| ) -> None: | ||
| self.failures = failures | ||
| self.unclaimed_sources = unclaimed_sources | ||
| if not failures: | ||
| message = "No credential providers were discovered." | ||
| else: | ||
| attempted = "; ".join( | ||
| f"{failure.provider_name}: {failure.error}" for failure in failures | ||
| ) | ||
| message = "Unable to resolve identity from any provider in the chain." | ||
| message = f"{message} Providers attempted: {attempted}." | ||
| if unclaimed_sources: | ||
| suggestions = " ".join(str(source) for source in unclaimed_sources) | ||
| message = f"{message} {suggestions}" | ||
| super().__init__(message) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don't we need to add an
invalidatemethod here? Something like:This will also require the
IdentityResolverinterface to be updated. I think we can implement a no-op as default. Then resolvers that need custom behavior can implement what they need. This does force custom resolvers to implement as well, but I think that's fine.