From b07b9249679664351887f550fbcbd9365fb6a2d4 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Tue, 17 Nov 2026 06:06:31 -0500 Subject: [PATCH 01/11] Add SSO credential provider feature IDs --- ...aws-core-enhancement-30ebc3dd61ff479d9d59f1bb6fe4b387.json | 4 ++++ .../smithy-aws-core/src/smithy_aws_core/business_metrics.py | 2 ++ 2 files changed, 6 insertions(+) create mode 100644 packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-30ebc3dd61ff479d9d59f1bb6fe4b387.json diff --git a/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-30ebc3dd61ff479d9d59f1bb6fe4b387.json b/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-30ebc3dd61ff479d9d59f1bb6fe4b387.json new file mode 100644 index 000000000..4ea5a1eaf --- /dev/null +++ b/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-30ebc3dd61ff479d9d59f1bb6fe4b387.json @@ -0,0 +1,4 @@ +{ + "type": "enhancement", + "description": "Added the `CREDENTIALS_PROFILE_SSO` and `CREDENTIALS_SSO` feature IDs for tracking IAM Identity Center (SSO) credentials in the User-Agent header." +} \ No newline at end of file diff --git a/packages/smithy-aws-core/src/smithy_aws_core/business_metrics.py b/packages/smithy-aws-core/src/smithy_aws_core/business_metrics.py index 97b8e4a37..b433e9b1c 100644 --- a/packages/smithy-aws-core/src/smithy_aws_core/business_metrics.py +++ b/packages/smithy-aws-core/src/smithy_aws_core/business_metrics.py @@ -57,6 +57,8 @@ class AwsFeatureId(StrEnum): CREDENTIALS_STS_ASSUME_ROLE_WEB_ID = "k" CREDENTIALS_PROFILE = "n" CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN = "q" # noqa: S105 + CREDENTIALS_PROFILE_SSO = "r" + CREDENTIALS_SSO = "s" CREDENTIALS_PROFILE_PROCESS = "v" CREDENTIALS_PROCESS = "w" FLEXIBLE_CHECKSUMS_REQ_MD5 = "AE" From 0fc300696b17430070b1a6ecdf07f7264e300f44 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Thu, 19 Nov 2026 23:42:28 -0500 Subject: [PATCH 02/11] Add TokenIdentity and StaticTokenResolver for bearer token auth --- ...ture-95dd3e29f84440cea31e28d6ed0d90d6.json | 4 ++ .../src/smithy_http/aio/identity/token.py | 30 ++++++++++ .../src/smithy_http/identity/__init__.py | 20 +++++++ .../src/smithy_http/identity/token.py | 29 +++++++++ .../tests/unit/aio/identity/test_token.py | 33 ++++++++++ .../tests/unit/identity/test_token.py | 60 +++++++++++++++++++ scripts/api-snapshot/api-rex.json | 15 ++++- scripts/api-snapshot/api.json | 10 +++- scripts/api-snapshot/mirrors.txt | 4 +- scripts/verifications/import-cost.json | 2 +- 10 files changed, 203 insertions(+), 4 deletions(-) create mode 100644 packages/smithy-http/.changes/next-release/smithy-http-feature-95dd3e29f84440cea31e28d6ed0d90d6.json create mode 100644 packages/smithy-http/src/smithy_http/aio/identity/token.py create mode 100644 packages/smithy-http/src/smithy_http/identity/token.py create mode 100644 packages/smithy-http/tests/unit/aio/identity/test_token.py create mode 100644 packages/smithy-http/tests/unit/identity/test_token.py diff --git a/packages/smithy-http/.changes/next-release/smithy-http-feature-95dd3e29f84440cea31e28d6ed0d90d6.json b/packages/smithy-http/.changes/next-release/smithy-http-feature-95dd3e29f84440cea31e28d6ed0d90d6.json new file mode 100644 index 000000000..404856b32 --- /dev/null +++ b/packages/smithy-http/.changes/next-release/smithy-http-feature-95dd3e29f84440cea31e28d6ed0d90d6.json @@ -0,0 +1,4 @@ +{ + "type": "feature", + "description": "Added `TokenIdentity`, `TokenIdentityProperties`, `StaticTokenResolver` and `AsyncStaticTokenResolver` for resolving bearer tokens." +} \ No newline at end of file diff --git a/packages/smithy-http/src/smithy_http/aio/identity/token.py b/packages/smithy-http/src/smithy_http/aio/identity/token.py new file mode 100644 index 000000000..ff63c66d1 --- /dev/null +++ b/packages/smithy-http/src/smithy_http/aio/identity/token.py @@ -0,0 +1,30 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from smithy_core.aio.interfaces.identity import AsyncIdentityResolver + +from ...identity import TokenIdentity, TokenIdentityProperties +from ...identity.token import StaticTokenResolver + +__all__ = [ + "AsyncStaticTokenResolver", + "TokenIdentity", + "TokenIdentityProperties", +] + + +class AsyncStaticTokenResolver( + AsyncIdentityResolver[TokenIdentity, TokenIdentityProperties] +): + """Resolves a bearer token from a fixed identity or request properties. + + The resolution is synchronous; this defers to the sync component without + awaiting. + """ + + def __init__(self, identity: TokenIdentity | None = None) -> None: + self._sync = StaticTokenResolver(identity) + + async def get_identity( + self, *, properties: TokenIdentityProperties + ) -> TokenIdentity: + return self._sync.get_identity(properties=properties) diff --git a/packages/smithy-http/src/smithy_http/identity/__init__.py b/packages/smithy-http/src/smithy_http/identity/__init__.py index 03eefd15e..cf2047d47 100644 --- a/packages/smithy-http/src/smithy_http/identity/__init__.py +++ b/packages/smithy-http/src/smithy_http/identity/__init__.py @@ -21,3 +21,23 @@ class APIKeyIdentityProperties(TypedDict, total=False): """Identity properties that may carry an explicit API key.""" api_key: str + + +@dataclass(kw_only=True) +class TokenIdentity(Identity): + """The identity for auth that uses a bearer token.""" + + token: str = field(repr=False) + """The token to add to requests. + + It is opaque to the client: never decoded or introspected. The signer only + refuses an empty one. + """ + + expiration: datetime | None = None + + +class TokenIdentityProperties(TypedDict, total=False): + """Identity properties that may carry an explicit token.""" + + token: str diff --git a/packages/smithy-http/src/smithy_http/identity/token.py b/packages/smithy-http/src/smithy_http/identity/token.py new file mode 100644 index 000000000..a50409e94 --- /dev/null +++ b/packages/smithy-http/src/smithy_http/identity/token.py @@ -0,0 +1,29 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from smithy_core.exceptions import SmithyIdentityError +from smithy_core.interfaces.identity import IdentityResolver + +from . import TokenIdentity, TokenIdentityProperties + +__all__ = [ + "StaticTokenResolver", + "TokenIdentity", + "TokenIdentityProperties", +] + + +class StaticTokenResolver(IdentityResolver[TokenIdentity, TokenIdentityProperties]): + """Resolves a bearer token from a fixed identity or request properties.""" + + def __init__(self, identity: TokenIdentity | None = None) -> None: + self._identity = identity + + def get_identity(self, *, properties: TokenIdentityProperties) -> TokenIdentity: + if self._identity is not None: + return self._identity + + if (token := properties.get("token")) is not None: + return TokenIdentity(token=token) + raise SmithyIdentityError( + "Attempted to use bearer token auth, but no token was configured." + ) diff --git a/packages/smithy-http/tests/unit/aio/identity/test_token.py b/packages/smithy-http/tests/unit/aio/identity/test_token.py new file mode 100644 index 000000000..9de64f8f4 --- /dev/null +++ b/packages/smithy-http/tests/unit/aio/identity/test_token.py @@ -0,0 +1,33 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +import pytest +from smithy_core.exceptions import SmithyIdentityError +from smithy_http.aio.identity.token import AsyncStaticTokenResolver +from smithy_http.identity import TokenIdentity + + +async def test_returns_fixed_identity() -> None: + identity = TokenIdentity(token="spam") + resolver = AsyncStaticTokenResolver(identity) + + assert await resolver.get_identity(properties={}) is identity + + +async def test_fixed_identity_wins_over_request_properties() -> None: + identity = TokenIdentity(token="spam") + resolver = AsyncStaticTokenResolver(identity) + + assert await resolver.get_identity(properties={"token": "eggs"}) is identity + + +async def test_reads_request_properties() -> None: + identity = await AsyncStaticTokenResolver().get_identity( + properties={"token": "spam"} + ) + + assert identity.token == "spam" + + +async def test_requires_token() -> None: + with pytest.raises(SmithyIdentityError): + await AsyncStaticTokenResolver().get_identity(properties={}) diff --git a/packages/smithy-http/tests/unit/identity/test_token.py b/packages/smithy-http/tests/unit/identity/test_token.py new file mode 100644 index 000000000..c58a3b377 --- /dev/null +++ b/packages/smithy-http/tests/unit/identity/test_token.py @@ -0,0 +1,60 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from datetime import UTC, datetime, timedelta, timezone + +import pytest +from smithy_core.exceptions import SmithyIdentityError +from smithy_http.identity import TokenIdentity +from smithy_http.identity.token import StaticTokenResolver + + +def test_returns_fixed_identity() -> None: + identity = TokenIdentity(token="spam") + resolver = StaticTokenResolver(identity) + + assert resolver.get_identity(properties={}) is identity + + +def test_fixed_identity_wins_over_request_properties() -> None: + identity = TokenIdentity(token="spam") + resolver = StaticTokenResolver(identity) + + assert resolver.get_identity(properties={"token": "eggs"}) is identity + + +def test_reads_request_properties() -> None: + identity = StaticTokenResolver().get_identity(properties={"token": "spam"}) + + assert identity.token == "spam" + assert identity.expiration is None + + +def test_requires_token() -> None: + with pytest.raises(SmithyIdentityError): + StaticTokenResolver().get_identity(properties={}) + + +def test_token_hidden_from_repr() -> None: + identity = TokenIdentity(token="spam") + + assert "spam" not in repr(identity) + assert "spam" not in str(identity) + + +def test_expiration_normalized_to_utc() -> None: + expiration = datetime(2026, 1, 1, 12, tzinfo=timezone(timedelta(hours=2))) + identity = TokenIdentity(token="spam", expiration=expiration) + + assert identity.expiration is not None + assert identity.expiration == datetime(2026, 1, 1, 10, tzinfo=UTC) + assert identity.expiration.tzinfo is UTC + + +def test_is_expired() -> None: + assert not TokenIdentity(token="spam").is_expired + assert not TokenIdentity( + token="spam", expiration=datetime.now(UTC) + timedelta(hours=1) + ).is_expired + assert TokenIdentity( + token="spam", expiration=datetime.now(UTC) - timedelta(hours=1) + ).is_expired diff --git a/scripts/api-snapshot/api-rex.json b/scripts/api-snapshot/api-rex.json index d5ee405dd..06443054f 100644 --- a/scripts/api-snapshot/api-rex.json +++ b/scripts/api-snapshot/api-rex.json @@ -1018,6 +1018,12 @@ "APIKeyIdentityResolver": "rex-class", "AsyncIdentityResolver": "rex-protocol[async]" }, + "smithy_http.aio.identity.token": { + "AsyncIdentityResolver": "rex-protocol[async]", + "StaticTokenResolver": "rex-class", + "TokenIdentity": "rex-class", + "TokenIdentityProperties": "rex-class" + }, "smithy_http.aio.interfaces": { "AsyncClientTransport": "rex-protocol[async]", "HTTPClientConfiguration": "rex-class", @@ -1139,7 +1145,8 @@ }, "smithy_http.identity": { "Identity": "rex-protocol", - "apikey": "rex-module" + "apikey": "rex-module", + "token": "rex-module" }, "smithy_http.identity.apikey": { "APIKeyIdentity": "rex-class", @@ -1147,6 +1154,12 @@ "IdentityResolver": "rex-protocol", "SmithyIdentityError": "rex-exception" }, + "smithy_http.identity.token": { + "IdentityResolver": "rex-protocol", + "SmithyIdentityError": "rex-exception", + "TokenIdentity": "rex-class", + "TokenIdentityProperties": "rex-class" + }, "smithy_http.interceptors": { "user_agent": "rex-module" }, diff --git a/scripts/api-snapshot/api.json b/scripts/api-snapshot/api.json index a42d81a44..b6924a475 100644 --- a/scripts/api-snapshot/api.json +++ b/scripts/api-snapshot/api.json @@ -702,6 +702,9 @@ "smithy_http.aio.identity.apikey": { "AsyncAPIKeyIdentityResolver": "class[async]" }, + "smithy_http.aio.identity.token": { + "AsyncStaticTokenResolver": "class[async]" + }, "smithy_http.aio.interfaces": { "AsyncHTTPClient": "protocol[async]" }, @@ -745,11 +748,16 @@ }, "smithy_http.identity": { "APIKeyIdentity": "class", - "APIKeyIdentityProperties": "class" + "APIKeyIdentityProperties": "class", + "TokenIdentity": "class", + "TokenIdentityProperties": "class" }, "smithy_http.identity.apikey": { "APIKeyIdentityResolver": "class" }, + "smithy_http.identity.token": { + "StaticTokenResolver": "class" + }, "smithy_http.interceptors": {}, "smithy_http.interceptors.user_agent": { "USER_AGENT": "PropertyKey", diff --git a/scripts/api-snapshot/mirrors.txt b/scripts/api-snapshot/mirrors.txt index 30a38b372..9f47e7339 100644 --- a/scripts/api-snapshot/mirrors.txt +++ b/scripts/api-snapshot/mirrors.txt @@ -85,6 +85,8 @@ Dual-mode symbols (async in aio, sync twin outside): identity/ apikey.py AsyncAPIKeyIdentityResolver APIKeyIdentityResolver + token.py + AsyncStaticTokenResolver StaticTokenResolver interfaces/ __init__.py AsyncHTTPClient HTTPClient @@ -100,4 +102,4 @@ Dual-mode symbols (async in aio, sync twin outside): http_mock.py AsyncHTTPMockController HTTPMockController mock_async mock -50 dual-mode symbol(s). +51 dual-mode symbol(s). diff --git a/scripts/verifications/import-cost.json b/scripts/verifications/import-cost.json index 0a29e2987..4b928b808 100644 --- a/scripts/verifications/import-cost.json +++ b/scripts/verifications/import-cost.json @@ -12,7 +12,7 @@ "smithy_core": 5, "smithy_core (all public modules)": 46, "smithy_http": 12, - "smithy_http (all public modules)": 92, + "smithy_http (all public modules)": 94, "smithy_json": 21, "smithy_json (all public modules)": 21, "smithy_python": 1, From c6a973ef704ebdd04e3fefef8063183702e92df8 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Fri, 20 Nov 2026 00:40:02 -0500 Subject: [PATCH 03/11] Add bearer token auth scheme, signer and codegen support --- CHANGELOG.md | 8 + .../codegen/test/PythonCodegenTest.java | 23 +++ .../it/resources/META-INF/smithy/main.smithy | 1 + .../smithy/python/codegen/RuntimeTypes.java | 4 + .../codegen/integrations/HttpBearerAuth.java | 154 +++++++++++++++++ ...hon.codegen.integrations.PythonIntegration | 1 + ...ture-1e8283b6ecaf49dd9aff2080c5f302c4.json | 4 + .../smithy-core/src/smithy_core/traits.py | 9 + .../smithy-core/tests/unit/test_traits.py | 7 + ...ture-95dd3e29f84440cea31e28d6ed0d90d6.json | 4 +- .../src/smithy_http/aio/auth/bearer.py | 55 ++++++ .../src/smithy_http/auth/bearer.py | 114 ++++++++++++ .../tests/unit/aio/auth/test_bearer.py | 43 +++++ .../tests/unit/auth/test_bearer.py | 163 ++++++++++++++++++ scripts/api-snapshot/api-rex.json | 24 ++- scripts/api-snapshot/api.json | 11 ++ scripts/api-snapshot/mirrors.txt | 5 +- scripts/verifications/import-cost.json | 2 +- 18 files changed, 627 insertions(+), 5 deletions(-) create mode 100644 codegen/core/src/main/java/software/amazon/smithy/python/codegen/integrations/HttpBearerAuth.java create mode 100644 packages/smithy-core/.changes/next-release/smithy-core-feature-1e8283b6ecaf49dd9aff2080c5f302c4.json create mode 100644 packages/smithy-http/src/smithy_http/aio/auth/bearer.py create mode 100644 packages/smithy-http/src/smithy_http/auth/bearer.py create mode 100644 packages/smithy-http/tests/unit/aio/auth/test_bearer.py create mode 100644 packages/smithy-http/tests/unit/auth/test_bearer.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 546dab812..9cc411735 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Change Log +## Unreleased + +### Features + +* Generated clients support the `smithy.api#httpBearerAuth` trait. A service that + models it gets `token` and `token_identity_resolver` configuration settings, + and its requests carry an `Authorization: Bearer` header. + ## v0.7.0 ### Breaking Changes diff --git a/codegen/core/src/it/java/software/amazon/smithy/python/codegen/test/PythonCodegenTest.java b/codegen/core/src/it/java/software/amazon/smithy/python/codegen/test/PythonCodegenTest.java index 56af6ed9f..0ad77cb6d 100644 --- a/codegen/core/src/it/java/software/amazon/smithy/python/codegen/test/PythonCodegenTest.java +++ b/codegen/core/src/it/java/software/amazon/smithy/python/codegen/test/PythonCodegenTest.java @@ -61,6 +61,25 @@ public void testCodegen(@TempDir Path tempDir) throws IOException { assertTrue(config.contains("self.transport = transport or AIOHTTPClient()")); assertFalse(config.contains("self.transport = transport or AWSCRTHTTPClient()")); + // The service models both @httpApiKeyAuth and @httpBearerAuth, so the config + // carries each scheme's identity settings and the resolver offers both. + assertTrue(config.contains("api_key: str | None")); + assertTrue(config.contains("api_key_identity_resolver or AsyncAPIKeyIdentityResolver()")); + assertTrue(config.contains("token: str | None")); + assertTrue(config.contains("token_identity_resolver or AsyncStaticTokenResolver()")); + assertTrue(config.contains("AsyncBearerAuthScheme()")); + + var auth = Files.readString(tempDir.resolve("src/weather/auth.py")); + assertTrue(auth.contains("def _generate_api_key_option(")); + assertTrue(auth.contains("def _generate_bearer_option(")); + assertTrue(auth.contains("ShapeID(\"smithy.api#httpBearerAuth\")")); + // Without an @auth trait the effective schemes are ordered by shape ID. + var apiKeyOption = auth.indexOf("_generate_api_key_option(auth_parameters)"); + var bearerOption = auth.indexOf("_generate_bearer_option(auth_parameters)"); + assertTrue(apiKeyOption >= 0); + assertTrue(bearerOption >= 0); + assertTrue(apiKeyOption < bearerOption); + var syncClient = Files.readString(tempDir.resolve("src/weather/client.py")); assertTrue(syncClient.contains("class Weather(Client[Config]):")); assertTrue(syncClient.contains("return self._invoke(")); @@ -187,6 +206,9 @@ async def stream_atmospheric_conditions( var syncConfig = Files.readString(tempDir.resolve("src/weather/config.py")); assertTrue(syncConfig.contains("self.transport = transport or Urllib3HTTPClient()")); + // The sync config maps the bearer scheme and resolver to their sync twins. + assertTrue(syncConfig.contains("token_identity_resolver or StaticTokenResolver()")); + assertTrue(syncConfig.contains("BearerAuthScheme()")); // An output that models a "responseMetadata" member gets both the SDK-reserved // response_metadata attribute and the escaped modeled member, so neither shadows @@ -331,6 +353,7 @@ def upload_city_image( assertTrue(schemas.contains("aws.protocols#restJson1")); assertTrue(schemas.contains("smithy.api#httpApiKeyAuth")); assertTrue(schemas.contains("\"name\": \"weather-auth\"")); + assertTrue(schemas.contains("smithy.api#httpBearerAuth")); // Lowering consumes the endpoint rules; the schemas no longer carry them. assertFalse(schemas.contains("smithy.rules#endpointBdd")); diff --git a/codegen/core/src/it/resources/META-INF/smithy/main.smithy b/codegen/core/src/it/resources/META-INF/smithy/main.smithy index 2b86fb4b0..3b862f91b 100644 --- a/codegen/core/src/it/resources/META-INF/smithy/main.smithy +++ b/codegen/core/src/it/resources/META-INF/smithy/main.smithy @@ -15,6 +15,7 @@ use smithy.waiters#waitable @fakeProtocol @paginated(inputToken: "nextToken", outputToken: "nextToken", pageSize: "pageSize") @httpApiKeyAuth(name: "weather-auth", in: "header") +@httpBearerAuth service Weather { version: "2006-03-01" resources: [ diff --git a/codegen/core/src/main/java/software/amazon/smithy/python/codegen/RuntimeTypes.java b/codegen/core/src/main/java/software/amazon/smithy/python/codegen/RuntimeTypes.java index 4ef300574..9e932a443 100644 --- a/codegen/core/src/main/java/software/amazon/smithy/python/codegen/RuntimeTypes.java +++ b/codegen/core/src/main/java/software/amazon/smithy/python/codegen/RuntimeTypes.java @@ -183,6 +183,10 @@ public final class RuntimeTypes { public static final Symbol API_KEY_IDENTITY_RESOLVER = createSymbol("aio.identity.apikey", "AsyncAPIKeyIdentityResolver", SmithyPythonDependency.SMITHY_HTTP); + // smithy_http.aio.identity.token + public static final Symbol STATIC_TOKEN_RESOLVER = + createSymbol("aio.identity.token", "AsyncStaticTokenResolver", SmithyPythonDependency.SMITHY_HTTP); + // smithy_aws_core.aio.protocols public static final Symbol REST_JSON_CLIENT_PROTOCOL = createSymbol( "aio.protocols", diff --git a/codegen/core/src/main/java/software/amazon/smithy/python/codegen/integrations/HttpBearerAuth.java b/codegen/core/src/main/java/software/amazon/smithy/python/codegen/integrations/HttpBearerAuth.java new file mode 100644 index 000000000..36c68ea96 --- /dev/null +++ b/codegen/core/src/main/java/software/amazon/smithy/python/codegen/integrations/HttpBearerAuth.java @@ -0,0 +1,154 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package software.amazon.smithy.python.codegen.integrations; + +import java.util.List; +import software.amazon.smithy.codegen.core.Symbol; +import software.amazon.smithy.model.shapes.ServiceShape; +import software.amazon.smithy.model.shapes.ShapeId; +import software.amazon.smithy.model.traits.HttpBearerAuthTrait; +import software.amazon.smithy.python.codegen.ApplicationProtocol; +import software.amazon.smithy.python.codegen.CodegenUtils; +import software.amazon.smithy.python.codegen.ConfigProperty; +import software.amazon.smithy.python.codegen.GenerationContext; +import software.amazon.smithy.python.codegen.PythonSettings; +import software.amazon.smithy.python.codegen.RuntimeTypes; +import software.amazon.smithy.python.codegen.SmithyPythonDependency; +import software.amazon.smithy.python.codegen.writer.PythonWriter; +import software.amazon.smithy.utils.SmithyInternalApi; + +/** + * Adds support for the http bearer auth. + * {@see https://smithy.io/2.0/spec/authentication-traits.html#smithy-api-httpbearerauth-trait} + */ +@SmithyInternalApi +public final class HttpBearerAuth implements PythonIntegration { + private static final String OPTION_GENERATOR_NAME = "_generate_bearer_option"; + + @Override + public List getClientPlugins(GenerationContext context) { + return List.of( + RuntimeClientPlugin.builder() + .servicePredicate((model, service) -> service.hasTrait(HttpBearerAuthTrait.class)) + .addConfigProperty(ConfigProperty.builder() + .name("token") + .documentation("The bearer token to send along with requests.") + .type(Symbol.builder().name("str").build()) + .nullable(true) + .build()) + .addConfigProperty(ConfigProperty.builder() + .name("token_identity_resolver") + .documentation("Resolves the bearer token.") + .type(Symbol.builder() + .name("AsyncIdentityResolver[TokenIdentity, TokenIdentityProperties]") + .addReference(Symbol.builder() + .addDependency(SmithyPythonDependency.SMITHY_CORE) + .name("AsyncIdentityResolver") + .namespace("smithy_core.aio.interfaces.identity", ".") + .build()) + .addReference(Symbol.builder() + .addDependency(SmithyPythonDependency.SMITHY_HTTP) + .name("TokenIdentity") + .namespace("smithy_http.identity", ".") + .build()) + .addReference(Symbol.builder() + .addDependency(SmithyPythonDependency.SMITHY_HTTP) + .name("TokenIdentityProperties") + .namespace("smithy_http.identity", ".") + .build()) + .build()) + .initialize(writer -> { + writer.write(""" + self.token_identity_resolver = ( + token_identity_resolver or $T() + ) + """, RuntimeTypes.STATIC_TOKEN_RESOLVER); + }) + .build()) + .authScheme(new BearerAuthScheme()) + .build()); + } + + @Override + public void customize(GenerationContext context) { + if (!hasBearerAuth(context)) { + return; + } + var resolver = CodegenUtils.getHttpAuthSchemeResolverSymbol(context.settings()); + + // Add a function that generates the http auth option for bearer auth. The + // trait has no modeled parameters, so the option is static; the function is + // generated anyway so every scheme is wired into the resolver the same way. + context.writerDelegator().useFileWriter(resolver.getDefinitionFile(), resolver.getNamespace(), writer -> { + writer.addDependency(SmithyPythonDependency.SMITHY_CORE); + writer.addDependency(SmithyPythonDependency.SMITHY_HTTP); + writer.addStdlibImport("typing", "Any"); + writer.pushState(); + writer.write(""" + def $1L(auth_params: $2T[Any, Any]) -> $3T | None: + return $4T( + scheme_id=$5T($6S), + identity_properties={}, # type: ignore + signer_properties={}, # type: ignore + ) + """, + OPTION_GENERATOR_NAME, + RuntimeTypes.AUTH_PARAMS, + RuntimeTypes.AUTH_OPTION_INTERFACE, + RuntimeTypes.AUTH_OPTION, + RuntimeTypes.SHAPE_ID, + HttpBearerAuthTrait.ID.toString()); + writer.popState(); + }); + } + + private boolean hasBearerAuth(GenerationContext context) { + if (context.settings().artifactType() == PythonSettings.ArtifactType.TYPES) { + return false; + } + var service = context.settings().service(context.model()); + return service.hasTrait(HttpBearerAuthTrait.class); + } + + /** + * The AuthScheme representing bearer auth. + */ + private static final class BearerAuthScheme implements AuthScheme { + + @Override + public ShapeId getAuthTrait() { + return HttpBearerAuthTrait.ID; + } + + @Override + public ApplicationProtocol getApplicationProtocol() { + return ApplicationProtocol.createDefaultHttpApplicationProtocol(); + } + + @Override + public Symbol getAuthOptionGenerator(GenerationContext context) { + var resolver = CodegenUtils.getHttpAuthSchemeResolverSymbol(context.settings()); + return Symbol.builder() + .name(OPTION_GENERATOR_NAME) + .namespace(resolver.getNamespace(), ".") + .definitionFile(resolver.getDefinitionFile()) + .build(); + } + + @Override + public Symbol getAuthSchemeSymbol(GenerationContext context) { + return Symbol.builder() + .name("AsyncBearerAuthScheme") + .namespace("smithy_http.aio.auth.bearer", ".") + .addDependency(SmithyPythonDependency.SMITHY_HTTP) + .build(); + } + + @Override + public void initializeScheme(GenerationContext context, PythonWriter writer, ServiceShape service) { + writer.write("$T()", getAuthSchemeSymbol(context)); + } + } +} diff --git a/codegen/core/src/main/resources/META-INF/services/software.amazon.smithy.python.codegen.integrations.PythonIntegration b/codegen/core/src/main/resources/META-INF/services/software.amazon.smithy.python.codegen.integrations.PythonIntegration index 57dc01030..7a5513816 100644 --- a/codegen/core/src/main/resources/META-INF/services/software.amazon.smithy.python.codegen.integrations.PythonIntegration +++ b/codegen/core/src/main/resources/META-INF/services/software.amazon.smithy.python.codegen.integrations.PythonIntegration @@ -7,6 +7,7 @@ software.amazon.smithy.python.codegen.integrations.RestJsonIntegration software.amazon.smithy.python.codegen.integrations.Rpcv2CborIntegration software.amazon.smithy.python.codegen.integrations.Rpcv2JsonIntegration software.amazon.smithy.python.codegen.integrations.HttpApiKeyAuth +software.amazon.smithy.python.codegen.integrations.HttpBearerAuth software.amazon.smithy.python.codegen.integrations.UserAgentIntegration software.amazon.smithy.python.codegen.integrations.EndpointBddIntegration software.amazon.smithy.python.codegen.integrations.HostPrefixIntegration diff --git a/packages/smithy-core/.changes/next-release/smithy-core-feature-1e8283b6ecaf49dd9aff2080c5f302c4.json b/packages/smithy-core/.changes/next-release/smithy-core-feature-1e8283b6ecaf49dd9aff2080c5f302c4.json new file mode 100644 index 000000000..38138f2ac --- /dev/null +++ b/packages/smithy-core/.changes/next-release/smithy-core-feature-1e8283b6ecaf49dd9aff2080c5f302c4.json @@ -0,0 +1,4 @@ +{ + "type": "feature", + "description": "Added `HTTPBearerAuthTrait` for the `smithy.api#httpBearerAuth` trait." +} \ No newline at end of file diff --git a/packages/smithy-core/src/smithy_core/traits.py b/packages/smithy-core/src/smithy_core/traits.py index 8aa522bdc..95adc9d05 100644 --- a/packages/smithy-core/src/smithy_core/traits.py +++ b/packages/smithy-core/src/smithy_core/traits.py @@ -33,6 +33,7 @@ "EventHeaderTrait", "EventPayloadTrait", "HTTPAPIKeyAuthTrait", + "HTTPBearerAuthTrait", "HTTPChecksumRequiredTrait", "HTTPErrorTrait", "HTTPHeaderTrait", @@ -524,6 +525,14 @@ def scheme(self) -> str | None: return self.document_value.get("scheme") # type: ignore +@dataclass(init=False, frozen=True) +class HTTPBearerAuthTrait(Trait, id=ShapeID("smithy.api#httpBearerAuth")): + """Configures bearer token auth for a service.""" + + def __post_init__(self) -> None: + assert self.document_value is None + + @dataclass(init=False, frozen=True) class RpcV2CborTrait(Trait, id=ShapeID("smithy.protocols#rpcv2Cbor")): """The ``smithy.protocols#rpcv2Cbor`` protocol trait.""" diff --git a/packages/smithy-core/tests/unit/test_traits.py b/packages/smithy-core/tests/unit/test_traits.py index a12340569..1bff3c9de 100644 --- a/packages/smithy-core/tests/unit/test_traits.py +++ b/packages/smithy-core/tests/unit/test_traits.py @@ -12,6 +12,7 @@ DynamicTrait, ErrorFault, ErrorTrait, + HTTPBearerAuthTrait, JSONNameTrait, OperationContextParamsTrait, RpcV2CborTrait, @@ -60,6 +61,12 @@ def test_unit_schema_uses_canonical_trait_id(): assert isinstance(trait, UnitTypeTrait) +def test_trait_factory_constructs_http_bearer_auth_trait(): + trait = Trait.new(ShapeID("smithy.api#httpBearerAuth")) + assert isinstance(trait, HTTPBearerAuthTrait) + assert trait.document_value is None + + def test_cant_construct_base_trait(): with pytest.raises(TypeError): Trait("foo") diff --git a/packages/smithy-http/.changes/next-release/smithy-http-feature-95dd3e29f84440cea31e28d6ed0d90d6.json b/packages/smithy-http/.changes/next-release/smithy-http-feature-95dd3e29f84440cea31e28d6ed0d90d6.json index 404856b32..3db742942 100644 --- a/packages/smithy-http/.changes/next-release/smithy-http-feature-95dd3e29f84440cea31e28d6ed0d90d6.json +++ b/packages/smithy-http/.changes/next-release/smithy-http-feature-95dd3e29f84440cea31e28d6ed0d90d6.json @@ -1,4 +1,4 @@ { "type": "feature", - "description": "Added `TokenIdentity`, `TokenIdentityProperties`, `StaticTokenResolver` and `AsyncStaticTokenResolver` for resolving bearer tokens." -} \ No newline at end of file + "description": "Added support for `smithy.api#httpBearerAuth`: `TokenIdentity`, `TokenIdentityProperties`, `StaticTokenResolver`/`AsyncStaticTokenResolver`, `BearerAuthScheme`/`AsyncBearerAuthScheme` and `BearerSigner`. The signer only signs requests bound for `https` endpoints and rejects an empty token." +} diff --git a/packages/smithy-http/src/smithy_http/aio/auth/bearer.py b/packages/smithy-http/src/smithy_http/aio/auth/bearer.py new file mode 100644 index 000000000..3cfb25fef --- /dev/null +++ b/packages/smithy-http/src/smithy_http/aio/auth/bearer.py @@ -0,0 +1,55 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from typing import Any, Protocol + +from smithy_core.aio.interfaces.auth import AsyncAuthScheme +from smithy_core.aio.interfaces.identity import AsyncIdentityResolver +from smithy_core.interfaces import TypedProperties as _TypedProperties +from smithy_core.types import PropertyKey + +from smithy_http.interfaces import HTTPRequest + +from ...auth.bearer import ( + _BearerAuthSchemeBase, # pyright: ignore[reportPrivateUsage] +) +from ...identity import TokenIdentity, TokenIdentityProperties + +__all__ = [ + "TOKEN_RESOLVER_CONFIG", + "AsyncBearerAuthScheme", + "AsyncTokenResolverConfig", +] + + +class AsyncTokenResolverConfig(Protocol): + """A config bearing bearer token properties.""" + + token: str | None + """An explicit bearer token. + + If not set, it MAY be retrieved from elsewhere by the resolver. + """ + + token_identity_resolver: ( + AsyncIdentityResolver[TokenIdentity, TokenIdentityProperties] | None + ) + """A bearer token identity resolver. + + The default implementation only returns the explicitly configured token. + """ + + +TOKEN_RESOLVER_CONFIG = PropertyKey(key="config", value_type=AsyncTokenResolverConfig) +"""A context property bearing a bearer token config.""" + + +class AsyncBearerAuthScheme( + _BearerAuthSchemeBase, + AsyncAuthScheme[HTTPRequest, TokenIdentity, TokenIdentityProperties, Any], +): + """An auth scheme containing necessary data and tools for bearer token auth.""" + + def identity_resolver( + self, *, context: _TypedProperties + ) -> AsyncIdentityResolver[TokenIdentity, TokenIdentityProperties]: + return super().identity_resolver(context=context) diff --git a/packages/smithy-http/src/smithy_http/auth/bearer.py b/packages/smithy-http/src/smithy_http/auth/bearer.py new file mode 100644 index 000000000..d06543146 --- /dev/null +++ b/packages/smithy-http/src/smithy_http/auth/bearer.py @@ -0,0 +1,114 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from typing import Any, Protocol, Self + +from smithy_core.exceptions import SmithyIdentityError +from smithy_core.interfaces import TypedProperties as _TypedProperties +from smithy_core.interfaces.auth import AuthScheme, Signer +from smithy_core.interfaces.identity import IdentityResolver +from smithy_core.shapes import ShapeID +from smithy_core.traits import HTTPBearerAuthTrait + +from smithy_http.interfaces import HTTPRequest + +from .. import Field +from ..exceptions import SmithyHTTPError +from ..identity import TokenIdentity, TokenIdentityProperties + +__all__ = ["BearerAuthScheme", "BearerSigner", "TokenResolverConfig"] + + +class TokenResolverConfig(Protocol): + """A config bearing bearer token properties for a synchronous client.""" + + token: str | None + """An explicit bearer token. + + If not set, it MAY be retrieved from elsewhere by the resolver. + """ + + token_identity_resolver: ( + IdentityResolver[TokenIdentity, TokenIdentityProperties] | None + ) + """A bearer token identity resolver.""" + + +class BearerSigner(Signer[HTTPRequest, TokenIdentity, Any]): + """A signer that signs http requests with a bearer token. + + The token is sent in the ``Authorization`` header as defined in RFC 6750 §2.1, + replacing any value already present. + """ + + def sign( + self, + *, + request: HTTPRequest, + identity: TokenIdentity, + properties: Any, + ) -> HTTPRequest: + """Add the bearer token to the request's ``Authorization`` header. + + :raises SmithyIdentityError: If the identity's token is empty. + :raises SmithyHTTPError: If the request is not bound for an ``https`` endpoint. + RFC 6750 §5.2 requires TLS for bearer tokens. + """ + if not identity.token: + raise SmithyIdentityError("Bearer token auth requires a non-empty token.") + if request.destination.scheme.lower() != "https": + raise SmithyHTTPError( + "Bearer token auth requires an https endpoint, but the request is " + f"bound for {request.destination.scheme}://{request.destination.host}." + ) + request.fields.set_field( + Field(name="Authorization", values=[f"Bearer {identity.token}"]) + ) + return request + + +class _BearerAuthSchemeBase: + """Bearer token auth scheme logic shared by the sync and async schemes.""" + + scheme_id: ShapeID = HTTPBearerAuthTrait.id + + def __init__(self) -> None: + self._signer = BearerSigner() + + def identity_properties( + self, *, context: _TypedProperties + ) -> TokenIdentityProperties: + config = context.get("config") + if config is not None and config.token is not None: + return {"token": config.token} + return {} + + def identity_resolver(self, *, context: _TypedProperties) -> Any: + config = context.get("config") + if config is None or config.token_identity_resolver is None: + raise SmithyIdentityError( + "Attempted to use bearer token auth, but token_identity_resolver was " + "not set on the config." + ) + return config.token_identity_resolver + + def signer_properties(self, *, context: _TypedProperties) -> Any: + return {} + + def signer(self) -> BearerSigner: + return self._signer + + @classmethod + def from_trait(cls, trait: HTTPBearerAuthTrait, /) -> Self: + return cls() + + +class BearerAuthScheme( + _BearerAuthSchemeBase, + AuthScheme[HTTPRequest, TokenIdentity, TokenIdentityProperties, Any], +): + """An auth scheme containing necessary data and tools for bearer token auth.""" + + def identity_resolver( + self, *, context: _TypedProperties + ) -> IdentityResolver[TokenIdentity, TokenIdentityProperties]: + return super().identity_resolver(context=context) diff --git a/packages/smithy-http/tests/unit/aio/auth/test_bearer.py b/packages/smithy-http/tests/unit/aio/auth/test_bearer.py new file mode 100644 index 000000000..2ec584ed9 --- /dev/null +++ b/packages/smithy-http/tests/unit/aio/auth/test_bearer.py @@ -0,0 +1,43 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from dataclasses import dataclass + +import pytest +from smithy_core.aio.interfaces.identity import AsyncIdentityResolver +from smithy_core.exceptions import SmithyIdentityError +from smithy_core.types import TypedProperties +from smithy_http.aio.auth.bearer import AsyncBearerAuthScheme +from smithy_http.aio.identity.token import AsyncStaticTokenResolver +from smithy_http.identity import TokenIdentity, TokenIdentityProperties + + +@dataclass +class _Config: + token: str | None = None + token_identity_resolver: ( + AsyncIdentityResolver[TokenIdentity, TokenIdentityProperties] | None + ) = None + + +async def test_auth_scheme_gets_resolver() -> None: + resolver = AsyncStaticTokenResolver() + context = TypedProperties({"config": _Config(token_identity_resolver=resolver)}) + + assert AsyncBearerAuthScheme().identity_resolver(context=context) is resolver + + +async def test_auth_scheme_missing_resolver() -> None: + with pytest.raises(SmithyIdentityError): + AsyncBearerAuthScheme().identity_resolver(context=TypedProperties()) + + +async def test_resolves_token_end_to_end() -> None: + config = _Config(token="spam", token_identity_resolver=AsyncStaticTokenResolver()) + context = TypedProperties({"config": config}) + scheme = AsyncBearerAuthScheme() + + identity = await scheme.identity_resolver(context=context).get_identity( + properties=scheme.identity_properties(context=context) + ) + + assert identity.token == "spam" diff --git a/packages/smithy-http/tests/unit/auth/test_bearer.py b/packages/smithy-http/tests/unit/auth/test_bearer.py new file mode 100644 index 000000000..df4c611f0 --- /dev/null +++ b/packages/smithy-http/tests/unit/auth/test_bearer.py @@ -0,0 +1,163 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +from dataclasses import dataclass + +import pytest +from smithy_core import URI +from smithy_core.exceptions import SmithyIdentityError +from smithy_core.interfaces.identity import IdentityResolver +from smithy_core.traits import HTTPBearerAuthTrait +from smithy_core.types import TypedProperties +from smithy_http import Field, Fields, HTTPRequest +from smithy_http.auth.bearer import BearerAuthScheme, BearerSigner +from smithy_http.exceptions import SmithyHTTPError +from smithy_http.identity import TokenIdentity, TokenIdentityProperties +from smithy_http.identity.token import StaticTokenResolver + +DESTINATION = URI( + scheme="https", + username="user", + password="secret", + host="example.com", + port=8443, + path="/resource", + query="spam=eggs", + fragment="frag", +) + + +def _request( + destination: URI = DESTINATION, fields: Fields | None = None +) -> HTTPRequest: + return HTTPRequest( + destination=destination, body=b"", method="GET", fields=fields or Fields() + ) + + +# Tokens are opaque (RFC 6750 §2.1): dotted, base64, and any existing header is replaced. +@pytest.mark.parametrize( + "token, fields", + [ + ("mF_9.B5f-4.1JqM", None), + ("eW91J3JlIG5vdCBzdXBwb3NlZCB0byBkZWNvZGUgdGhpcyE=", None), + ( + "mF_9.B5f-4.1JqM", + Fields([Field(name="Authorization", values=["Bearer foo"])]), + ), + ], +) +def test_sign_sets_authorization_header(token: str, fields: Fields | None) -> None: + actual = BearerSigner().sign( + request=_request(fields=fields), + identity=TokenIdentity(token=token), + properties={}, + ) + + expected = _request( + fields=Fields([Field(name="Authorization", values=[f"Bearer {token}"])]) + ) + assert actual == expected + + +def test_sign_preserves_destination_and_other_fields() -> None: + fields = Fields([Field(name="X-Spam", values=["eggs"])]) + actual = BearerSigner().sign( + request=_request(fields=fields), + identity=TokenIdentity(token="token"), + properties={}, + ) + + assert actual.destination == DESTINATION + assert actual.fields["X-Spam"].values == ["eggs"] + assert actual.fields["Authorization"].values == ["Bearer token"] + + +def test_sign_accepts_uppercase_scheme() -> None: + destination = URI(scheme="HTTPS", host="example.com") + actual = BearerSigner().sign( + request=_request(destination), + identity=TokenIdentity(token="spam"), + properties={}, + ) + + assert actual.fields["Authorization"].values == ["Bearer spam"] + + +def test_sign_requires_https() -> None: + with pytest.raises(SmithyHTTPError, match="https"): + BearerSigner().sign( + request=_request(URI(scheme="http", host="example.com")), + identity=TokenIdentity(token="spam"), + properties={}, + ) + + +def test_sign_rejects_empty_token() -> None: + request = _request() + with pytest.raises(SmithyIdentityError, match="non-empty token"): + BearerSigner().sign( + request=request, identity=TokenIdentity(token=""), properties={} + ) + assert "Authorization" not in request.fields + + +@dataclass +class _Config: + token: str | None = None + token_identity_resolver: ( + IdentityResolver[TokenIdentity, TokenIdentityProperties] | None + ) = None + + +def test_scheme_id() -> None: + assert BearerAuthScheme().scheme_id == HTTPBearerAuthTrait.id + assert BearerAuthScheme.from_trait(HTTPBearerAuthTrait()).scheme_id == ( + HTTPBearerAuthTrait.id + ) + + +def test_identity_properties_from_config() -> None: + scheme = BearerAuthScheme() + context = TypedProperties({"config": _Config(token="spam")}) + + assert scheme.identity_properties(context=context) == {"token": "spam"} + + +@pytest.mark.parametrize( + "context", [TypedProperties(), TypedProperties({"config": _Config()})] +) +def test_identity_properties_without_token(context: TypedProperties) -> None: + assert BearerAuthScheme().identity_properties(context=context) == {} + + +def test_identity_resolver_from_config() -> None: + resolver = StaticTokenResolver() + context = TypedProperties({"config": _Config(token_identity_resolver=resolver)}) + + assert BearerAuthScheme().identity_resolver(context=context) is resolver + + +def test_identity_resolver_missing() -> None: + with pytest.raises(SmithyIdentityError): + BearerAuthScheme().identity_resolver(context=TypedProperties()) + + +def test_signer_properties_empty() -> None: + assert BearerAuthScheme().signer_properties(context=TypedProperties()) == {} + + +def test_scheme_signs_end_to_end() -> None: + config = _Config(token="spam", token_identity_resolver=StaticTokenResolver()) + context = TypedProperties({"config": config}) + scheme = BearerAuthScheme() + + identity = scheme.identity_resolver(context=context).get_identity( + properties=scheme.identity_properties(context=context) + ) + signed = scheme.signer().sign( + request=_request(), + identity=identity, + properties=scheme.signer_properties(context=context), + ) + + assert signed.fields["Authorization"].values == ["Bearer spam"] diff --git a/scripts/api-snapshot/api-rex.json b/scripts/api-snapshot/api-rex.json index 06443054f..f10a4cce2 100644 --- a/scripts/api-snapshot/api-rex.json +++ b/scripts/api-snapshot/api-rex.json @@ -999,6 +999,14 @@ "HTTPRequest": "rex-protocol", "PropertyKey": "rex-class" }, + "smithy_http.aio.auth.bearer": { + "AsyncAuthScheme": "rex-protocol", + "AsyncIdentityResolver": "rex-protocol[async]", + "HTTPRequest": "rex-protocol", + "PropertyKey": "rex-class", + "TokenIdentity": "rex-class", + "TokenIdentityProperties": "rex-class" + }, "smithy_http.aio.crt": { "AsyncBytesReader": "rex-class[async]", "Field": "rex-class", @@ -1077,7 +1085,8 @@ "list_async": "rex-function" }, "smithy_http.auth": { - "apikey": "rex-module" + "apikey": "rex-module", + "bearer": "rex-module" }, "smithy_http.auth.apikey": { "APIKeyIdentity": "rex-class", @@ -1093,6 +1102,19 @@ "SmithyIdentityError": "rex-exception", "URI": "rex-class" }, + "smithy_http.auth.bearer": { + "AuthScheme": "rex-protocol", + "Field": "rex-class", + "HTTPBearerAuthTrait": "rex-class", + "HTTPRequest": "rex-protocol", + "IdentityResolver": "rex-protocol", + "ShapeID": "rex-class", + "Signer": "rex-protocol", + "SmithyHTTPError": "rex-exception", + "SmithyIdentityError": "rex-exception", + "TokenIdentity": "rex-class", + "TokenIdentityProperties": "rex-class" + }, "smithy_http.bindings": { "ErrorFault": "rex-class", "ErrorTrait": "rex-class", diff --git a/scripts/api-snapshot/api.json b/scripts/api-snapshot/api.json index b6924a475..bc6ff566f 100644 --- a/scripts/api-snapshot/api.json +++ b/scripts/api-snapshot/api.json @@ -609,6 +609,7 @@ "EventHeaderTrait": "class", "EventPayloadTrait": "class", "HTTPAPIKeyAuthTrait": "class", + "HTTPBearerAuthTrait": "class", "HTTPChecksumRequiredTrait": "class", "HTTPErrorTrait": "class", "HTTPHeaderTrait": "class", @@ -690,6 +691,11 @@ "AsyncAPIKeyAuthScheme": "class", "AsyncAPIKeyResolverConfig": "protocol" }, + "smithy_http.aio.auth.bearer": { + "AsyncBearerAuthScheme": "class", + "AsyncTokenResolverConfig": "protocol", + "TOKEN_RESOLVER_CONFIG": "PropertyKey" + }, "smithy_http.aio.crt": { "AWSCRTHTTPClient": "class[async]", "AWSCRTHTTPClientConfig": "class", @@ -726,6 +732,11 @@ "APIKeyResolverConfig": "protocol", "APIKeySigner": "class" }, + "smithy_http.auth.bearer": { + "BearerAuthScheme": "class", + "BearerSigner": "class", + "TokenResolverConfig": "protocol" + }, "smithy_http.bindings": { "Binding": "class", "RequestBindingMatcher": "class", diff --git a/scripts/api-snapshot/mirrors.txt b/scripts/api-snapshot/mirrors.txt index 9f47e7339..411aab79a 100644 --- a/scripts/api-snapshot/mirrors.txt +++ b/scripts/api-snapshot/mirrors.txt @@ -82,6 +82,9 @@ Dual-mode symbols (async in aio, sync twin outside): apikey.py AsyncAPIKeyAuthScheme APIKeyAuthScheme AsyncAPIKeyResolverConfig APIKeyResolverConfig + bearer.py + AsyncBearerAuthScheme BearerAuthScheme + AsyncTokenResolverConfig TokenResolverConfig identity/ apikey.py AsyncAPIKeyIdentityResolver APIKeyIdentityResolver @@ -102,4 +105,4 @@ Dual-mode symbols (async in aio, sync twin outside): http_mock.py AsyncHTTPMockController HTTPMockController mock_async mock -51 dual-mode symbol(s). +53 dual-mode symbol(s). diff --git a/scripts/verifications/import-cost.json b/scripts/verifications/import-cost.json index 4b928b808..badb97e0a 100644 --- a/scripts/verifications/import-cost.json +++ b/scripts/verifications/import-cost.json @@ -12,7 +12,7 @@ "smithy_core": 5, "smithy_core (all public modules)": 46, "smithy_http": 12, - "smithy_http (all public modules)": 94, + "smithy_http (all public modules)": 96, "smithy_json": 21, "smithy_json (all public modules)": 21, "smithy_python": 1, From 9ba9b07dae6b5ce28188c4299282898e54f0a9e4 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Sun, 22 Nov 2026 11:59:33 -0500 Subject: [PATCH 04/11] Default token_identity_resolver in generated AWS clients to a static resolver when a token is configured, otherwise to the default token identity chain --- CHANGELOG.md | 8 +- .../aws-json-1-0/src/awsjson10/aio/client.py | 21 ++- .../aws-json-1-0/src/awsjson10/client.py | 21 ++- .../aws-json-1-1/src/awsjson11/aio/client.py | 21 ++- .../aws-json-1-1/src/awsjson11/client.py | 21 ++- .../aws-query/src/awsquery/aio/client.py | 21 ++- .../aws-query/src/awsquery/client.py | 21 ++- .../ec2-query/src/ec2query/aio/client.py | 21 ++- .../ec2-query/src/ec2query/client.py | 21 ++- .../nonquerycompatiblerpcv2cbor/aio/client.py | 21 ++- .../src/nonquerycompatiblerpcv2cbor/client.py | 21 ++- .../querycompatibleawsjson10/aio/client.py | 21 ++- .../src/querycompatibleawsjson10/client.py | 21 ++- .../querycompatiblerpcv2cbor/aio/client.py | 21 ++- .../src/querycompatiblerpcv2cbor/client.py | 21 ++- .../rest-json-1/src/restjson/aio/client.py | 21 ++- .../rest-json-1/src/restjson/client.py | 21 ++- .../src/restxmlwithnamespace/aio/client.py | 21 ++- .../src/restxmlwithnamespace/client.py | 21 ++- .../rest-xml/src/restxml/aio/client.py | 21 ++- codegen-output/rest-xml/src/restxml/client.py | 21 ++- .../python/codegen/test/AwsCodegenTest.java | 54 ++++++++ .../it/resources/META-INF/smithy/main.smithy | 1 + .../aws/codegen/AwsIdentityIntegration.java | 129 +++++++++++++++--- 24 files changed, 449 insertions(+), 163 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cc411735..256273303 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,13 @@ * Generated clients support the `smithy.api#httpBearerAuth` trait. A service that models it gets `token` and `token_identity_resolver` configuration settings, - and its requests carry an `Authorization: Bearer` header. + and an operation whose selected auth scheme is bearer auth sends an + `Authorization: Bearer` header. Auth scheme selection is unchanged: the first + scheme in an operation's effective auth list that the client supports is used, + so a service that lists SigV4 before bearer auth keeps signing with SigV4. AWS + clients default `token_identity_resolver` during setup: a configured `token` + is used through a static resolver, otherwise the default token identity chain + is consulted, so neither needs a resolver wired by hand. ## v0.7.0 diff --git a/codegen-output/aws-json-1-0/src/awsjson10/aio/client.py b/codegen-output/aws-json-1-0/src/awsjson10/aio/client.py index 0bfaf22ed..83154b4ea 100644 --- a/codegen-output/aws-json-1-0/src/awsjson10/aio/client.py +++ b/codegen-output/aws-json-1-0/src/awsjson10/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -737,13 +738,7 @@ async def _new_config(self) -> AsyncJSONRPC10Config: async def _post_setup(self, config: AsyncJSONRPC10Config) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -751,3 +746,15 @@ async def _post_setup(self, config: AsyncJSONRPC10Config) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncJSONRPC10Config + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/aws-json-1-0/src/awsjson10/client.py b/codegen-output/aws-json-1-0/src/awsjson10/client.py index e187e6cdf..1f172ccba 100644 --- a/codegen-output/aws-json-1-0/src/awsjson10/client.py +++ b/codegen-output/aws-json-1-0/src/awsjson10/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -737,13 +738,7 @@ def _new_config(self) -> JSONRPC10Config: def _post_setup(self, config: JSONRPC10Config) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -751,3 +746,15 @@ def _post_setup(self, config: JSONRPC10Config) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: JSONRPC10Config + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/aws-json-1-1/src/awsjson11/aio/client.py b/codegen-output/aws-json-1-1/src/awsjson11/aio/client.py index 4656a6e77..597b034cc 100644 --- a/codegen-output/aws-json-1-1/src/awsjson11/aio/client.py +++ b/codegen-output/aws-json-1-1/src/awsjson11/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -812,13 +813,7 @@ async def _new_config(self) -> AsyncJsonProtocolConfig: async def _post_setup(self, config: AsyncJsonProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -826,3 +821,15 @@ async def _post_setup(self, config: AsyncJsonProtocolConfig) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncJsonProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/aws-json-1-1/src/awsjson11/client.py b/codegen-output/aws-json-1-1/src/awsjson11/client.py index 0745c4942..8cfc7d01f 100644 --- a/codegen-output/aws-json-1-1/src/awsjson11/client.py +++ b/codegen-output/aws-json-1-1/src/awsjson11/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -812,13 +813,7 @@ def _new_config(self) -> JsonProtocolConfig: def _post_setup(self, config: JsonProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -826,3 +821,15 @@ def _post_setup(self, config: JsonProtocolConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: JsonProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/aws-query/src/awsquery/aio/client.py b/codegen-output/aws-query/src/awsquery/aio/client.py index 3199e7f86..d7f0b73ab 100644 --- a/codegen-output/aws-query/src/awsquery/aio/client.py +++ b/codegen-output/aws-query/src/awsquery/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -1455,13 +1456,7 @@ async def _new_config(self) -> AsyncQueryProtocolConfig: async def _post_setup(self, config: AsyncQueryProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -1469,3 +1464,15 @@ async def _post_setup(self, config: AsyncQueryProtocolConfig) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncQueryProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/aws-query/src/awsquery/client.py b/codegen-output/aws-query/src/awsquery/client.py index b004779d1..a3707ec16 100644 --- a/codegen-output/aws-query/src/awsquery/client.py +++ b/codegen-output/aws-query/src/awsquery/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -1455,13 +1456,7 @@ def _new_config(self) -> QueryProtocolConfig: def _post_setup(self, config: QueryProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -1469,3 +1464,15 @@ def _post_setup(self, config: QueryProtocolConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: QueryProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/ec2-query/src/ec2query/aio/client.py b/codegen-output/ec2-query/src/ec2query/aio/client.py index b6c477a1d..bf96264db 100644 --- a/codegen-output/ec2-query/src/ec2query/aio/client.py +++ b/codegen-output/ec2-query/src/ec2query/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -1112,13 +1113,7 @@ async def _new_config(self) -> AsyncEC2ProtocolConfig: async def _post_setup(self, config: AsyncEC2ProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -1126,3 +1121,15 @@ async def _post_setup(self, config: AsyncEC2ProtocolConfig) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncEC2ProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/ec2-query/src/ec2query/client.py b/codegen-output/ec2-query/src/ec2query/client.py index 0a41d2b1e..ea8e4f264 100644 --- a/codegen-output/ec2-query/src/ec2query/client.py +++ b/codegen-output/ec2-query/src/ec2query/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -1112,13 +1113,7 @@ def _new_config(self) -> EC2ProtocolConfig: def _post_setup(self, config: EC2ProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -1126,3 +1121,15 @@ def _post_setup(self, config: EC2ProtocolConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: EC2ProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/non-query-compatible-rpcv2-cbor/src/nonquerycompatiblerpcv2cbor/aio/client.py b/codegen-output/non-query-compatible-rpcv2-cbor/src/nonquerycompatiblerpcv2cbor/aio/client.py index 37e67d682..4aa026cae 100644 --- a/codegen-output/non-query-compatible-rpcv2-cbor/src/nonquerycompatiblerpcv2cbor/aio/client.py +++ b/codegen-output/non-query-compatible-rpcv2-cbor/src/nonquerycompatiblerpcv2cbor/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -81,13 +82,7 @@ async def _post_setup( self, config: AsyncNonQueryCompatibleRpcV2ProtocolConfig ) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -95,3 +90,15 @@ async def _post_setup( region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncNonQueryCompatibleRpcV2ProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/non-query-compatible-rpcv2-cbor/src/nonquerycompatiblerpcv2cbor/client.py b/codegen-output/non-query-compatible-rpcv2-cbor/src/nonquerycompatiblerpcv2cbor/client.py index 937b6e433..0edccf0f1 100644 --- a/codegen-output/non-query-compatible-rpcv2-cbor/src/nonquerycompatiblerpcv2cbor/client.py +++ b/codegen-output/non-query-compatible-rpcv2-cbor/src/nonquerycompatiblerpcv2cbor/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -79,13 +80,7 @@ def _new_config(self) -> NonQueryCompatibleRpcV2ProtocolConfig: def _post_setup(self, config: NonQueryCompatibleRpcV2ProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -93,3 +88,15 @@ def _post_setup(self, config: NonQueryCompatibleRpcV2ProtocolConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: NonQueryCompatibleRpcV2ProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/query-compatible-aws-json-1-0/src/querycompatibleawsjson10/aio/client.py b/codegen-output/query-compatible-aws-json-1-0/src/querycompatibleawsjson10/aio/client.py index d5b55c019..d8e45a2d2 100644 --- a/codegen-output/query-compatible-aws-json-1-0/src/querycompatibleawsjson10/aio/client.py +++ b/codegen-output/query-compatible-aws-json-1-0/src/querycompatibleawsjson10/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -79,13 +80,7 @@ async def _new_config(self) -> AsyncQueryCompatibleJSONRPC10Config: async def _post_setup(self, config: AsyncQueryCompatibleJSONRPC10Config) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -93,3 +88,15 @@ async def _post_setup(self, config: AsyncQueryCompatibleJSONRPC10Config) -> None region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncQueryCompatibleJSONRPC10Config + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/query-compatible-aws-json-1-0/src/querycompatibleawsjson10/client.py b/codegen-output/query-compatible-aws-json-1-0/src/querycompatibleawsjson10/client.py index c620e96d3..975d199d8 100644 --- a/codegen-output/query-compatible-aws-json-1-0/src/querycompatibleawsjson10/client.py +++ b/codegen-output/query-compatible-aws-json-1-0/src/querycompatibleawsjson10/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -77,13 +78,7 @@ def _new_config(self) -> QueryCompatibleJSONRPC10Config: def _post_setup(self, config: QueryCompatibleJSONRPC10Config) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -91,3 +86,15 @@ def _post_setup(self, config: QueryCompatibleJSONRPC10Config) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: QueryCompatibleJSONRPC10Config + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/query-compatible-rpcv2-cbor/src/querycompatiblerpcv2cbor/aio/client.py b/codegen-output/query-compatible-rpcv2-cbor/src/querycompatiblerpcv2cbor/aio/client.py index a1313e1b4..7f5bfee69 100644 --- a/codegen-output/query-compatible-rpcv2-cbor/src/querycompatiblerpcv2cbor/aio/client.py +++ b/codegen-output/query-compatible-rpcv2-cbor/src/querycompatiblerpcv2cbor/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -81,13 +82,7 @@ async def _post_setup( self, config: AsyncQueryCompatibleRpcV2ProtocolConfig ) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -95,3 +90,15 @@ async def _post_setup( region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncQueryCompatibleRpcV2ProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/query-compatible-rpcv2-cbor/src/querycompatiblerpcv2cbor/client.py b/codegen-output/query-compatible-rpcv2-cbor/src/querycompatiblerpcv2cbor/client.py index bf76bd38b..a37b7194e 100644 --- a/codegen-output/query-compatible-rpcv2-cbor/src/querycompatiblerpcv2cbor/client.py +++ b/codegen-output/query-compatible-rpcv2-cbor/src/querycompatiblerpcv2cbor/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -77,13 +78,7 @@ def _new_config(self) -> QueryCompatibleRpcV2ProtocolConfig: def _post_setup(self, config: QueryCompatibleRpcV2ProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -91,3 +86,15 @@ def _post_setup(self, config: QueryCompatibleRpcV2ProtocolConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: QueryCompatibleRpcV2ProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/rest-json-1/src/restjson/aio/client.py b/codegen-output/rest-json-1/src/restjson/aio/client.py index 9bdb86196..12d832386 100644 --- a/codegen-output/rest-json-1/src/restjson/aio/client.py +++ b/codegen-output/rest-json-1/src/restjson/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -4990,13 +4991,7 @@ async def _new_config(self) -> AsyncRestJsonProtocolConfig: async def _post_setup(self, config: AsyncRestJsonProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -5004,3 +4999,15 @@ async def _post_setup(self, config: AsyncRestJsonProtocolConfig) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncRestJsonProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/rest-json-1/src/restjson/client.py b/codegen-output/rest-json-1/src/restjson/client.py index 5b37a6984..03c9f26ae 100644 --- a/codegen-output/rest-json-1/src/restjson/client.py +++ b/codegen-output/rest-json-1/src/restjson/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -4652,13 +4653,7 @@ def _new_config(self) -> RestJsonProtocolConfig: def _post_setup(self, config: RestJsonProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -4666,3 +4661,15 @@ def _post_setup(self, config: RestJsonProtocolConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: RestJsonProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/rest-xml-with-namespace/src/restxmlwithnamespace/aio/client.py b/codegen-output/rest-xml-with-namespace/src/restxmlwithnamespace/aio/client.py index 4501fd151..e436076cb 100644 --- a/codegen-output/rest-xml-with-namespace/src/restxmlwithnamespace/aio/client.py +++ b/codegen-output/rest-xml-with-namespace/src/restxmlwithnamespace/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -85,13 +86,7 @@ async def _new_config(self) -> AsyncRestXmlProtocolNamespaceConfig: async def _post_setup(self, config: AsyncRestXmlProtocolNamespaceConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -99,3 +94,15 @@ async def _post_setup(self, config: AsyncRestXmlProtocolNamespaceConfig) -> None region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncRestXmlProtocolNamespaceConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/rest-xml-with-namespace/src/restxmlwithnamespace/client.py b/codegen-output/rest-xml-with-namespace/src/restxmlwithnamespace/client.py index d5306246c..c0a53c7b4 100644 --- a/codegen-output/rest-xml-with-namespace/src/restxmlwithnamespace/client.py +++ b/codegen-output/rest-xml-with-namespace/src/restxmlwithnamespace/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -83,13 +84,7 @@ def _new_config(self) -> RestXmlProtocolNamespaceConfig: def _post_setup(self, config: RestXmlProtocolNamespaceConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -97,3 +92,15 @@ def _post_setup(self, config: RestXmlProtocolNamespaceConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: RestXmlProtocolNamespaceConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/rest-xml/src/restxml/aio/client.py b/codegen-output/rest-xml/src/restxml/aio/client.py index 233bc2e1d..5bc78b56b 100644 --- a/codegen-output/rest-xml/src/restxml/aio/client.py +++ b/codegen-output/rest-xml/src/restxml/aio/client.py @@ -6,6 +6,7 @@ from typing import Unpack as _Unpack, cast, overload as _overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -2868,13 +2869,7 @@ async def _new_config(self) -> AsyncRestXmlProtocolConfig: async def _post_setup(self, config: AsyncRestXmlProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -2882,3 +2877,15 @@ async def _post_setup(self, config: AsyncRestXmlProtocolConfig) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncRestXmlProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output/rest-xml/src/restxml/client.py b/codegen-output/rest-xml/src/restxml/client.py index 57acdab3a..10d2cdbb0 100644 --- a/codegen-output/rest-xml/src/restxml/client.py +++ b/codegen-output/rest-xml/src/restxml/client.py @@ -5,6 +5,7 @@ import logging from typing import Unpack as _Unpack, cast, overload as _overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -2868,13 +2869,7 @@ def _new_config(self) -> RestXmlProtocolConfig: def _post_setup(self, config: RestXmlProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -2882,3 +2877,15 @@ def _post_setup(self, config: RestXmlProtocolConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: RestXmlProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsCodegenTest.java b/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsCodegenTest.java index f1d21e83e..7ffdc69b3 100644 --- a/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsCodegenTest.java +++ b/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsCodegenTest.java @@ -69,9 +69,63 @@ public void testCodegen(@TempDir Path tempDir) throws IOException { assertFalse(client.contains("def _ensure_setup(")); assertFalse(client.contains("def _prepare_call[")); + // Bearer auth: the config gets the token fields and the AWS setup hook defaults + // the resolver: static when a ``token`` is configured, the default token chain + // otherwise. No SigV4 on this service, so no credentials chain is wired. + assertTrue(config.contains("token: str | None = None")); + // The formatter wraps the long annotation, so match its parts. + assertInOrder(config, + "token_identity_resolver: (", + "AsyncIdentityResolver[TokenIdentity, TokenIdentityProperties] | None", + ") = None"); + assertTrue(config.contains("\"token_identity_resolver\": FieldSpec(default=None)")); + assertTrue(config.contains("ShapeID(\"smithy.api#httpBearerAuth\"): AsyncBearerAuthScheme()")); + assertInOrder( + client, + "async def _post_setup(self, config: AsyncRESTJSONConfig) -> None:", + "if config.token_identity_resolver is None:", + "if config.token is not None:", + "config.token_identity_resolver = AsyncStaticTokenResolver()", + "else:", + "config_file, profile_name = await self._profile_overrides(config)", + "config.token_identity_resolver = await AsyncIdentityChain.create(", + "TokenIdentity,", + "config_file=config_file,", + "profile_name=profile_name,", + "region_override=config.region,", + "http_client=cast(AsyncHTTPClient | None, config.transport),", + "async def _profile_overrides(", + "config_file = await config_context.parsed_profiles()", + "if config_context.profile_source is ConfigSource.OVERRIDE:", + "return config_file, profile_name"); + assertTrue(client.contains("from smithy_http.aio.identity.token import AsyncStaticTokenResolver")); + assertTrue(client.contains("from smithy_aws_core.aio.identity.chain import AsyncIdentityChain")); + assertTrue(client.contains("from smithy_http.identity import TokenIdentity")); + assertFalse(client.contains("aws_credentials_identity_resolver")); + + var syncClient = Files.readString(tempDir.resolve("src/restjson/client.py")); + assertInOrder( + syncClient, + "def _post_setup(self, config: RESTJSONConfig) -> None:", + "if config.token_identity_resolver is None:", + "if config.token is not None:", + "config.token_identity_resolver = StaticTokenResolver()", + "else:", + "config_file, profile_name = self._profile_overrides(config)", + "config.token_identity_resolver = IdentityChain.create(", + "TokenIdentity,", + "http_client=cast(HTTPClient | None, config.transport),", + "def _profile_overrides(", + "config_file = config_context.parsed_profiles()"); + assertTrue(syncClient.contains("from smithy_http.identity.token import StaticTokenResolver")); + assertTrue(syncClient.contains("from smithy_aws_core.identity.chain.resolver import IdentityChain")); + assertFalse(syncClient.contains("async def _post_setup")); + assertFalse(syncClient.contains("async def _profile_overrides")); + var schemas = Files.readString(tempDir.resolve("src/restjson/_private/schemas.py")); assertTrue(schemas.contains("aws.protocols#restJson1")); assertTrue(schemas.contains("smithy.api#httpApiKeyAuth")); + assertTrue(schemas.contains("smithy.api#httpBearerAuth")); assertTrue(schemas.contains("\"name\": \"weather-auth\"")); assertTrue(schemas.contains("aws.api#service")); assertTrue(schemas.contains("\"sdkId\": \"REST JSON\"")); diff --git a/codegen/aws/core/src/it/resources/META-INF/smithy/main.smithy b/codegen/aws/core/src/it/resources/META-INF/smithy/main.smithy index bbb57c913..6db3b157d 100644 --- a/codegen/aws/core/src/it/resources/META-INF/smithy/main.smithy +++ b/codegen/aws/core/src/it/resources/META-INF/smithy/main.smithy @@ -20,6 +20,7 @@ use aws.api#service @title("AWS REST JSON Service") @paginated(inputToken: "nextToken", outputToken: "nextToken", pageSize: "pageSize") @httpApiKeyAuth(name: "weather-auth", in: "header") +@httpBearerAuth service RestJsonService { version: "2006-03-01" operations: [ diff --git a/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegration.java b/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegration.java index 8f0a1954f..fe914eeae 100644 --- a/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegration.java +++ b/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegration.java @@ -7,7 +7,9 @@ import java.util.List; import software.amazon.smithy.aws.traits.auth.SigV4Trait; import software.amazon.smithy.codegen.core.Symbol; +import software.amazon.smithy.model.traits.HttpBearerAuthTrait; import software.amazon.smithy.python.codegen.GenerationContext; +import software.amazon.smithy.python.codegen.RuntimeTypes; import software.amazon.smithy.python.codegen.SmithyPythonDependency; import software.amazon.smithy.python.codegen.SyncVariant; import software.amazon.smithy.python.codegen.integrations.PythonIntegration; @@ -18,7 +20,12 @@ import software.amazon.smithy.utils.SmithyInternalApi; /** - * Sets up the default AWS credentials identity chain during client setup. + * Sets up the default identity resolvers during client setup. + * + *

For services using SigV4 this wires the default AWS credentials identity chain. + * For services using {@code smithy.api#httpBearerAuth} it wires a static token + * resolver when a {@code token} is configured, matching the generic client config, + * and the default token identity chain otherwise. */ @SmithyInternalApi public class AwsIdentityIntegration implements PythonIntegration { @@ -28,18 +35,35 @@ public List> inte GenerationContext context ) { var service = context.settings().service(context.model()); - if (!service.hasTrait(SigV4Trait.class)) { + var hasSigV4 = service.hasTrait(SigV4Trait.class); + var hasBearer = service.hasTrait(HttpBearerAuthTrait.class); + if (!hasSigV4 && !hasBearer) { return List.of(); } - return List.of(new CredentialsIdentitySetupInterceptor()); + return List.of(new IdentitySetupInterceptor(hasSigV4, hasBearer)); } /** - * Initializes the default AWS credentials identity chain during client setup. + * Initializes the default identity resolvers during client setup. */ - private static final class CredentialsIdentitySetupInterceptor + private static final class IdentitySetupInterceptor implements CodeInterceptor { + // The sync writer maps this to its sync twin. + private static final Symbol HTTP_CLIENT = Symbol.builder() + .name("AsyncHTTPClient") + .namespace("smithy_http.aio.interfaces", ".") + .addDependency(SmithyPythonDependency.SMITHY_HTTP) + .build(); + + private final boolean hasSigV4; + private final boolean hasBearer; + + IdentitySetupInterceptor(boolean hasSigV4, boolean hasBearer) { + this.hasSigV4 = hasSigV4; + this.hasBearer = hasBearer; + } + @Override public Class sectionType() { return ClientSetupSection.class; @@ -50,39 +74,100 @@ public void write(PythonWriter writer, String previousText, ClientSetupSection s if (!previousText.isBlank()) { writer.write(previousText); } + var header = "async def _post_setup(self, config: $T) -> None:"; + writer.openBlock(section.sync() ? SyncVariant.toSyncCode(header) : header, + "", + section.config(), + () -> { + if (hasSigV4) { + writeCredentialsSetup(writer, section); + } + if (hasBearer) { + writeBearerTokenSetup(writer, section); + } + }); + writer.write(""); + writeProfileOverrides(writer, section); + } + + private void writeCredentialsSetup(PythonWriter writer, ClientSetupSection section) { + var template = """ + if config.aws_credentials_identity_resolver is None: + config_file, profile_name = await self._profile_overrides(config) + config.aws_credentials_identity_resolver = await $1T.create( + $2T, + config_file=config_file, + profile_name=profile_name, + region_override=config.region, + http_client=cast($3T | None, config.transport), + ) + """; writer.addStdlibImport("typing", "cast"); + writer.write(section.sync() ? SyncVariant.toSyncCode(template) : template, + identityChain(section.sync()), + AwsRuntimeTypes.AWS_CREDENTIALS_IDENTITY, + HTTP_CLIENT); + } + + // A configured ``token`` gets the static resolver, which reads it from the + // identity properties the bearer auth scheme supplies. Otherwise the default + // token provider chain is consulted, as every AWS SDK does for bearer auth. + // The sync writer maps the async symbols to their twins. + private void writeBearerTokenSetup(PythonWriter writer, ClientSetupSection section) { var template = """ - async def _post_setup(self, config: $5T) -> None: - if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is $4T.OVERRIDE: - profile_name = config_context.profile_name - config.aws_credentials_identity_resolver = await $1T.create( - $2T, + if config.token_identity_resolver is None: + if config.token is not None: + config.token_identity_resolver = $1T() + else: + config_file, profile_name = await self._profile_overrides(config) + config.token_identity_resolver = await $2T.create( + $3T, config_file=config_file, profile_name=profile_name, region_override=config.region, - http_client=cast($3T | None, config.transport), + http_client=cast($4T | None, config.transport), ) """; + writer.addStdlibImport("typing", "cast"); writer.write(section.sync() ? SyncVariant.toSyncCode(template) : template, + RuntimeTypes.STATIC_TOKEN_RESOLVER, identityChain(section.sync()), - AwsRuntimeTypes.AWS_CREDENTIALS_IDENTITY, Symbol.builder() - .name("AsyncHTTPClient") - .namespace("smithy_http.aio.interfaces", ".") + .name("TokenIdentity") + .namespace("smithy_http.identity", ".") .addDependency(SmithyPythonDependency.SMITHY_HTTP) .build(), + HTTP_CLIENT); + } + + // Shared by every identity chain the client builds: the parsed config file + // and the explicit profile override, if any. + private void writeProfileOverrides(PythonWriter writer, ClientSetupSection section) { + var template = """ + async def _profile_overrides( + self, config: $1T + ) -> tuple[$2T | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is $3T.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name + """; + writer.write(section.sync() ? SyncVariant.toSyncCode(template) : template, + section.config(), + Symbol.builder() + .name("MergedConfig") + .namespace("smithy_aws_core.config.merged_config", ".") + .addDependency(AwsPythonDependency.SMITHY_AWS_CORE) + .build(), Symbol.builder() .name("ConfigSource") .namespace("smithy_aws_core.config.types", ".") .addDependency(AwsPythonDependency.SMITHY_AWS_CORE) - .build(), - section.config()); + .build()); } // The sync twin is defined in a submodule the aio-stripping convention can't derive. From ca7355018807480310732217f202a517866070c0 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Fri, 20 Nov 2026 05:22:56 -0500 Subject: [PATCH 05/11] Select the active profile in the identity chain for every identity type, not only AWS credentials --- ...ncement-c23ea870f2f643559a19bff285d91447.json | 4 ++++ .../identity/chain/providers/shared_config.py | 16 ++++++++-------- .../chain/providers/test_shared_config.py | 13 ++++++++++--- scripts/api-snapshot/api-rex.json | 1 - 4 files changed, 22 insertions(+), 12 deletions(-) create mode 100644 packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-c23ea870f2f643559a19bff285d91447.json diff --git a/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-c23ea870f2f643559a19bff285d91447.json b/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-c23ea870f2f643559a19bff285d91447.json new file mode 100644 index 000000000..6b3ce6aae --- /dev/null +++ b/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-c23ea870f2f643559a19bff285d91447.json @@ -0,0 +1,4 @@ +{ + "type": "enhancement", + "description": "The identity chain's shared config step now loads the config files and selects the active profile for every identity type, so `TokenIdentity` chains see the same profile as credentials chains." +} diff --git a/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/providers/shared_config.py b/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/providers/shared_config.py index 02a9aa2c1..b29f2beb6 100644 --- a/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/providers/shared_config.py +++ b/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/providers/shared_config.py @@ -6,7 +6,6 @@ from smithy_core.interfaces.identity import Identity from smithy_core.program import Program -from ...components import AWSCredentialsIdentity from ..ordering import Standard, StandardProvider from ..provider import _ChainSetupBase # pyright: ignore[reportPrivateUsage] @@ -27,15 +26,16 @@ def ordering(self) -> Standard: return Standard(slot=StandardProvider.SHARED_CONFIG) def setup(self, identity_type: type[Identity], setup: _ChainSetupBase) -> Any: - """Load and select the active profile for AWS credentials.""" - return setup._run(self._setup(identity_type, setup)) # pyright: ignore[reportPrivateUsage] + """Load and select the active profile for every identity type. - def _setup( - self, identity_type: type[Identity], setup: _ChainSetupBase - ) -> Program[None]: - if identity_type is not AWSCredentialsIdentity: - return + This step registers no resolvers; it only makes the shared config and the + active profile name available to the profile-based providers that follow it, + whatever identity type the chain resolves (for example ``TokenIdentity`` + chains read ``sso_session`` from the same profile). + """ + return setup._run(self._setup(setup)) # pyright: ignore[reportPrivateUsage] + def _setup(self, setup: _ChainSetupBase) -> Program[None]: config_file = setup.config_file if config_file is None: config_file = yield setup._load_config # pyright: ignore[reportPrivateUsage] diff --git a/packages/smithy-aws-core/tests/unit/identity/chain/providers/test_shared_config.py b/packages/smithy-aws-core/tests/unit/identity/chain/providers/test_shared_config.py index 8d903e9b4..383c8c62f 100644 --- a/packages/smithy-aws-core/tests/unit/identity/chain/providers/test_shared_config.py +++ b/packages/smithy-aws-core/tests/unit/identity/chain/providers/test_shared_config.py @@ -14,18 +14,25 @@ from .conftest import OtherIdentity -async def test_ignores_non_aws_identity_type( +# The shared config step is identity-type agnostic: a TokenIdentity chain needs the +# same active profile (to find its sso_session) as a credentials chain does. +async def test_selects_profile_for_non_aws_identity_type( setup_provider: Callable[..., Awaitable[AsyncChainSetup]], + merged_config: Callable[..., MergedConfig], monkeypatch: pytest.MonkeyPatch, ) -> None: - load_config = AsyncMock() + loaded = merged_config({"default": {"name": "loaded"}}) + load_config = AsyncMock(return_value=loaded) monkeypatch.setattr(shared_config_module, "load_config_async", load_config) + monkeypatch.setenv("AWS_PROFILE", "environment") setup = await setup_provider(SharedConfigProvider(), identity_type=OtherIdentity) + assert setup.config_file is loaded + assert setup.profile_name == "environment" assert setup.resolvers == () assert not setup.terminal - load_config.assert_not_awaited() + load_config.assert_awaited_once_with() # Profile selection precedence: profile_name wins over the AWS_PROFILE diff --git a/scripts/api-snapshot/api-rex.json b/scripts/api-snapshot/api-rex.json index f10a4cce2..ca518746a 100644 --- a/scripts/api-snapshot/api-rex.json +++ b/scripts/api-snapshot/api-rex.json @@ -415,7 +415,6 @@ "StandardProvider": "rex-class" }, "smithy_aws_core.identity.chain.providers.shared_config": { - "AWSCredentialsIdentity": "rex-class", "Identity": "rex-protocol", "Program": "rex-type_alias", "Standard": "rex-class", From 328368e9461338589c5f52a91e7aa856f18a4f9f Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Sat, 21 Nov 2026 15:32:06 -0500 Subject: [PATCH 06/11] Treat the bearer token as a secret and share auth identity resolvers across config copies --- .../AwsClientContextParamsCodegenTest.java | 2 + .../python/codegen/test/AwsCodegenTest.java | 14 +++ .../codegen/AwsAsyncConfigIntegration.java | 19 ++++ ...ment-958c7cbfa9004679b551de251e33329b.json | 4 + .../src/smithy_aws_core/config/aws_config.py | 46 +++++--- .../identity/chain/exceptions.py | 2 +- .../identity/chain/resolver.py | 14 ++- .../tests/unit/config/test_resolver.py | 107 +++++++++++++++++- .../tests/unit/identity/chain/test_chain.py | 33 +++++- scripts/api-snapshot/api-rex.json | 1 + 10 files changed, 215 insertions(+), 27 deletions(-) create mode 100644 packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-958c7cbfa9004679b551de251e33329b.json diff --git a/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsClientContextParamsCodegenTest.java b/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsClientContextParamsCodegenTest.java index 8761ef71d..123566fd7 100644 --- a/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsClientContextParamsCodegenTest.java +++ b/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsClientContextParamsCodegenTest.java @@ -64,6 +64,8 @@ public void addsAsyncConfigFieldsForClientContextParams(@TempDir Path tempDir) t assertFalse(config.contains("use_fips_endpoint")); assertFalse(config.contains("use_dualstack_endpoint")); assertFalse(config.contains("account_id_endpoint_mode")); + // SigV4-only: the base class already shares the credentials resolver. + assertFalse(config.contains("_SHARED_FIELDS")); } @Test diff --git a/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsCodegenTest.java b/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsCodegenTest.java index 7ffdc69b3..e8007112b 100644 --- a/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsCodegenTest.java +++ b/codegen/aws/core/src/it/java/software/amazon/smithy/python/codegen/test/AwsCodegenTest.java @@ -80,6 +80,20 @@ public void testCodegen(@TempDir Path tempDir) throws IOException { ") = None"); assertTrue(config.contains("\"token_identity_resolver\": FieldSpec(default=None)")); assertTrue(config.contains("ShapeID(\"smithy.api#httpBearerAuth\"): AsyncBearerAuthScheme()")); + // Deep copies of the config share the auth schemes' identity resolvers. + assertInOrder(config, + "_SHARED_FIELDS: ClassVar[tuple[str, ...]] = (", + "*AsyncAwsConfig._SHARED_FIELDS,", + "\"api_key_identity_resolver\",", + "\"token_identity_resolver\",", + ")"); + var syncConfig = Files.readString(tempDir.resolve("src/restjson/config.py")); + assertInOrder(syncConfig, + "_SHARED_FIELDS: ClassVar[tuple[str, ...]] = (", + "*AwsConfig._SHARED_FIELDS,", + "\"api_key_identity_resolver\",", + "\"token_identity_resolver\",", + ")"); assertInOrder( client, "async def _post_setup(self, config: AsyncRESTJSONConfig) -> None:", diff --git a/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsAsyncConfigIntegration.java b/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsAsyncConfigIntegration.java index 4ce368c44..ee13556c7 100644 --- a/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsAsyncConfigIntegration.java +++ b/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsAsyncConfigIntegration.java @@ -401,6 +401,25 @@ public void write(PythonWriter writer, String previousText, AsyncConfigSection s writer.closeBlock("}"); writer.write(""); + + // Identity resolvers added by auth schemes hold caches and locks, so a + // deep copy of the config must share them like the base resolvers. + var sharedFields = pluginProperties.keySet() + .stream() + .filter(name -> name.endsWith("_identity_resolver")) + // The base class already shares the SigV4 credentials resolver. + .filter(name -> !PREDEFINED_CONFIG_FIELDS.contains(name)) + .sorted() + .toList(); + if (!sharedFields.isEmpty()) { + writer.openBlock("_SHARED_FIELDS: ClassVar[tuple[str, ...]] = (", ")", () -> { + writer.write("*$T._SHARED_FIELDS,", asyncAwsConfigSymbol); + for (var name : sharedFields) { + writer.write("$S,", name); + } + }); + writer.write(""); + } if (hasAuth) { writer.write("def set_auth_scheme(self, scheme: $T) -> None:", authSchemeSymbol); writer.indent(); diff --git a/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-958c7cbfa9004679b551de251e33329b.json b/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-958c7cbfa9004679b551de251e33329b.json new file mode 100644 index 000000000..83375d8e8 --- /dev/null +++ b/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-958c7cbfa9004679b551de251e33329b.json @@ -0,0 +1,4 @@ +{ + "type": "enhancement", + "description": "AWS configs now treat the generated `token` and `api_key` fields as secrets: they are hidden from `repr` and cannot be changed after resolution. Deep copies share the identity resolvers a generated config lists in `_SHARED_FIELDS`, like the credentials resolver. A `TokenIdentity` chain no longer logs or reports detected-but-unclaimed credential sources, and chain errors say \"identity providers\"." +} diff --git a/packages/smithy-aws-core/src/smithy_aws_core/config/aws_config.py b/packages/smithy-aws-core/src/smithy_aws_core/config/aws_config.py index 42782fb5f..1ca0e9a26 100644 --- a/packages/smithy-aws-core/src/smithy_aws_core/config/aws_config.py +++ b/packages/smithy-aws-core/src/smithy_aws_core/config/aws_config.py @@ -50,6 +50,20 @@ ] _CREDENTIAL_FIELDS = ("aws_access_key_id", "aws_secret_access_key", "aws_session_token") +"""The SigV4 credential fields, which must be overridden together.""" + +_SECRET_FIELDS = (*_CREDENTIAL_FIELDS, "token", "api_key") +"""Fields holding secrets: hidden from ``repr`` and frozen after resolution. + +``token`` and ``api_key`` are generated onto the configs of services with +``httpBearerAuth`` and ``httpApiKeyAuth``. +""" + +_SECRET_RESOLVERS = { + "token": "token_identity_resolver", + "api_key": "api_key_identity_resolver", +} +"""The identity resolver field that supplies each non-SigV4 secret dynamically.""" _BASE_FIELDS: dict[str, FieldSpec] = { @@ -112,6 +126,16 @@ class _AwsConfigBase: _FIELDS: ClassVar[dict[str, FieldSpec]] _RESOLVE_PREFIX: ClassVar[str] = "" + _SHARED_FIELDS: ClassVar[tuple[str, ...]] = ( + "aws_credentials_identity_resolver", + "transport", + "retry_strategy", + ) + """Fields a deep copy shares by identity instead of copying. + + These hold network clients, locks and shared caches. Generated configs + extend the tuple with the identity resolvers their auth schemes add. + """ _ctx: Any _sources: dict[str, ConfigSource] @@ -131,7 +155,7 @@ def __repr__(self) -> str: rendered = ", ".join( f"{f.name}={getattr(self, f.name)!r}" for f in fields(cast(Any, self)) - if f.repr and f.name not in _CREDENTIAL_FIELDS + if f.repr and f.name not in _SECRET_FIELDS ) return f"{type(self).__name__}({rendered})" @@ -161,17 +185,17 @@ def __setattr__(self, name: str, value: Any) -> None: if spec is not None and spec.converter is not None and value is not UNSET: value = spec.converter(value) - # Block override for credentials after resolution + # Block override for secrets after resolution if ( - name in _CREDENTIAL_FIELDS + name in _SECRET_FIELDS and hasattr(self, "_sources") and name in self._sources ): + resolver = _SECRET_RESOLVERS.get(name, "aws_credentials_identity_resolver") raise AttributeError( - f"'{name}' cannot be modified after resolution. Pass credentials " - f"to `{self._RESOLVE_PREFIX}{type(self).__name__}.resolve(...)`, or set " - "'aws_credentials_identity_resolver' to supply credentials " - "dynamically." + f"'{name}' cannot be modified after resolution. Pass it to " + f"`{self._RESOLVE_PREFIX}{type(self).__name__}.resolve(...)`, or set " + f"'{resolver}' to supply it dynamically." ) # Mark as override only if the field is in _FIELDS and was already resolved @@ -183,12 +207,8 @@ def __setattr__(self, name: str, value: Any) -> None: def __deepcopy__(self, memo: dict[int, Any]) -> Self: """Deep-copy the config while sharing resources that must not be duplicated.""" - for shared in ( - self.aws_credentials_identity_resolver, - self.transport, - self.retry_strategy, - ): - if shared is not None: + for name in self._SHARED_FIELDS: + if (shared := getattr(self, name, None)) is not None: memo[id(shared)] = shared new = self._create_instance() memo[id(self)] = new diff --git a/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/exceptions.py b/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/exceptions.py index 9e6e6856d..826a0fafc 100644 --- a/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/exceptions.py +++ b/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/exceptions.py @@ -54,7 +54,7 @@ def __init__( self.failures = failures self.unclaimed_sources = unclaimed_sources if not failures: - message = "No credential providers were configured to resolve an identity." + message = "No identity providers were configured to resolve an identity." else: attempted = "; ".join( f"{failure.provider_name}: {failure.error}" for failure in failures diff --git a/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/resolver.py b/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/resolver.py index 81828080c..a24d63d77 100644 --- a/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/resolver.py +++ b/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/resolver.py @@ -12,6 +12,7 @@ from smithy_http.interfaces import HTTPClient from ...config.merged_config import MergedConfig +from ..components import AWSCredentialsIdentity from .exceptions import ( IdentityChainConfigurationError, IdentityChainError, @@ -179,7 +180,14 @@ def _assemble( """Run each discovered provider's setup in chain order.""" _validate_providers(discovered_providers) providers = _sort_by_ordering(discovered_providers) - unclaimed_sources = _find_unclaimed_sources(discovered_providers) + # Standard slots describe credential sources, so only a credentials chain + # can report one as detected but unclaimed. A token chain would otherwise + # repeat the warning and suggest a package that cannot supply a token. + unclaimed_sources = ( + _find_unclaimed_sources(discovered_providers) + if identity_type is AWSCredentialsIdentity + else () + ) for provider in providers: setup.set_current_provider(provider) @@ -233,7 +241,7 @@ def _validate_providers(providers: Sequence[Any]) -> None: normalized_name = provider.name.casefold() if (previous := discovered_names.get(normalized_name)) is not None: raise IdentityChainConfigurationError( - f"Credential providers {type(previous).__name__} and " + f"Identity providers {type(previous).__name__} and " f"{type(provider).__name__} use the same name: {provider.name}." ) discovered_names[normalized_name] = provider @@ -242,7 +250,7 @@ def _validate_providers(providers: Sequence[Any]) -> None: 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"Identity providers {type(previous).__name__} and " f"{type(provider).__name__} both claim standard slot: " f"{ordering.slot.name}." ) diff --git a/packages/smithy-aws-core/tests/unit/config/test_resolver.py b/packages/smithy-aws-core/tests/unit/config/test_resolver.py index 7bf9c7df0..855e9af49 100644 --- a/packages/smithy-aws-core/tests/unit/config/test_resolver.py +++ b/packages/smithy-aws-core/tests/unit/config/test_resolver.py @@ -52,7 +52,9 @@ ) from smithy_core.aio.program import run_program_async from smithy_core.retries import StandardRetryStrategy +from smithy_http.aio.identity.token import AsyncStaticTokenResolver from smithy_http.aio.testing import AsyncMockHTTPClient +from smithy_http.identity import TokenIdentity from smithy_http.interfaces import HTTPRequestConfiguration @@ -525,12 +527,14 @@ def test_deepcopy_returns_same_instance(self): class TestConfigDeepCopy: - """Generated clients deep-copy the config on every operation call. - - The copy exists to keep plugin mutations scoped to a single call, so the - fields plugins write must be independent per copy. The resolution context - is read-only afterwards and is shared instead, which keeps the per-request - cost from scaling with the size of the caller's shared config files. + """``copy.deepcopy(config)`` must keep shared components by identity. + + Clients copy the config per call with a shallow copy (``_copy_config``), + but user code and test mocks may deep-copy it. A deep copy keeps the + fields plugins write independent per copy, while components that hold + network clients, locks, or shared caches are shared instead. The + resolution context is read-only afterwards and is shared too, which keeps + the copy cost from scaling with the size of the caller's config files. """ @pytest.mark.asyncio @@ -590,6 +594,20 @@ async def test_shared_resources_are_shared_by_identity(self): assert copy.aws_credentials_identity_resolver is resolver assert copy.retry_strategy is retry_strategy + @pytest.mark.asyncio + async def test_token_identity_resolver_is_shared_by_identity(self): + # Services with httpBearerAuth generate this field; a token resolver may + # hold a lock and a refresh state, so a copy must point at the same one. + with patch.dict(os.environ, {"AWS_REGION": "us-east-1"}, clear=True): + config = await _BearerServiceConfig.resolve(fs=NullFileSystem()) + resolver = AsyncStaticTokenResolver(TokenIdentity(token="t")) + config.token_identity_resolver = resolver + + copy = deepcopy(config) + + assert copy is not config + assert copy.token_identity_resolver is resolver + @pytest.mark.asyncio async def test_deepcopy_with_no_shared_resources(self): with patch.dict(os.environ, {"AWS_REGION": "us-east-1"}, clear=True): @@ -990,6 +1008,35 @@ class ServiceConfig(AsyncAwsConfig): assert "AKIAIOSFODNN7EXAMPLE" not in config_repr assert "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" not in config_repr + @pytest.mark.asyncio + async def test_repr_does_not_leak_bearer_token(self): + # The generated `token` field is a reusable secret like an access key. + with patch.dict(os.environ, {"AWS_REGION": "us-east-1"}, clear=True): + config = await _resolve_bearer_config(token="mF_9.B5f-4.1JqM") + assert config.token == "mF_9.B5f-4.1JqM" + assert "mF_9.B5f-4.1JqM" not in repr(config) + + @pytest.mark.asyncio + async def test_bearer_token_cannot_be_overridden_after_resolution(self): + with patch.dict(os.environ, {"AWS_REGION": "us-east-1"}, clear=True): + config = await _resolve_bearer_config(token="mF_9.B5f-4.1JqM") + with pytest.raises(AttributeError, match="token_identity_resolver"): + config.token = "other" + + @pytest.mark.asyncio + async def test_repr_does_not_leak_api_key(self): + with patch.dict(os.environ, {"AWS_REGION": "us-east-1"}, clear=True): + config = await _resolve_api_key_config(api_key="abcdef-123456") + assert config.api_key == "abcdef-123456" + assert "abcdef-123456" not in repr(config) + + @pytest.mark.asyncio + async def test_api_key_cannot_be_overridden_after_resolution(self): + with patch.dict(os.environ, {"AWS_REGION": "us-east-1"}, clear=True): + config = await _resolve_api_key_config(api_key="abcdef-123456") + with pytest.raises(AttributeError, match="api_key_identity_resolver"): + config.api_key = "other" + class TestIncodeStaticCredentialResolution: """Credentials must be resolved from a single source — never mixed.""" @@ -1105,6 +1152,54 @@ async def test_returns_unset_when_not_configured(self): assert result.value is UNSET +@dataclass(kw_only=True, repr=False, init=False) +class _BearerServiceConfig(AsyncAwsConfig): + """Mirrors the config codegen emits for services with the httpBearerAuth trait.""" + + token: str | None = None + token_identity_resolver: Any = None + + _FIELDS: ClassVar[dict[str, FieldSpec]] = { + "token": FieldSpec(default=None), + "token_identity_resolver": FieldSpec(default=None), + **AsyncAwsConfig._FIELDS, + } + _SHARED_FIELDS: ClassVar[tuple[str, ...]] = ( + *AsyncAwsConfig._SHARED_FIELDS, + "token_identity_resolver", + ) + + +async def _resolve_bearer_config(**overrides: Any) -> _BearerServiceConfig: + # Generated configs widen resolve()'s overrides for their own fields; this + # stand-in only widens the type. + widened: Any = overrides + return await _BearerServiceConfig.resolve(fs=NullFileSystem(), **widened) + + +@dataclass(kw_only=True, repr=False, init=False) +class _ApiKeyServiceConfig(AsyncAwsConfig): + """Mirrors the config codegen emits for services with the httpApiKeyAuth trait.""" + + api_key: str | None = None + api_key_identity_resolver: Any = None + + _FIELDS: ClassVar[dict[str, FieldSpec]] = { + "api_key": FieldSpec(default=None), + "api_key_identity_resolver": FieldSpec(default=None), + **AsyncAwsConfig._FIELDS, + } + _SHARED_FIELDS: ClassVar[tuple[str, ...]] = ( + *AsyncAwsConfig._SHARED_FIELDS, + "api_key_identity_resolver", + ) + + +async def _resolve_api_key_config(**overrides: Any) -> _ApiKeyServiceConfig: + widened: Any = overrides + return await _ApiKeyServiceConfig.resolve(fs=NullFileSystem(), **widened) + + @dataclass(kw_only=True, repr=False, init=False) class _ChecksumServiceConfig(AsyncAwsConfig): """Mirrors the config codegen emits for services with the httpChecksum trait.""" diff --git a/packages/smithy-aws-core/tests/unit/identity/chain/test_chain.py b/packages/smithy-aws-core/tests/unit/identity/chain/test_chain.py index 06b52ba1e..18e3310b5 100644 --- a/packages/smithy-aws-core/tests/unit/identity/chain/test_chain.py +++ b/packages/smithy-aws-core/tests/unit/identity/chain/test_chain.py @@ -27,6 +27,7 @@ ) from smithy_core.aio.interfaces.identity import AsyncIdentityResolver from smithy_core.exceptions import SmithyIdentityError +from smithy_http.identity import TokenIdentity class _StubProvider: @@ -111,6 +112,30 @@ def no_providers(group: str) -> tuple[Any, ...]: assert_type(chain, AsyncIdentityChain[AWSCredentialsIdentity]) +async def test_only_credentials_chains_report_unclaimed_sources( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + # A detected credential source with no installed provider is reported by a + # credentials chain, but a token chain neither warns about it nor suggests + # a package that cannot supply a token. + def no_providers(group: str) -> tuple[Any, ...]: + return () + + monkeypatch.setattr(chain_module, "_discover_providers", no_providers) + monkeypatch.setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", "http://localhost/creds") + + with caplog.at_level("WARNING"): + credentials_chain = await AsyncIdentityChain.create(AWSCredentialsIdentity) + token_chain = await AsyncIdentityChain.create(TokenIdentity) + + assert len(credentials_chain._unclaimed_sources) == 1 + assert token_chain._unclaimed_sources == () + assert sum("aws-credentials-http" in r.message for r in caplog.records) == 1 + with pytest.raises(IdentityChainError) as excinfo: + await token_chain.get_identity(properties={}) + assert "install" not in str(excinfo.value) + + def test_discovers_and_constructs_entry_point_providers( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -202,7 +227,7 @@ def test_validate_rejects_duplicate_names() -> None: with pytest.raises( IdentityChainConfigurationError, - match="Credential providers _StubProvider and _StubProvider use the " + match="Identity providers _StubProvider and _StubProvider use the " "same name: dup", ): resolver_module._validate_providers((first, second)) @@ -214,7 +239,7 @@ def test_validate_rejects_case_insensitive_duplicate_names() -> None: with pytest.raises( IdentityChainConfigurationError, - match="Credential providers _StubProvider and _StubProvider use the " + match="Identity providers _StubProvider and _StubProvider use the " "same name: duplicate", ): resolver_module._validate_providers((first, second)) @@ -226,7 +251,7 @@ def test_validate_rejects_duplicate_standard_slots() -> None: with pytest.raises( IdentityChainConfigurationError, - match="Credential providers _StubProvider and _StubProvider both claim " + match="Identity providers _StubProvider and _StubProvider both claim " "standard slot: ENVIRONMENT", ): resolver_module._validate_providers((first, second)) @@ -265,7 +290,7 @@ async def test_empty_chain_reports_no_configured_provider() -> None: with pytest.raises( IdentityChainError, - match="No credential providers were configured to resolve an identity", + match="No identity providers were configured to resolve an identity", ): await chain.get_identity(properties={}) diff --git a/scripts/api-snapshot/api-rex.json b/scripts/api-snapshot/api-rex.json index ca518746a..ca86cb67e 100644 --- a/scripts/api-snapshot/api-rex.json +++ b/scripts/api-snapshot/api-rex.json @@ -421,6 +421,7 @@ "StandardProvider": "rex-class" }, "smithy_aws_core.identity.chain.resolver": { + "AWSCredentialsIdentity": "rex-class", "After": "rex-class", "Before": "rex-class", "ChainIdentityProvider": "rex-protocol", From 9f13c7adef0fb77824306009454e07595306280f Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Sat, 21 Nov 2026 16:54:31 -0500 Subject: [PATCH 07/11] Replace the bearer token in mocked AWS clients so the HTTP mock never consults the token identity chain --- ...ment-0412602668954bf3a02615d668252267.json | 4 + .../src/smithy_test/_private/http_mock.py | 39 ++++++--- .../src/smithy_test/aio/http_mock.py | 5 +- .../smithy-test/src/smithy_test/http_mock.py | 3 +- .../tests/functional/aio/test_http_mock.py | 34 ++++++++ .../tests/functional/test_http_mock.py | 82 ++++++++++++++++++- scripts/api-snapshot/api-rex.json | 2 + scripts/verifications/import-cost.json | 4 +- 8 files changed, 158 insertions(+), 15 deletions(-) create mode 100644 packages/smithy-test/.changes/next-release/smithy-test-enhancement-0412602668954bf3a02615d668252267.json diff --git a/packages/smithy-test/.changes/next-release/smithy-test-enhancement-0412602668954bf3a02615d668252267.json b/packages/smithy-test/.changes/next-release/smithy-test-enhancement-0412602668954bf3a02615d668252267.json new file mode 100644 index 000000000..2e96f3693 --- /dev/null +++ b/packages/smithy-test/.changes/next-release/smithy-test-enhancement-0412602668954bf3a02615d668252267.json @@ -0,0 +1,4 @@ +{ + "type": "enhancement", + "description": "The HTTP mock now replaces the bearer token of AWS clients whose service uses bearer auth: `token` becomes `HTTP_MOCK` and `token_identity_resolver` a static resolver, so a mocked client never consults the default token identity chain." +} \ No newline at end of file diff --git a/packages/smithy-test/src/smithy_test/_private/http_mock.py b/packages/smithy-test/src/smithy_test/_private/http_mock.py index c5a77fabf..c5838dd85 100644 --- a/packages/smithy-test/src/smithy_test/_private/http_mock.py +++ b/packages/smithy-test/src/smithy_test/_private/http_mock.py @@ -10,6 +10,7 @@ from smithy_core._client import ClientBase from smithy_core.exceptions import SmithyError +from smithy_http.identity import TokenIdentity from smithy_http.interfaces import HTTPRequest MOCK_CREDENTIAL = "HTTP_MOCK" @@ -29,34 +30,37 @@ def take_over( client: ClientBase[Any], transport: MockTransport, wrap_invoke: Callable[[Callable[..., Any]], Callable[..., Any]], + static_token_resolver: Callable[..., Any], ) -> None: """Route the client's calls to the transport and replace its credentials. + :param static_token_resolver: Builds the sync or async static token resolver + that replaces an AWS bearer client's, from its ``identity`` keyword. :raises TypeError: If the client's internals aren't the ones this relies on. """ _check_client(client) # Typed as Any so instance attributes can shadow the client's methods. target: Any = client if target._setup_done: - _scrub(target._config, transport) + _scrub(target._config, transport, static_token_resolver) target._transport = transport elif target._config is not None: # Copied so the caller's config, possibly shared, keeps its own values. target._config = deepcopy(target._config) - _scrub(target._config, transport) + _scrub(target._config, transport, static_token_resolver) post_setup = target._post_setup build_call = target._build_call # Client and operation plugins may set credentials or a transport after this. def _post_setup(config: Any) -> Any: - _scrub(config, transport) + _scrub(config, transport, static_token_resolver) return post_setup(config) def _build_call( input: Any, operation: Any, *, config: Any, retry_strategy: Any ) -> Any: - _scrub(config, transport) + _scrub(config, transport, static_token_resolver) return build_call( input, operation, config=config, retry_strategy=retry_strategy ) @@ -114,12 +118,17 @@ def _check_config(config: Any) -> None: name = type(config).__name__ if not hasattr(config, "transport"): raise TypeError(f"{name} has no transport; it can't be mocked.") + # A bare `token` field may be a client context param; only a resolver marks bearer auth. + if hasattr(config, "token_identity_resolver") and not hasattr(config, "token"): + raise TypeError( + f"{name} has token_identity_resolver, but the mock needs the bearer auth " + "fields token and token_identity_resolver to replace them." + ) aws = ("aws_credentials_identity_resolver", *_CREDENTIAL_FIELDS) present = [f for f in aws if hasattr(config, f)] - if not present: - return - if len(present) < len(aws) or not callable( - getattr(config, "_static_credentials_resolver", None) + if present and ( + len(present) < len(aws) + or not callable(getattr(config, "_static_credentials_resolver", None)) ): raise TypeError( f"{name} has the AWS credential fields {present}, but the mock needs all " @@ -127,7 +136,9 @@ def _check_config(config: Any) -> None: ) -def _scrub(config: Any, transport: MockTransport) -> None: +def _scrub( + config: Any, transport: MockTransport, static_token_resolver: Callable[..., Any] +) -> None: _check_config(config) source_of = getattr(config, "source_of", None) # A default transport belongs to the config, so the mock closes it in its place. @@ -142,7 +153,8 @@ def _scrub(config: Any, transport: MockTransport) -> None: # Imported here so clients without AWS auth don't need smithy-aws-core. from smithy_aws_core.identity.components import AWSCredentialsIdentity - # CAUTION: bypasses AwsConfig.__setattr__, which locks resolved credentials. + # CAUTION: bypasses AwsConfig.__setattr__, which locks resolved secrets + # (the credential fields and, below, the token). for name in _CREDENTIAL_FIELDS: object.__setattr__(config, name, MOCK_CREDENTIAL) config.aws_credentials_identity_resolver = config._static_credentials_resolver( @@ -152,6 +164,13 @@ def _scrub(config: Any, transport: MockTransport) -> None: session_token=MOCK_CREDENTIAL, ) ) + # AWS services with bearer auth also resolve a token; replace it before + # the client's setup consults the default token identity chain. + if hasattr(config, "token_identity_resolver"): + object.__setattr__(config, "token", MOCK_CREDENTIAL) + config.token_identity_resolver = static_token_resolver( + identity=TokenIdentity(token=MOCK_CREDENTIAL) + ) def _subjects( diff --git a/packages/smithy-test/src/smithy_test/aio/http_mock.py b/packages/smithy-test/src/smithy_test/aio/http_mock.py index e85a6f34a..38630f574 100644 --- a/packages/smithy-test/src/smithy_test/aio/http_mock.py +++ b/packages/smithy-test/src/smithy_test/aio/http_mock.py @@ -13,6 +13,7 @@ from smithy_core.aio.types import AsyncBytesProvider from smithy_core.aio.utils import read_streaming_blob_async from smithy_http import HTTPResponse +from smithy_http.aio.identity.token import AsyncStaticTokenResolver from smithy_http.aio.interfaces import AsyncHTTPClient from smithy_http.aio.testing import AsyncMockHTTPClient from smithy_http.interfaces import HTTPRequest, HTTPRequestConfiguration @@ -35,7 +36,9 @@ async def mock_async[C](client: AsyncClient[C]) -> "AsyncHTTPMockController": ) controller = AsyncHTTPMockController() controller._capture = _AsyncMockTransport(controller) - take_over(client, controller._capture, _none_without_response) + take_over( + client, controller._capture, _none_without_response, AsyncStaticTokenResolver + ) return controller diff --git a/packages/smithy-test/src/smithy_test/http_mock.py b/packages/smithy-test/src/smithy_test/http_mock.py index a70e68129..48f90904d 100644 --- a/packages/smithy-test/src/smithy_test/http_mock.py +++ b/packages/smithy-test/src/smithy_test/http_mock.py @@ -11,6 +11,7 @@ from smithy_core.interfaces import AnyStreamingBlob from smithy_core.utils import read_streaming_blob from smithy_http import HTTPResponse +from smithy_http.identity.token import StaticTokenResolver from smithy_http.interfaces import HTTPClient, HTTPRequest, HTTPRequestConfiguration from smithy_http.testing.mockhttp import MockHTTPClient, MockHTTPClientBase @@ -46,7 +47,7 @@ def mock[C](client: Client[C]) -> "HTTPMockController": ) controller = HTTPMockController() controller._capture = _MockTransport(controller) - take_over(client, controller._capture, _none_without_response) + take_over(client, controller._capture, _none_without_response, StaticTokenResolver) return controller diff --git a/packages/smithy-test/tests/functional/aio/test_http_mock.py b/packages/smithy-test/tests/functional/aio/test_http_mock.py index fd8009a96..2e1e03028 100644 --- a/packages/smithy-test/tests/functional/aio/test_http_mock.py +++ b/packages/smithy-test/tests/functional/aio/test_http_mock.py @@ -1,5 +1,8 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 +from dataclasses import dataclass +from typing import Any, ClassVar + import pytest pytest.importorskip("restjson") @@ -8,6 +11,8 @@ from restjson.aio.config import AsyncRestJsonProtocolConfig from restjson.client import RestJsonProtocolClient from restjson.models import SimpleScalarPropertiesInput +from smithy_aws_core.config.types import FieldSpec +from smithy_http.aio.identity.token import AsyncStaticTokenResolver from smithy_test import HTTPMockError, HTTPMockMismatchError from smithy_test.aio import mock_async @@ -65,6 +70,35 @@ async def test_raises_on_exit_with_unmet_expectations() -> None: await client.simple_scalar_properties(SimpleScalarPropertiesInput()) +async def test_replaces_the_bearer_token() -> None: + @dataclass(kw_only=True, repr=False, init=False) + class BearerConfig(AsyncRestJsonProtocolConfig): + # The fields codegen adds to the config of a service with bearer auth. + token: str | None = None + token_identity_resolver: Any = None + + _FIELDS: ClassVar[dict[str, FieldSpec]] = { + "token": FieldSpec(default=None), + "token_identity_resolver": FieldSpec(default=None), + **AsyncRestJsonProtocolConfig._FIELDS, + } + + overrides: Any = {"token": "real"} + config = await BearerConfig.resolve(region="us-west-2", **overrides) + async with AsyncRestJsonProtocolClient(config) as client: + (await mock_async(client)).expect_request() + + await client.simple_scalar_properties(SimpleScalarPropertiesInput()) + + mocked: Any = client._config # pyright: ignore[reportPrivateUsage] + + assert config.token == "real" + assert mocked.token == "HTTP_MOCK" + assert isinstance(mocked.token_identity_resolver, AsyncStaticTokenResolver) + identity = await mocked.token_identity_resolver.get_identity(properties={}) + assert identity.token == "HTTP_MOCK" + + async def test_rejects_a_sync_client() -> None: with pytest.raises(TypeError, match=r"smithy_test\.mock\(\)"): await mock_async(RestJsonProtocolClient()) # type: ignore[arg-type] diff --git a/packages/smithy-test/tests/functional/test_http_mock.py b/packages/smithy-test/tests/functional/test_http_mock.py index b5e6b7df0..e7ae73163 100644 --- a/packages/smithy-test/tests/functional/test_http_mock.py +++ b/packages/smithy-test/tests/functional/test_http_mock.py @@ -1,8 +1,9 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 +from dataclasses import dataclass from io import BytesIO from types import SimpleNamespace -from typing import Any +from typing import Any, ClassVar import pytest @@ -16,7 +17,10 @@ SimpleScalarPropertiesInput, StreamingTraitsInput, ) +from smithy_aws_core.config.types import FieldSpec from smithy_core.utils import read_streaming_blob +from smithy_http.identity import TokenIdentity +from smithy_http.identity.token import StaticTokenResolver from smithy_http.urllib3 import Urllib3HTTPClient from smithy_test import HTTPMockError, HTTPMockMismatchError, mock @@ -178,6 +182,35 @@ def test_replaces_credentials_from_the_environment( _call(client) +def test_replaces_the_bearer_token() -> None: + @dataclass(kw_only=True, repr=False, init=False) + class BearerConfig(RestJsonProtocolConfig): + # The fields codegen adds to the config of a service with bearer auth. + token: str | None = None + token_identity_resolver: Any = None + + _FIELDS: ClassVar[dict[str, FieldSpec]] = { + "token": FieldSpec(default=None), + "token_identity_resolver": FieldSpec(default=None), + **RestJsonProtocolConfig._FIELDS, + } + + overrides: Any = {"token": "real"} + config = BearerConfig.resolve(region="us-west-2", **overrides) + client = RestJsonProtocolClient(config) + mock(client).expect_request() + + _call(client) + + assert config.token == "real" + mocked: Any = client._config # pyright: ignore[reportPrivateUsage] + assert mocked.token == "HTTP_MOCK" + assert isinstance(mocked.token_identity_resolver, StaticTokenResolver) + assert ( + mocked.token_identity_resolver.get_identity(properties={}).token == "HTTP_MOCK" + ) + + def test_takes_over_a_client_after_setup() -> None: client = _client() client._ensure_setup() # pyright: ignore[reportPrivateUsage] @@ -254,6 +287,53 @@ def _build_call(self, input: Any, operation: Any, **kwargs: Any) -> Any: mock(Changed(RestJsonProtocolConfig.resolve(region="us-west-2"))) +def test_leaves_the_token_of_a_client_without_aws_auth_alone() -> None: + # Only AWS clients resolve a token through a default chain; a generic + # bearer client's token is its own business. + resolver = StaticTokenResolver(identity=TokenIdentity(token="real")) + client = _client() + client._config = SimpleNamespace( # pyright: ignore[reportPrivateUsage, reportAttributeAccessIssue] + transport=None, token="real", token_identity_resolver=resolver + ) + + mock(client) + + # The mock copies the config, so compare what the resolver yields. + mocked: Any = client._config # pyright: ignore[reportPrivateUsage] + assert mocked.token == "real" + assert mocked.token_identity_resolver.get_identity(properties={}).token == "real" + + +def test_adds_no_token_to_a_client_without_bearer_auth() -> None: + client = _client() + mock(client).expect_request() + + _call(client) + + assert not hasattr(client._config, "token") # pyright: ignore[reportPrivateUsage] + + +def test_rejects_a_config_with_partial_bearer_fields() -> None: + client = _client() + client._config = SimpleNamespace( # pyright: ignore[reportPrivateUsage, reportAttributeAccessIssue] + transport=None, token_identity_resolver=None + ) + + with pytest.raises(TypeError, match="bearer auth fields"): + mock(client) + + +def test_accepts_a_config_whose_token_is_not_bearer_auth() -> None: + client = _client() + client._config = SimpleNamespace( # pyright: ignore[reportPrivateUsage, reportAttributeAccessIssue] + transport=None, token="a context param" + ) + + mock(client) + + assert client._config.token == "a context param" # pyright: ignore[reportPrivateUsage] + + def test_rejects_a_config_with_partial_aws_credentials() -> None: client = _client() client._config = SimpleNamespace( # pyright: ignore[reportPrivateUsage, reportAttributeAccessIssue] diff --git a/scripts/api-snapshot/api-rex.json b/scripts/api-snapshot/api-rex.json index ca86cb67e..fe772fb90 100644 --- a/scripts/api-snapshot/api-rex.json +++ b/scripts/api-snapshot/api-rex.json @@ -1464,6 +1464,7 @@ "AsyncClient": "rex-class[async]", "AsyncHTTPClient": "rex-protocol[async]", "AsyncMockHTTPClient": "rex-class[async]", + "AsyncStaticTokenResolver": "rex-class[async]", "HTTPMockController": "rex-class", "HTTPMockError": "rex-exception", "HTTPRequest": "rex-protocol", @@ -1484,6 +1485,7 @@ "MockHTTPClientBase": "rex-class", "NoResponse": "rex-exception", "SmithyError": "rex-exception", + "StaticTokenResolver": "rex-class", "mismatches": "rex-function", "read_streaming_blob": "rex-function", "take_over": "rex-function" diff --git a/scripts/verifications/import-cost.json b/scripts/verifications/import-cost.json index badb97e0a..b62044d96 100644 --- a/scripts/verifications/import-cost.json +++ b/scripts/verifications/import-cost.json @@ -17,8 +17,8 @@ "smithy_json (all public modules)": 21, "smithy_python": 1, "smithy_python (all public modules)": 34, - "smithy_test": 44, - "smithy_test (all public modules)": 60, + "smithy_test": 46, + "smithy_test (all public modules)": 64, "smithy_xml": 20, "smithy_xml (all public modules)": 20 } From 76e6e934a0798cf51a59e11a8ef13593cd3205e5 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Tue, 24 Nov 2026 14:26:14 -0500 Subject: [PATCH 08/11] Python codegen: generate bearer token auth and the AWS token chain --- .../.smithy-python-manifest.json | 4 +- .../src/awsjson10_client/aio/client.py | 21 +- .../src/awsjson10_client/client.py | 21 +- .../.smithy-python-manifest.json | 4 +- .../src/awsjson11_client/aio/client.py | 21 +- .../src/awsjson11_client/client.py | 21 +- .../.smithy-python-manifest.json | 14 +- .../src/features_client/_private/schemas.py | 213 ++++++++++-------- .../src/features_client/aio/client.py | 72 +++++- .../src/features_client/aio/config.py | 29 ++- .../src/features_client/client.py | 72 +++++- .../src/features_client/config.py | 29 ++- .../src/features_client/models.py | 10 +- .../src/features_client/models.pyi | 29 +++ .../.smithy-python-manifest.json | 4 +- .../aio/client.py | 21 +- .../client.py | 21 +- .../.smithy-python-manifest.json | 4 +- .../src/restjson_client/aio/client.py | 21 +- .../src/restjson_client/client.py | 21 +- designs/codegen/client.md | 58 +++-- ...ture-4d0cd3317e65481aa51eaba1182703e6.json | 4 + .../smithy-python/src/smithy_python/_auth.py | 61 ++++- .../src/smithy_python/aws/__init__.py | 12 +- .../src/smithy_python/aws/_config.py | 16 ++ .../src/smithy_python/aws/_identity.py | 203 +++++++++++++++++ .../src/smithy_python/aws/_sigv4.py | 148 ------------ .../tests/unit/test_client_generation.py | 120 +++++++++- scripts/api-snapshot/api-rex.json | 2 +- .../codegen-output-py/models/features.json | 43 +++- .../codegen-output-py/models/features.smithy | 16 +- .../tests/test_client_snapshots.py | 30 +++ 32 files changed, 997 insertions(+), 368 deletions(-) create mode 100644 packages/smithy-python/.changes/next-release/smithy-python-feature-4d0cd3317e65481aa51eaba1182703e6.json create mode 100644 packages/smithy-python/src/smithy_python/aws/_identity.py delete mode 100644 packages/smithy-python/src/smithy_python/aws/_sigv4.py diff --git a/codegen-output-py/aws-json-1-0-client/.smithy-python-manifest.json b/codegen-output-py/aws-json-1-0-client/.smithy-python-manifest.json index 82fd61f50..64b6a131a 100644 --- a/codegen-output-py/aws-json-1-0-client/.smithy-python-manifest.json +++ b/codegen-output-py/aws-json-1-0-client/.smithy-python-manifest.json @@ -7,10 +7,10 @@ "src/awsjson10_client/_private/endpoints.py": "7d515fe771678e82ddbe07798d6b7e48c25c6c9bec19cec9318deb0bc5064ead", "src/awsjson10_client/_private/schemas.py": "0e254d9f031858bb9894d35adbceb708ad3d77db5030ce91ff0c4e150ba04657", "src/awsjson10_client/aio/__init__.py": "e2072bcfa8185b3654fd315c0b92205140c5d22ddfc4ac50c80bb9089bda8d75", - "src/awsjson10_client/aio/client.py": "1ae4e9910e15f60579ee8b15f7337e90596e27be8932ef9cdeb977f364601370", + "src/awsjson10_client/aio/client.py": "e5a9933715572cd735b9447993fdbb975432934afa5b1847081fddf176b1dd76", "src/awsjson10_client/aio/config.py": "c0f6a8506afd000e8de4697e02faa34280e0a0a4b68366009311739e50ec6c4d", "src/awsjson10_client/aio/user_agent.py": "8e17f04fa14a0e1721e55beefbfa640c838b53be7c231f020d2ff3ed2f63f20a", - "src/awsjson10_client/client.py": "e6bd7e342676f5f5a71c38c02174b595afbd413ac337c377813a4e2c9bcfd843", + "src/awsjson10_client/client.py": "83c8b4af80b1fe435058fcd9b7f088cd8e7ae9340bbadad8844bf111dc3c8584", "src/awsjson10_client/config.py": "024eb5f174b588e67ebf9a272930eba6fcc3b1a181d677dade0823b7c2da7773", "src/awsjson10_client/models.py": "d184b6f8288bd787f23c6f119a0a1259e1a468fb487c3d9c2c710825d390636a", "src/awsjson10_client/models.pyi": "fc5bc36883b8b0851132826edfa5b51dbf7a2023e94b357dccac383878ff9d02", diff --git a/codegen-output-py/aws-json-1-0-client/src/awsjson10_client/aio/client.py b/codegen-output-py/aws-json-1-0-client/src/awsjson10_client/aio/client.py index 0086b0743..5418a166a 100644 --- a/codegen-output-py/aws-json-1-0-client/src/awsjson10_client/aio/client.py +++ b/codegen-output-py/aws-json-1-0-client/src/awsjson10_client/aio/client.py @@ -3,6 +3,7 @@ from typing import Unpack, cast, overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -599,13 +600,7 @@ async def _new_config(self) -> AsyncJSONRPC10Config: async def _post_setup(self, config: AsyncJSONRPC10Config) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -613,3 +608,15 @@ async def _post_setup(self, config: AsyncJSONRPC10Config) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncJSONRPC10Config + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output-py/aws-json-1-0-client/src/awsjson10_client/client.py b/codegen-output-py/aws-json-1-0-client/src/awsjson10_client/client.py index cf4618233..c8881c101 100644 --- a/codegen-output-py/aws-json-1-0-client/src/awsjson10_client/client.py +++ b/codegen-output-py/aws-json-1-0-client/src/awsjson10_client/client.py @@ -2,6 +2,7 @@ from typing import Unpack, cast, overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -599,13 +600,7 @@ def _new_config(self) -> JSONRPC10Config: def _post_setup(self, config: JSONRPC10Config) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -613,3 +608,15 @@ def _post_setup(self, config: JSONRPC10Config) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: JSONRPC10Config + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output-py/aws-json-1-1-client/.smithy-python-manifest.json b/codegen-output-py/aws-json-1-1-client/.smithy-python-manifest.json index 67874fe98..1321e8197 100644 --- a/codegen-output-py/aws-json-1-1-client/.smithy-python-manifest.json +++ b/codegen-output-py/aws-json-1-1-client/.smithy-python-manifest.json @@ -7,10 +7,10 @@ "src/awsjson11_client/_private/endpoints.py": "7d515fe771678e82ddbe07798d6b7e48c25c6c9bec19cec9318deb0bc5064ead", "src/awsjson11_client/_private/schemas.py": "39f6fcaed62547b27d149c3a2eb7c591b05d140eb4b63520b5c49ecf30e17c99", "src/awsjson11_client/aio/__init__.py": "d4cd42353a6f80219be93c41d60c27b752e90e223bf4f37d0162c9456fdb48e5", - "src/awsjson11_client/aio/client.py": "3c7d63086da2b7116bfc51db85bdb593d799c3826ae83caeee3832cde4881063", + "src/awsjson11_client/aio/client.py": "3de510765d05962670983789ce6ec42ee4eb36f656cd994949c15ac433d66239", "src/awsjson11_client/aio/config.py": "5f170845cae3ea3fa70ae7cf4958f9e7dcb4ef0b82d51b540a8eba5e6f1e230d", "src/awsjson11_client/aio/user_agent.py": "61bfd1fdbc339bc5b696baee392aa7428d6cd663c950c64d0658e7d188c53762", - "src/awsjson11_client/client.py": "d41809f6631a8587e487ee590e3a1cbf1f22e87a968387ed70b09dc1c1edd3f6", + "src/awsjson11_client/client.py": "d7ee41e828e88fc5dfa142d8394e329a5dc5a11bd5fedd71e069815a4656c803", "src/awsjson11_client/config.py": "d9b26a4f7004249b76ea30b2470bc652f2789e05ad42807fc4184bc49bc55864", "src/awsjson11_client/models.py": "3e666b01d5b536476b4d0b990b8f39a73bd9479484bc931e08f684fbeae68f73", "src/awsjson11_client/models.pyi": "a018f0bbb86538b80a7a59a84ebba899a773a18a3a38a905d1a14501a76ae736", diff --git a/codegen-output-py/aws-json-1-1-client/src/awsjson11_client/aio/client.py b/codegen-output-py/aws-json-1-1-client/src/awsjson11_client/aio/client.py index cbacd9fd5..bf5dc5397 100644 --- a/codegen-output-py/aws-json-1-1-client/src/awsjson11_client/aio/client.py +++ b/codegen-output-py/aws-json-1-1-client/src/awsjson11_client/aio/client.py @@ -3,6 +3,7 @@ from typing import Unpack, cast, overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -657,13 +658,7 @@ async def _new_config(self) -> AsyncJsonProtocolConfig: async def _post_setup(self, config: AsyncJsonProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -671,3 +666,15 @@ async def _post_setup(self, config: AsyncJsonProtocolConfig) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncJsonProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output-py/aws-json-1-1-client/src/awsjson11_client/client.py b/codegen-output-py/aws-json-1-1-client/src/awsjson11_client/client.py index db5c7d975..7d9ecc9e2 100644 --- a/codegen-output-py/aws-json-1-1-client/src/awsjson11_client/client.py +++ b/codegen-output-py/aws-json-1-1-client/src/awsjson11_client/client.py @@ -2,6 +2,7 @@ from typing import Unpack, cast, overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -657,13 +658,7 @@ def _new_config(self) -> JsonProtocolConfig: def _post_setup(self, config: JsonProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -671,3 +666,15 @@ def _post_setup(self, config: JsonProtocolConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: JsonProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output-py/features-client/.smithy-python-manifest.json b/codegen-output-py/features-client/.smithy-python-manifest.json index 432f81009..21d35ec5c 100644 --- a/codegen-output-py/features-client/.smithy-python-manifest.json +++ b/codegen-output-py/features-client/.smithy-python-manifest.json @@ -5,15 +5,15 @@ "src/features_client/__init__.py": "32592f5725712e19c306d0c817040e64c67203ae420e3fac2a05301915b742aa", "src/features_client/_private/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "src/features_client/_private/endpoints.py": "90e1bc94c3ca6338b495b94870e7b1e433c1c2da064e336a85ad94616953916a", - "src/features_client/_private/schemas.py": "14264d5a32b434bb249f350f18f2960450df6210a3233aee0fa7cbed06aa7d06", + "src/features_client/_private/schemas.py": "3b5718a8bf522eb2fc05e998147c50ebd9ff6a390cdc88e1004a2a93f3f46d9e", "src/features_client/aio/__init__.py": "2d6c204a7bbceeed5b175fe0df922722d341068027b29287cfdcbb9cb29403af", - "src/features_client/aio/client.py": "38bc118ef83c9f40081c35d3bf5d80d55af5f50d0a6842d8e90b2ee08535fad1", - "src/features_client/aio/config.py": "96baec406f19b8641e301fa89088e83a3cdde57a8ae14a270fd16ffe25e70214", + "src/features_client/aio/client.py": "45fc4676b92661d9d484842c5277dbbdb9925e655cef9b3588af564ce8a46969", + "src/features_client/aio/config.py": "0b8ab6e0648b479de7a9befe6742fbe72865bee2fab11a4533fbede79516e99a", "src/features_client/aio/user_agent.py": "05cbb5932a96cb83d55ece172f9b9b5b8aeb625782140647e177d5d5cbd18dd5", - "src/features_client/client.py": "4fc44b151779df58e8263324eaf287a09a4fe23c5972914e0965306a05587f52", - "src/features_client/config.py": "0380227b86fc8409c15e381894be6396fdaa00cdd9a76c7da968537f855adb68", - "src/features_client/models.py": "b9e33ac885f9c8c1c9eda86cffb407fb2fbdea61a461484f0e489580173d7de3", - "src/features_client/models.pyi": "9aad31a601154c7a2a156830b5d647f3a4b100859c649bffe26124609e7258f9", + "src/features_client/client.py": "88b136c9f9bbad718905b130fcdc9bb4546af5ec7c220cda20287bbafad5c1a9", + "src/features_client/config.py": "8852d5679ab46123361451298ec619ee6506c6d0488fad2f940a29972e1cc755", + "src/features_client/models.py": "80f36c9213b2bfe0d2b17e54d9cc15a22c2d322cdccbfd1325582cc0cf2a35f9", + "src/features_client/models.pyi": "100ce17b968597321b338bc2ca06525cd3ffdf6a64807ea45217ad77f87265d8", "src/features_client/py.typed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "src/features_client/user_agent.py": "6d7e1477fa0123330b26d750070dcb49afe76bd14baa8bbe4b66a3d28e7ad75f", "tests/test_endpoints.py": "395f805a2889159097487f70f8ee3d6bfb83403ec370dc97e56e5e9304ba93a9" diff --git a/codegen-output-py/features-client/src/features_client/_private/schemas.py b/codegen-output-py/features-client/src/features_client/_private/schemas.py index 09b79b95e..d9beefde4 100644 --- a/codegen-output-py/features-client/src/features_client/_private/schemas.py +++ b/codegen-output-py/features-client/src/features_client/_private/schemas.py @@ -3,57 +3,62 @@ from smithy_core._schema_compact import StaticOperationSchema, StaticSchema n0 = "example.features" -_s0 = "GetThingInput" +_s0 = "GetNoteInput" _s1 = "smithy.synthetic#originalShapeId" -_s2 = "example.features#GetThingInput" +_s2 = "example.features#GetNoteInput" _s3 = "smithy.api#input" -_s4 = "name" -_s5 = "GetThingOutput" -_s6 = "example.features#GetThingOutput" +_s4 = "id" +_s5 = "GetNoteOutput" +_s6 = "example.features#GetNoteOutput" _s7 = "smithy.api#output" -_s8 = "value" -_s9 = "ListNotesInput" -_s10 = "example.features#ListNotesInput" -_s11 = "nextToken" -_s12 = "pageSize" -_s13 = "NoteList" -_s14 = "member" -_s15 = "ListNotesOutput" -_s16 = "example.features#ListNotesOutput" -_s17 = "items" -_s18 = "PluginNames" -_s19 = "PutNoteInput" -_s20 = "example.features#PutNoteInput" -_s21 = "text" -_s22 = "PutNoteOutput" -_s23 = "example.features#PutNoteOutput" -_s24 = "id" -_s25 = "ThingTag" -_s26 = "key" -_s27 = "PutThingInput" -_s28 = "example.features#PutThingInput" -_s29 = "smithy.rules#contextParam" -_s30 = "smithy.api#required" -_s31 = "tag" -_s32 = "plugins" -_s33 = "EchoInput" -_s34 = "smithy.api#Unit" -_s35 = "EchoOutput" -_s36 = "PingInput" -_s37 = "PingOutput" -_s38 = "PutThingOutput" -_s39 = "Echo" -_s40 = "GetThing" -_s41 = "ListNotes" -_s42 = "smithy.rules#staticContextParams" -_s43 = "Ping" -_s44 = "PutNote" -_s45 = "PutThing" -_s46 = "FieldNotes" -_s47 = "aws.api#service" -_s48 = "smithy.protocols#rpcv2Cbor" +_s8 = "text" +_s9 = "GetThingInput" +_s10 = "example.features#GetThingInput" +_s11 = "name" +_s12 = "GetThingOutput" +_s13 = "example.features#GetThingOutput" +_s14 = "value" +_s15 = "ListNotesInput" +_s16 = "example.features#ListNotesInput" +_s17 = "nextToken" +_s18 = "pageSize" +_s19 = "NoteList" +_s20 = "member" +_s21 = "ListNotesOutput" +_s22 = "example.features#ListNotesOutput" +_s23 = "items" +_s24 = "PluginNames" +_s25 = "PutNoteInput" +_s26 = "example.features#PutNoteInput" +_s27 = "PutNoteOutput" +_s28 = "example.features#PutNoteOutput" +_s29 = "ThingTag" +_s30 = "key" +_s31 = "PutThingInput" +_s32 = "example.features#PutThingInput" +_s33 = "smithy.rules#contextParam" +_s34 = "smithy.api#required" +_s35 = "tag" +_s36 = "plugins" +_s37 = "EchoInput" +_s38 = "smithy.api#Unit" +_s39 = "EchoOutput" +_s40 = "PingInput" +_s41 = "PingOutput" +_s42 = "PutThingOutput" +_s43 = "Echo" +_s44 = "GetNote" +_s45 = "GetThing" +_s46 = "ListNotes" +_s47 = "smithy.rules#staticContextParams" +_s48 = "Ping" +_s49 = "PutNote" +_s50 = "PutThing" +_s51 = "FieldNotes" +_s52 = "aws.api#service" +_s53 = "smithy.protocols#rpcv2Cbor" -GET_THING_INPUT: StaticSchema = ( +GET_NOTE_INPUT: StaticSchema = ( 18, n0, _s0, @@ -62,7 +67,7 @@ ((3, 0),), ) -GET_THING_OUTPUT: StaticSchema = ( +GET_NOTE_OUTPUT: StaticSchema = ( 18, n0, _s5, @@ -71,77 +76,95 @@ ((3, 0),), ) -LIST_NOTES_INPUT: StaticSchema = ( +GET_THING_INPUT: StaticSchema = ( 18, n0, _s9, {_s1: _s10, _s3: None}, - (_s11, _s12), + (_s11,), + ((3, 0),), +) + +GET_THING_OUTPUT: StaticSchema = ( + 18, + n0, + _s12, + {_s1: _s13, _s7: None}, + (_s14,), + ((3, 0),), +) + +LIST_NOTES_INPUT: StaticSchema = ( + 18, + n0, + _s15, + {_s1: _s16, _s3: None}, + (_s17, _s18), ((3, 0), (7, 0)), ) NOTE_LIST: StaticSchema = ( 16, n0, - _s13, + _s19, 0, - (_s14,), + (_s20,), ((3, 0),), ) LIST_NOTES_OUTPUT: StaticSchema = ( 18, n0, - _s15, - {_s1: _s16, _s7: None}, - (_s17, _s11), + _s21, + {_s1: _s22, _s7: None}, + (_s23, _s17), ((NOTE_LIST, 0), (3, 0)), ) PLUGIN_NAMES: StaticSchema = ( 16, n0, - _s18, + _s24, 0, - (_s14,), + (_s20,), ((3, 0),), ) PUT_NOTE_INPUT: StaticSchema = ( 18, n0, - _s19, - {_s1: _s20, _s3: None}, - (_s21,), + _s25, + {_s1: _s26, _s3: None}, + (_s8,), ((3, 0),), ) PUT_NOTE_OUTPUT: StaticSchema = ( 18, n0, - _s22, - {_s1: _s23, _s7: None}, - (_s24,), + _s27, + {_s1: _s28, _s7: None}, + (_s4,), ((3, 0),), ) THING_TAG: StaticSchema = ( 18, n0, - _s25, + _s29, 0, - (_s26, _s8), + (_s30, _s14), ((3, 0), (3, 0)), ) PUT_THING_INPUT: StaticSchema = ( 18, n0, - _s27, - {_s1: _s28, _s3: None}, - (_s4, _s31, _s32), + _s31, + {_s1: _s32, _s3: None}, + (_s11, _s35, _s36), ( - (3, {_s29: MappingProxyType({"name": "Name"}), _s30: None}), + (3, {_s33: MappingProxyType({"name": "Name"}), _s34: None}), (THING_TAG, 0), (PLUGIN_NAMES, 0), ), @@ -150,52 +173,62 @@ ECHO_INPUT: StaticSchema = ( 18, n0, - _s33, - {_s1: _s34, _s3: None}, + _s37, + {_s1: _s38, _s3: None}, ) ECHO_OUTPUT: StaticSchema = ( 18, n0, - _s35, - {_s1: _s34, _s7: None}, + _s39, + {_s1: _s38, _s7: None}, ) PING_INPUT: StaticSchema = ( 18, n0, - _s36, - {_s1: _s34, _s3: None}, + _s40, + {_s1: _s38, _s3: None}, ) PING_OUTPUT: StaticSchema = ( 18, n0, - _s37, - {_s1: _s34, _s7: None}, + _s41, + {_s1: _s38, _s7: None}, ) PUT_THING_OUTPUT: StaticSchema = ( 18, n0, - _s38, - {_s1: _s34, _s7: None}, + _s42, + {_s1: _s38, _s7: None}, ) ECHO: StaticOperationSchema = ( 23, n0, - _s39, + _s43, 0, ECHO_INPUT, ECHO_OUTPUT, (), ) +GET_NOTE: StaticOperationSchema = ( + 23, + n0, + _s44, + 0, + GET_NOTE_INPUT, + GET_NOTE_OUTPUT, + (), +) + GET_THING: StaticOperationSchema = ( 23, n0, - _s40, + _s45, 0, GET_THING_INPUT, GET_THING_OUTPUT, @@ -205,8 +238,8 @@ LIST_NOTES: StaticOperationSchema = ( 23, n0, - _s41, - {_s42: MappingProxyType({"Kind": MappingProxyType({"value": "list"})})}, + _s46, + {_s47: MappingProxyType({"Kind": MappingProxyType({"value": "list"})})}, LIST_NOTES_INPUT, LIST_NOTES_OUTPUT, (), @@ -215,8 +248,8 @@ PING: StaticOperationSchema = ( 23, n0, - _s43, - {_s42: MappingProxyType({"Kind": MappingProxyType({"value": "ping"})})}, + _s48, + {_s47: MappingProxyType({"Kind": MappingProxyType({"value": "ping"})})}, PING_INPUT, PING_OUTPUT, (), @@ -225,7 +258,7 @@ PUT_NOTE: StaticOperationSchema = ( 23, n0, - _s44, + _s49, 0, PUT_NOTE_INPUT, PUT_NOTE_OUTPUT, @@ -235,8 +268,8 @@ PUT_THING: StaticOperationSchema = ( 23, n0, - _s45, - {_s42: MappingProxyType({"Kind": MappingProxyType({"value": "put"})})}, + _s50, + {_s47: MappingProxyType({"Kind": MappingProxyType({"value": "put"})})}, PUT_THING_INPUT, PUT_THING_OUTPUT, (), @@ -245,6 +278,6 @@ FIELD_NOTES: StaticSchema = ( 21, n0, - _s46, - {_s47: MappingProxyType({"sdkId": "Field Notes"}), _s48: None}, + _s51, + {_s52: MappingProxyType({"sdkId": "Field Notes"}), _s53: None}, ) diff --git a/codegen-output-py/features-client/src/features_client/aio/client.py b/codegen-output-py/features-client/src/features_client/aio/client.py index c9a2a9ba7..0bd4c8e33 100644 --- a/codegen-output-py/features-client/src/features_client/aio/client.py +++ b/codegen-output-py/features-client/src/features_client/aio/client.py @@ -3,11 +3,14 @@ from typing import Unpack, cast, overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient from smithy_core.aio.pagination import AsyncItemPaginator +from smithy_http.aio.identity.token import AsyncStaticTokenResolver from smithy_http.aio.interfaces import AsyncHTTPClient +from smithy_http.identity import TokenIdentity from smithy_http.plugins import user_agent_plugin from features_client import models @@ -21,7 +24,7 @@ class AsyncFieldNotesClient(AsyncClient[AsyncFieldNotesConfig]): Its endpoint rules read config, input, and operation values. Its operations - use SigV4, API key auth, optional auth, and no auth. + use SigV4, bearer token auth, API key auth, optional auth, and no auth. """ _client_plugins = (aws_user_agent_plugin, user_agent_plugin) @@ -60,6 +63,40 @@ async def echo( plugins, ) + @overload + async def get_note( + self, + request: models.GetNoteInput | models.GetNoteInputDict, + /, + *, + plugins: list[Plugin] | None = None, + ) -> models.GetNoteOutput: ... + + @overload + async def get_note( + self, + /, + *, + plugins: list[Plugin] | None = None, + **kwargs: Unpack[models.GetNoteInputDict], + ) -> models.GetNoteOutput: + """ + Reads a note, with a bearer token. + + :param plugins: Callables that change the configuration for this call + only. + """ + + async def get_note( + self, /, *args: object, plugins: list[Plugin] | None = None, **kwargs: object + ) -> models.GetNoteOutput: + return await self._invoke( + self._select_input(models.GET_NOTE, args, kwargs), + models.GET_NOTE, + [], + plugins, + ) + @overload async def get_thing( self, @@ -293,13 +330,7 @@ async def _new_config(self) -> AsyncFieldNotesConfig: async def _post_setup(self, config: AsyncFieldNotesConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -307,3 +338,28 @@ async def _post_setup(self, config: AsyncFieldNotesConfig) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + if config.token_identity_resolver is None: + if config.token is not None: + config.token_identity_resolver = AsyncStaticTokenResolver() + else: + config_file, profile_name = await self._profile_overrides(config) + config.token_identity_resolver = await AsyncIdentityChain.create( + TokenIdentity, + config_file=config_file, + profile_name=profile_name, + region_override=config.region, + http_client=cast(AsyncHTTPClient | None, config.transport), + ) + + async def _profile_overrides( + self, config: AsyncFieldNotesConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output-py/features-client/src/features_client/aio/config.py b/codegen-output-py/features-client/src/features_client/aio/config.py index 8548e60d0..dd87c1100 100644 --- a/codegen-output-py/features-client/src/features_client/aio/config.py +++ b/codegen-output-py/features-client/src/features_client/aio/config.py @@ -31,9 +31,15 @@ from smithy_core.traits import APIKeyLocation from smithy_http.aio.aiohttp import AIOHTTPClient from smithy_http.aio.auth.apikey import AsyncAPIKeyAuthScheme +from smithy_http.aio.auth.bearer import AsyncBearerAuthScheme from smithy_http.aio.identity.apikey import AsyncAPIKeyIdentityResolver from smithy_http.aio.protocols import AsyncRpcV2CborClientProtocol -from smithy_http.identity import APIKeyIdentity, APIKeyIdentityProperties +from smithy_http.identity import ( + APIKeyIdentity, + APIKeyIdentityProperties, + TokenIdentity, + TokenIdentityProperties, +) from features_client._private.endpoints import BDD from features_client._private.schemas import FIELD_NOTES @@ -59,6 +65,10 @@ class _AsyncFieldNotesConfigOverrides(AsyncAwsConfigOverrides, total=False): api_key_identity_resolver: ( AsyncIdentityResolver[APIKeyIdentity, APIKeyIdentityProperties] | None ) + token: str | None + token_identity_resolver: ( + AsyncIdentityResolver[TokenIdentity, TokenIdentityProperties] | None + ) stage: str | None force_path_style: bool | None use_fips_endpoint: bool | None @@ -93,6 +103,14 @@ class AsyncFieldNotesConfig(AsyncAwsConfig): ) = None "Resolves the API key." + token: str | None = None + "The bearer token to send along with requests." + + token_identity_resolver: ( + AsyncIdentityResolver[TokenIdentity, TokenIdentityProperties] | None + ) = None + "Resolves the bearer token." + stage: str | None = None "The deployment stage." @@ -124,6 +142,7 @@ class AsyncFieldNotesConfig(AsyncAwsConfig): location=APIKeyLocation.HEADER, scheme="ApiKey", ), + ShapeID("smithy.api#httpBearerAuth"): AsyncBearerAuthScheme(), } ), "auth_scheme_resolver": FieldSpec(default_factory=DefaultAuthResolver), @@ -131,6 +150,8 @@ class AsyncFieldNotesConfig(AsyncAwsConfig): "api_key_identity_resolver": FieldSpec( default_factory=lambda: AsyncAPIKeyIdentityResolver() ), + "token": FieldSpec(default=None), + "token_identity_resolver": FieldSpec(default=None), "stage": FieldSpec(default=None), "force_path_style": FieldSpec(default=None), "use_fips_endpoint": FieldSpec( @@ -139,6 +160,12 @@ class AsyncFieldNotesConfig(AsyncAwsConfig): "transport": FieldSpec(default_factory=lambda: AIOHTTPClient()), } + _SHARED_FIELDS: ClassVar[tuple[str, ...]] = ( + *AsyncAwsConfig._SHARED_FIELDS, + "api_key_identity_resolver", + "token_identity_resolver", + ) + def set_auth_scheme(self, scheme: AsyncAuthScheme[Any, Any, Any, Any]) -> None: "Set an auth scheme under its scheme ID." auth_schemes = dict(self.auth_schemes or {}) diff --git a/codegen-output-py/features-client/src/features_client/client.py b/codegen-output-py/features-client/src/features_client/client.py index ef9fa0404..05b3dc270 100644 --- a/codegen-output-py/features-client/src/features_client/client.py +++ b/codegen-output-py/features-client/src/features_client/client.py @@ -2,11 +2,14 @@ from typing import Unpack, cast, overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.client import Client from smithy_core.pagination import ItemPaginator +from smithy_http.identity import TokenIdentity +from smithy_http.identity.token import StaticTokenResolver from smithy_http.interfaces import HTTPClient from smithy_http.plugins import user_agent_plugin @@ -21,7 +24,7 @@ class FieldNotesClient(Client[FieldNotesConfig]): Its endpoint rules read config, input, and operation values. Its operations - use SigV4, API key auth, optional auth, and no auth. + use SigV4, bearer token auth, API key auth, optional auth, and no auth. """ _client_plugins = (aws_user_agent_plugin, user_agent_plugin) @@ -60,6 +63,40 @@ def echo( plugins, ) + @overload + def get_note( + self, + request: models.GetNoteInput | models.GetNoteInputDict, + /, + *, + plugins: list[Plugin] | None = None, + ) -> models.GetNoteOutput: ... + + @overload + def get_note( + self, + /, + *, + plugins: list[Plugin] | None = None, + **kwargs: Unpack[models.GetNoteInputDict], + ) -> models.GetNoteOutput: + """ + Reads a note, with a bearer token. + + :param plugins: Callables that change the configuration for this call + only. + """ + + def get_note( + self, /, *args: object, plugins: list[Plugin] | None = None, **kwargs: object + ) -> models.GetNoteOutput: + return self._invoke( + self._select_input(models.GET_NOTE, args, kwargs), + models.GET_NOTE, + [], + plugins, + ) + @overload def get_thing( self, @@ -293,13 +330,7 @@ def _new_config(self) -> FieldNotesConfig: def _post_setup(self, config: FieldNotesConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -307,3 +338,28 @@ def _post_setup(self, config: FieldNotesConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + if config.token_identity_resolver is None: + if config.token is not None: + config.token_identity_resolver = StaticTokenResolver() + else: + config_file, profile_name = self._profile_overrides(config) + config.token_identity_resolver = IdentityChain.create( + TokenIdentity, + config_file=config_file, + profile_name=profile_name, + region_override=config.region, + http_client=cast(HTTPClient | None, config.transport), + ) + + def _profile_overrides( + self, config: FieldNotesConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output-py/features-client/src/features_client/config.py b/codegen-output-py/features-client/src/features_client/config.py index b663696d5..93565fb41 100644 --- a/codegen-output-py/features-client/src/features_client/config.py +++ b/codegen-output-py/features-client/src/features_client/config.py @@ -25,7 +25,13 @@ from smithy_core.shapes import ShapeID from smithy_core.traits import APIKeyLocation from smithy_http.auth.apikey import APIKeyAuthScheme -from smithy_http.identity import APIKeyIdentity, APIKeyIdentityProperties +from smithy_http.auth.bearer import BearerAuthScheme +from smithy_http.identity import ( + APIKeyIdentity, + APIKeyIdentityProperties, + TokenIdentity, + TokenIdentityProperties, +) from smithy_http.identity.apikey import APIKeyIdentityResolver from smithy_http.protocols import RpcV2CborClientProtocol from smithy_http.urllib3 import Urllib3HTTPClient @@ -54,6 +60,10 @@ class _FieldNotesConfigOverrides(AwsConfigOverrides, total=False): api_key_identity_resolver: ( IdentityResolver[APIKeyIdentity, APIKeyIdentityProperties] | None ) + token: str | None + token_identity_resolver: ( + IdentityResolver[TokenIdentity, TokenIdentityProperties] | None + ) stage: str | None force_path_style: bool | None use_fips_endpoint: bool | None @@ -88,6 +98,14 @@ class FieldNotesConfig(AwsConfig): ) = None "Resolves the API key." + token: str | None = None + "The bearer token to send along with requests." + + token_identity_resolver: ( + IdentityResolver[TokenIdentity, TokenIdentityProperties] | None + ) = None + "Resolves the bearer token." + stage: str | None = None "The deployment stage." @@ -119,6 +137,7 @@ class FieldNotesConfig(AwsConfig): location=APIKeyLocation.HEADER, scheme="ApiKey", ), + ShapeID("smithy.api#httpBearerAuth"): BearerAuthScheme(), } ), "auth_scheme_resolver": FieldSpec(default_factory=DefaultAuthResolver), @@ -126,6 +145,8 @@ class FieldNotesConfig(AwsConfig): "api_key_identity_resolver": FieldSpec( default_factory=lambda: APIKeyIdentityResolver() ), + "token": FieldSpec(default=None), + "token_identity_resolver": FieldSpec(default=None), "stage": FieldSpec(default=None), "force_path_style": FieldSpec(default=None), "use_fips_endpoint": FieldSpec( @@ -134,6 +155,12 @@ class FieldNotesConfig(AwsConfig): "transport": FieldSpec(default_factory=lambda: Urllib3HTTPClient()), } + _SHARED_FIELDS: ClassVar[tuple[str, ...]] = ( + *AwsConfig._SHARED_FIELDS, + "api_key_identity_resolver", + "token_identity_resolver", + ) + def set_auth_scheme(self, scheme: AuthScheme[Any, Any, Any, Any]) -> None: "Set an auth scheme under its scheme ID." auth_schemes = dict(self.auth_schemes or {}) diff --git a/codegen-output-py/features-client/src/features_client/models.py b/codegen-output-py/features-client/src/features_client/models.py index 9a55b6f41..d2a37fbeb 100644 --- a/codegen-output-py/features-client/src/features_client/models.py +++ b/codegen-output-py/features-client/src/features_client/models.py @@ -14,6 +14,8 @@ class ServiceError(ModeledError): _MODEL_INDEX = { + "GetNoteInput": "GET_NOTE_INPUT", + "GetNoteOutput": "GET_NOTE_OUTPUT", "GetThingInput": "GET_THING_INPUT", "GetThingOutput": "GET_THING_OUTPUT", "ListNotesInput": "LIST_NOTES_INPUT", @@ -38,6 +40,10 @@ class ServiceError(ModeledError): (), ("smithy.api#httpApiKeyAuth", "smithy.api#noAuth"), ), + "GET_NOTE": ( + (), + ("smithy.api#httpBearerAuth",), + ), "GET_THING": ( (), ("smithy.api#httpApiKeyAuth",), @@ -52,7 +58,7 @@ class ServiceError(ModeledError): ), "PUT_NOTE": ( (), - ("aws.auth#sigv4", "smithy.api#httpApiKeyAuth"), + ("aws.auth#sigv4", "smithy.api#httpApiKeyAuth", "smithy.api#httpBearerAuth"), ), "PUT_THING": ( (), @@ -73,6 +79,8 @@ class ServiceError(ModeledError): { "EchoInput", "EchoOutput", + "GetNoteInput", + "GetNoteOutput", "GetThingInput", "GetThingOutput", "ListNotesInput", diff --git a/codegen-output-py/features-client/src/features_client/models.pyi b/codegen-output-py/features-client/src/features_client/models.pyi index 5589bcfce..f3ef16d3c 100644 --- a/codegen-output-py/features-client/src/features_client/models.pyi +++ b/codegen-output-py/features-client/src/features_client/models.pyi @@ -10,6 +10,7 @@ from smithy_core.serializers import ShapeSerializer __all__ = [ "ECHO", + "GET_NOTE", "GET_THING", "LIST_NOTES", "PING", @@ -17,6 +18,8 @@ __all__ = [ "PUT_THING", "EchoInput", "EchoOutput", + "GetNoteInput", + "GetNoteOutput", "GetThingInput", "GetThingOutput", "ListNotesInput", @@ -45,6 +48,31 @@ class ServiceError(ModeledError): implicit, and shared exception types. """ +@dataclass(kw_only=True) +class GetNoteInput(_SerdeShape): + "Dataclass for GetNoteInput structure." + + id: str | None = ... + +class GetNoteInputDict(TypedDict, total=False): + "Dictionary form of `GetNoteInput`." + + id: str | None + +@dataclass(kw_only=True) +class GetNoteOutput(_SerdeShape): + "Dataclass for GetNoteOutput structure." + + text: str | None = ... + response_metadata: ResponseMetadata = ... + """ + Metadata about the response that produced this output. + + Use this to recover the request identifiers a service's support team + needs in order to investigate a call. Members of the metadata are + individually optional. + """ + @dataclass(kw_only=True) class GetThingInput(_SerdeShape): "Dataclass for GetThingInput structure." @@ -205,6 +233,7 @@ class PutThingOutput(_SerdeShape): """ ECHO: APIOperation[EchoInput, EchoOutput] +GET_NOTE: APIOperation[GetNoteInput, GetNoteOutput] GET_THING: APIOperation[GetThingInput, GetThingOutput] LIST_NOTES: APIOperation[ListNotesInput, ListNotesOutput] PING: APIOperation[PingInput, PingOutput] diff --git a/codegen-output-py/query-compatible-aws-json-1-0-client/.smithy-python-manifest.json b/codegen-output-py/query-compatible-aws-json-1-0-client/.smithy-python-manifest.json index 5eaf7a56b..5189d6679 100644 --- a/codegen-output-py/query-compatible-aws-json-1-0-client/.smithy-python-manifest.json +++ b/codegen-output-py/query-compatible-aws-json-1-0-client/.smithy-python-manifest.json @@ -7,10 +7,10 @@ "src/querycompatible_awsjson10_client/_private/endpoints.py": "7d515fe771678e82ddbe07798d6b7e48c25c6c9bec19cec9318deb0bc5064ead", "src/querycompatible_awsjson10_client/_private/schemas.py": "cc88f0e7ad5c190d8c8dfeef89c45c73bfffd54e6710bec6e693ba8753f37f55", "src/querycompatible_awsjson10_client/aio/__init__.py": "c147a9d60c2a26446fffc16eb7c4452299b7ec7c8de0cb55207a8f5e0189893e", - "src/querycompatible_awsjson10_client/aio/client.py": "a901f0976d7071bc02e3f73812ad89178b828bfa332bb2fd83b5852d64dc4664", + "src/querycompatible_awsjson10_client/aio/client.py": "dc6c58cf38a4e5271764575405d9b37a78adb5e828943b1e05a05ebbe3bc45dd", "src/querycompatible_awsjson10_client/aio/config.py": "c50946907f8489db780b579c2d1d4815a827b649c754745d61da765eec34523c", "src/querycompatible_awsjson10_client/aio/user_agent.py": "3f53ccc91866f16bc80ea835a16fef5593be909ec62938f10d7b433494b8671a", - "src/querycompatible_awsjson10_client/client.py": "e99bc0002072f720baced05fdf598793406d8ec3a730b81fb954895f60864fce", + "src/querycompatible_awsjson10_client/client.py": "87f4c63d7a60c31883fb18b4bf58af06918028a6791e27154d0adcb0c06c6fb3", "src/querycompatible_awsjson10_client/config.py": "fbafbc4431b0c279f45561193b035ab09f9521913fcfa4076a5db52ec3f4f4ca", "src/querycompatible_awsjson10_client/models.py": "143e8b8644ac97c317c07d9a31f7975364cb3c952601a640755a4568e31e2d3d", "src/querycompatible_awsjson10_client/models.pyi": "16a51e56007a1bbb95969fc2aa0ecb3044196c2c4d4234420d01e7e06844d9ac", diff --git a/codegen-output-py/query-compatible-aws-json-1-0-client/src/querycompatible_awsjson10_client/aio/client.py b/codegen-output-py/query-compatible-aws-json-1-0-client/src/querycompatible_awsjson10_client/aio/client.py index e2bf28cb1..1566530d0 100644 --- a/codegen-output-py/query-compatible-aws-json-1-0-client/src/querycompatible_awsjson10_client/aio/client.py +++ b/codegen-output-py/query-compatible-aws-json-1-0-client/src/querycompatible_awsjson10_client/aio/client.py @@ -3,6 +3,7 @@ from typing import Unpack, cast, overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -64,13 +65,7 @@ async def _new_config(self) -> AsyncQueryCompatibleJSONRPC10Config: async def _post_setup(self, config: AsyncQueryCompatibleJSONRPC10Config) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -78,3 +73,15 @@ async def _post_setup(self, config: AsyncQueryCompatibleJSONRPC10Config) -> None region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncQueryCompatibleJSONRPC10Config + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output-py/query-compatible-aws-json-1-0-client/src/querycompatible_awsjson10_client/client.py b/codegen-output-py/query-compatible-aws-json-1-0-client/src/querycompatible_awsjson10_client/client.py index 15679131c..fe0fd373d 100644 --- a/codegen-output-py/query-compatible-aws-json-1-0-client/src/querycompatible_awsjson10_client/client.py +++ b/codegen-output-py/query-compatible-aws-json-1-0-client/src/querycompatible_awsjson10_client/client.py @@ -2,6 +2,7 @@ from typing import Unpack, cast, overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -62,13 +63,7 @@ def _new_config(self) -> QueryCompatibleJSONRPC10Config: def _post_setup(self, config: QueryCompatibleJSONRPC10Config) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -76,3 +71,15 @@ def _post_setup(self, config: QueryCompatibleJSONRPC10Config) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: QueryCompatibleJSONRPC10Config + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output-py/rest-json-1-client/.smithy-python-manifest.json b/codegen-output-py/rest-json-1-client/.smithy-python-manifest.json index 6d79ca97e..ef3e31f47 100644 --- a/codegen-output-py/rest-json-1-client/.smithy-python-manifest.json +++ b/codegen-output-py/rest-json-1-client/.smithy-python-manifest.json @@ -11,10 +11,10 @@ "src/restjson_client/_private/schemas_2.py": "7af39a649f958d781c314de6dc5d0a1c1e6bc22cf46983ba834aabb461312b83", "src/restjson_client/_private/schemas_3.py": "1edc1721aac792698841b83674d1306b373dd42bfd575f45df07da0ba34d882a", "src/restjson_client/aio/__init__.py": "473fc51fef9cf762ab73c2de65aabd8036c7d440c7884bf017e4a02ad7b41ec5", - "src/restjson_client/aio/client.py": "d9ae4ab21316b30caf6594f67e557b5f79f470a707c7b9b50ee66f995b380eb9", + "src/restjson_client/aio/client.py": "299f9dd1c01b1a351975e027a6d96be974e8924b86189f3651c66393f29aec46", "src/restjson_client/aio/config.py": "68ea9b1478ac71564640bb1b6983672436fae6a96e48dd1195ff9a5e26b5ee20", "src/restjson_client/aio/user_agent.py": "8e6fb66d21c2c5e59ecf31b59db9566fb217d3f95a1af63ddcb47e637613afb9", - "src/restjson_client/client.py": "6bb2663462fa8d84569bac0ca483e828a9096b5f241467defd362014864f3744", + "src/restjson_client/client.py": "05c2217c6ae4c82ac519784e01c85cf4ee30b89ea062d0976511ece0b35963ed", "src/restjson_client/config.py": "c77b84c655fa53efceff14cf46569e0872dc10999d55bdd7e0a92fc6bf8cb0ed", "src/restjson_client/models.py": "2ef5c492a6cf5922580732d19f28df88821bf8eb2c4ffaa8339ddc2d3c9cf52d", "src/restjson_client/models.pyi": "22ffb750b64a6640e5eac1c38a3d52465d4aab181669d59b626a5cf33171f0d2", diff --git a/codegen-output-py/rest-json-1-client/src/restjson_client/aio/client.py b/codegen-output-py/rest-json-1-client/src/restjson_client/aio/client.py index 052017b44..d6a4b1471 100644 --- a/codegen-output-py/rest-json-1-client/src/restjson_client/aio/client.py +++ b/codegen-output-py/rest-json-1-client/src/restjson_client/aio/client.py @@ -3,6 +3,7 @@ from typing import Unpack, cast, overload from smithy_aws_core.aio.identity.chain import AsyncIdentityChain +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.components import AWSCredentialsIdentity from smithy_core.aio.client import AsyncClient @@ -3701,13 +3702,7 @@ async def _new_config(self) -> AsyncRestJsonProtocolConfig: async def _post_setup(self, config: AsyncRestJsonProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = await config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = await self._profile_overrides(config) config.aws_credentials_identity_resolver = await AsyncIdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -3715,3 +3710,15 @@ async def _post_setup(self, config: AsyncRestJsonProtocolConfig) -> None: region_override=config.region, http_client=cast(AsyncHTTPClient | None, config.transport), ) + + async def _profile_overrides( + self, config: AsyncRestJsonProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = await config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/codegen-output-py/rest-json-1-client/src/restjson_client/client.py b/codegen-output-py/rest-json-1-client/src/restjson_client/client.py index bac042e3a..c69dce721 100644 --- a/codegen-output-py/rest-json-1-client/src/restjson_client/client.py +++ b/codegen-output-py/rest-json-1-client/src/restjson_client/client.py @@ -2,6 +2,7 @@ from typing import Unpack, cast, overload +from smithy_aws_core.config.merged_config import MergedConfig from smithy_aws_core.config.types import ConfigSource from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_aws_core.identity.components import AWSCredentialsIdentity @@ -3701,13 +3702,7 @@ def _new_config(self) -> RestJsonProtocolConfig: def _post_setup(self, config: RestJsonProtocolConfig) -> None: if config.aws_credentials_identity_resolver is None: - config_context = config.resolution_context() - config_file = None - profile_name = None - if config_context is not None: - config_file = config_context.parsed_profiles() - if config_context.profile_source is ConfigSource.OVERRIDE: - profile_name = config_context.profile_name + config_file, profile_name = self._profile_overrides(config) config.aws_credentials_identity_resolver = IdentityChain.create( AWSCredentialsIdentity, config_file=config_file, @@ -3715,3 +3710,15 @@ def _post_setup(self, config: RestJsonProtocolConfig) -> None: region_override=config.region, http_client=cast(HTTPClient | None, config.transport), ) + + def _profile_overrides( + self, config: RestJsonProtocolConfig + ) -> tuple[MergedConfig | None, str | None]: + config_context = config.resolution_context() + config_file = None + profile_name = None + if config_context is not None: + config_file = config_context.parsed_profiles() + if config_context.profile_source is ConfigSource.OVERRIDE: + profile_name = config_context.profile_name + return config_file, profile_name diff --git a/designs/codegen/client.md b/designs/codegen/client.md index 7566e85c9..c53673f8c 100644 --- a/designs/codegen/client.md +++ b/designs/codegen/client.md @@ -283,16 +283,19 @@ dependency group adds `pytest`, `pytest-asyncio`, and `smithy-test`. An auth registry maps auth trait IDs to auth contributions. A contribution provides the sync and async runtime auth schemes, builds each from the service's auth trait value, and declares the config fields its identity resolver reads. -`smithy.api#httpApiKeyAuth` is built in: +`smithy.api#httpApiKeyAuth` and `smithy.api#httpBearerAuth` are built in: | Part | Sync | Async | | --- | --- | --- | -| Scheme | `APIKeyAuthScheme` | `AsyncAPIKeyAuthScheme` | +| API key scheme | `APIKeyAuthScheme` | `AsyncAPIKeyAuthScheme` | | `api_key_identity_resolver` default | `APIKeyIdentityResolver` | `AsyncAPIKeyIdentityResolver` | +| Bearer scheme | `BearerAuthScheme` | `AsyncBearerAuthScheme` | +| `token_identity_resolver` default | `StaticTokenResolver` | `AsyncStaticTokenResolver` | -The scheme takes the trait's `name`, `in`, and `scheme`. Both configs also get -an `api_key` field. The fields, the `auth_schemes` default, and a -`set_auth_scheme` method match the Java generator's. +The API key scheme takes the trait's `name`, `in`, and `scheme`, and both +configs also get an `api_key` field. The bearer scheme takes no arguments, and +both configs also get a `token` field. The fields, the `auth_schemes` default, +and a `set_auth_scheme` method match the Java generator's. Both configs keep `DefaultAuthResolver`. It returns each operation's effective auth scheme IDs in order, and the runtime signs with the first one in @@ -345,6 +348,8 @@ config: `endpoint_resolver`, `protocol`, `auth_schemes`, `auth_scheme_resolver`, auth scheme fields, and client context fields. `endpoint_uri` also reads `AWS_ENDPOINT_URL_` and the profile's service section. +* Identity resolvers an auth scheme adds join the config's `_SHARED_FIELDS`, so + a deep copy of the config shares them like the base credentials resolver. * A typed `Unpack` overrides dictionary covers the added fields. * Clients apply `aws_user_agent_plugin`, which adds `UserAgentInterceptor` with the SDK ID, the package version, `sdk_ua_app_id`, and @@ -353,17 +358,26 @@ config: The generated package depends on `smithy-aws-core`. A client context field may not take an `AwsConfig` field name. -`AwsSigV4Integration` matches a service with both `aws.api#service` and -`aws.auth#sigv4`, and follows the Java generator: - -* Both configs default `auth_schemes` to `SigV4AuthScheme` or - `AsyncSigV4AuthScheme` for the trait's signing name. `AwsConfig` already - declares the credential fields and `aws_credentials_identity_resolver`. -* A client's `_post_setup` sets the default AWS credentials chain when the - config has no credentials resolver. The chain reads the config's profile, - region, and transport. +`AwsIdentityIntegration` matches a service that has `aws.api#service` and at +least one of `aws.auth#sigv4` and `smithy.api#httpBearerAuth`, and follows the +Java generator: + +* Both configs default `auth_schemes` to one scheme per auth trait the service + has: `SigV4AuthScheme` (`AsyncSigV4AuthScheme`) for the trait's signing name, + and `BearerAuthScheme` (`AsyncBearerAuthScheme`). `AwsConfig` already declares + the credential fields and `aws_credentials_identity_resolver`. The bearer + fields are the generic generator's `token` and `token_identity_resolver`, + except that the resolver has no default. +* A client's `_post_setup` fills each resolver the config leaves unset. The + credentials resolver becomes the default AWS credentials chain. The token + resolver becomes the static resolver when the config has a `token`, and + otherwise the default AWS token provider chain. Both chains read the config's + region and transport, and take the parsed config file and profile override + from a `_profile_overrides` helper. * A service with `aws.auth#sigv4` but not `aws.api#service` fails generation, - because SigV4 needs the AWS config. + because SigV4 needs the AWS config. A service with `smithy.api#httpBearerAuth` + but not `aws.api#service` gets the generic generator's bearer auth, whose + resolver defaults to the static resolver. S3 signing properties come later with S3 support. @@ -445,9 +459,10 @@ runtime metadata. It covers `self`, `plugins`, defaults, and idempotency tokens. ## Supported Features The generator supports non-streaming RPCv2 CBOR and RPCv2 JSON operations that -are unsigned or use API key auth or SigV4, and whose endpoint rules use the -standard library. Models that require other auth schemes or event or data -streams fail generation with a diagnostic naming the operation and feature. +are unsigned or use API key auth, bearer token auth, or SigV4, and whose +endpoint rules use the standard library. Models that require other auth +schemes or event or data streams fail generation with a diagnostic naming the +operation and feature. Authentication and endpoint extension points are provider-neutral. AWS config resolution, the AWS user agent, SigV4, and AWS endpoint functions are AWS @@ -473,6 +488,7 @@ model assembled by Smithy with its ruleset compiled by `CompileBdd`: | Endpoint rules | Client context fields, `SDK::Endpoint`, `AWS::Region`, `AWS::UseFIPS`, `aws.partition`, an endpoint auth scheme, an input context parameter, and static context parameters | | Endpoint tests | Rules and client cases, run by the snapshot tests | | SigV4 | The service's default auth | +| Bearer token auth | An operation with `@auth([httpBearerAuth])` | | API key auth | Operations with `@auth([httpApiKeyAuth])`, one also `@optionalAuth` | | No auth | Operations with `@auth([])` | | AWS config | `aws.api#service`, with the SDK ID `Field Notes` | @@ -481,8 +497,10 @@ Its tests check which requests carry the API key and that a missing key fails the call. They resolve the endpoint from `AWS_ENDPOINT_URL_` and from a profile, check the AWS user agent, check that unknown fields and direct construction fail, and check SigV4 signing with configured credentials and with -credentials from the default chain. The core config is covered by the -`rpcv2-cbor-client` and `rpcv2-json-client` snapshots and by unit tests. +credentials from the default chain. They check that a configured token is sent +as a bearer token and that, without one, the token provider chain is consulted. +The core config is covered by the `rpcv2-cbor-client` and `rpcv2-json-client` +snapshots and by unit tests. Client snapshots sit alongside the types snapshots and cover the provider-neutral RPCv2 CBOR and RPCv2 JSON projections. Checks cover deterministic diff --git a/packages/smithy-python/.changes/next-release/smithy-python-feature-4d0cd3317e65481aa51eaba1182703e6.json b/packages/smithy-python/.changes/next-release/smithy-python-feature-4d0cd3317e65481aa51eaba1182703e6.json new file mode 100644 index 000000000..19fe0aca8 --- /dev/null +++ b/packages/smithy-python/.changes/next-release/smithy-python-feature-4d0cd3317e65481aa51eaba1182703e6.json @@ -0,0 +1,4 @@ +{ + "type": "feature", + "description": "Generate clients for services with `httpBearerAuth`. Configs get `token` and `token_identity_resolver` fields and default to the bearer token auth scheme. AWS clients fall back to the default AWS token provider chain when the config has no token, and share the identity resolvers their auth schemes add across deep copies." +} diff --git a/packages/smithy-python/src/smithy_python/_auth.py b/packages/smithy-python/src/smithy_python/_auth.py index 8bc8937cc..57d269700 100644 --- a/packages/smithy-python/src/smithy_python/_auth.py +++ b/packages/smithy-python/src/smithy_python/_auth.py @@ -107,7 +107,7 @@ def _quote(value: str) -> str: _API_KEY_LOCATION: Final = _core("APIKeyLocation", "traits") _API_KEY_IDENTITY: Final = _http("APIKeyIdentity", "identity") _API_KEY_IDENTITY_PROPERTIES: Final = _http("APIKeyIdentityProperties", "identity") -_IDENTITY_ARGUMENTS: Final = ( +_API_KEY_ARGUMENTS: Final = ( "[", _API_KEY_IDENTITY, ", ", @@ -136,12 +136,12 @@ def _quote(value: str) -> str: name="api_key_identity_resolver", annotation=( _core("IdentityResolver", "interfaces.identity"), - *_IDENTITY_ARGUMENTS, + *_API_KEY_ARGUMENTS, " | None", ), async_annotation=( _core("AsyncIdentityResolver", "aio.interfaces.identity"), - *_IDENTITY_ARGUMENTS, + *_API_KEY_ARGUMENTS, " | None", ), documentation="Resolves the API key.", @@ -155,7 +155,60 @@ def _quote(value: str) -> str: ) """API key auth, from the ``smithy.api#httpApiKeyAuth`` trait.""" +_TOKEN_IDENTITY: Final = _http("TokenIdentity", "identity") +_TOKEN_IDENTITY_PROPERTIES: Final = _http("TokenIdentityProperties", "identity") +_TOKEN_ARGUMENTS: Final = ( + "[", + _TOKEN_IDENTITY, + ", ", + _TOKEN_IDENTITY_PROPERTIES, + "]", +) + +TOKEN_IDENTITY_RESOLVER: Final = ConfigField( + name="token_identity_resolver", + annotation=( + _core("IdentityResolver", "interfaces.identity"), + *_TOKEN_ARGUMENTS, + " | None", + ), + async_annotation=( + _core("AsyncIdentityResolver", "aio.interfaces.identity"), + *_TOKEN_ARGUMENTS, + " | None", + ), + documentation="Resolves the bearer token.", + default=(_http("StaticTokenResolver", "identity.token"), "()"), + async_default=(_http("AsyncStaticTokenResolver", "aio.identity.token"), "()"), +) +"""The bearer token resolver field, defaulting to the static resolver.""" + +HTTP_BEARER_AUTH: Final = AuthContribution( + scheme_id=_model.ShapeId("smithy.api", "httpBearerAuth"), + # The trait has no parameters, so the scheme takes none. + scheme=lambda trait: (_http("BearerAuthScheme", "auth.bearer"), "()"), + async_scheme=lambda trait: ( + _http("AsyncBearerAuthScheme", "aio.auth.bearer"), + "()", + ), + fields=( + ConfigField( + name="token", + annotation=("str | None",), + async_annotation=("str | None",), + documentation="The bearer token to send along with requests.", + ), + TOKEN_IDENTITY_RESOLVER, + ), +) +"""Bearer token auth, from the ``smithy.api#httpBearerAuth`` trait.""" + DEFAULT_AUTH_SCHEMES: Final[Mapping[_model.ShapeId, AuthContribution]] = ( - MappingProxyType({HTTP_API_KEY_AUTH.scheme_id: HTTP_API_KEY_AUTH}) + MappingProxyType( + { + HTTP_API_KEY_AUTH.scheme_id: HTTP_API_KEY_AUTH, + HTTP_BEARER_AUTH.scheme_id: HTTP_BEARER_AUTH, + } + ) ) """The auth schemes generated clients support, by auth trait ID.""" diff --git a/packages/smithy-python/src/smithy_python/aws/__init__.py b/packages/smithy-python/src/smithy_python/aws/__init__.py index 653f1a2f2..75e702915 100644 --- a/packages/smithy-python/src/smithy_python/aws/__init__.py +++ b/packages/smithy-python/src/smithy_python/aws/__init__.py @@ -5,8 +5,10 @@ A service with the ``aws.api#service`` trait gets clients named for its SDK ID and configs that resolve from the environment and shared config files. Its clients also send the AWS user agent. A service with the ``aws.auth#sigv4`` trait also gets SigV4 -auth and the default AWS credentials chain. AWS services, and services whose rules -use AWS functions or built-ins, resolve endpoints with the AWS rules extension. +auth and the default AWS credentials chain, and one with ``smithy.api#httpBearerAuth`` +gets bearer auth and the default AWS token provider chain. AWS services, and +services whose rules use AWS functions or built-ins, resolve endpoints with the +AWS rules extension. Clients may also use the AWS protocols ``aws.protocols#restJson1``, ``awsJson1_0`` and ``awsJson1_1``. """ @@ -18,8 +20,8 @@ from ._config import AwsConfigIntegration from ._dependencies import SMITHY_AWS_CORE from ._endpoints import AwsEndpointsIntegration +from ._identity import AwsIdentityIntegration from ._protocols import AWS_JSON_10, AWS_JSON_11, AWS_PROTOCOLS, REST_JSON -from ._sigv4 import AwsSigV4Integration __all__ = [ "AWS_INTEGRATIONS", @@ -30,12 +32,12 @@ "SMITHY_AWS_CORE", "AwsConfigIntegration", "AwsEndpointsIntegration", - "AwsSigV4Integration", + "AwsIdentityIntegration", ] AWS_INTEGRATIONS: Final = ( AwsConfigIntegration(), - AwsSigV4Integration(), + AwsIdentityIntegration(), AwsEndpointsIntegration(), ) """The integrations AWS services get, in order.""" diff --git a/packages/smithy-python/src/smithy_python/aws/_config.py b/packages/smithy-python/src/smithy_python/aws/_config.py index 7624c72cc..fd355acaa 100644 --- a/packages/smithy-python/src/smithy_python/aws/_config.py +++ b/packages/smithy-python/src/smithy_python/aws/_config.py @@ -301,6 +301,22 @@ def _write_config(writer: PythonWriter, config: ConfigPlan) -> None: "()),", ) writer.line("}") + # Identity resolvers added by auth schemes hold caches and locks, so a + # deep copy of the config must share them like the base resolvers. + shared = sorted( + field.name + for field in auth_fields + if field.name.endswith("_identity_resolver") + and field.name not in _BASE_FIELDS + ) + if shared: + writer.line() + writer.line("_SHARED_FIELDS: ", _CLASS_VAR, "[tuple[str, ...]] = (") + with writer.indent(): + writer.line("*", base, "._SHARED_FIELDS,") + for name in shared: + writer.line(_quote(name), ",") + writer.line(")") if config.auth_schemes: writer.line() writer.line( diff --git a/packages/smithy-python/src/smithy_python/aws/_identity.py b/packages/smithy-python/src/smithy_python/aws/_identity.py new file mode 100644 index 000000000..257da8a5c --- /dev/null +++ b/packages/smithy-python/src/smithy_python/aws/_identity.py @@ -0,0 +1,203 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""SigV4 and bearer token auth, with the default AWS identity chains.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from dataclasses import replace +from typing import TYPE_CHECKING, Final + +from .. import exceptions as _exceptions +from .. import model as _model +from .. import models as _models +from .._auth import HTTP_BEARER_AUTH as _CORE_BEARER_AUTH +from .._auth import TOKEN_IDENTITY_RESOLVER, AuthContribution +from ..dependencies import SMITHY_HTTP +from ..integrations import ClientIntegration, ClientMode +from ..symbols import TypeReference +from ._dependencies import SMITHY_AWS_CORE + +if TYPE_CHECKING: + from ..clients import ClientPlan + from ..integrations import Part + from ..writer import PythonWriter + +__all__ = ["AWS_HTTP_BEARER_AUTH", "SIGV4", "AwsIdentityIntegration"] + + +class AwsIdentityIntegration(ClientIntegration): + """Identity resolution for AWS services with ``aws.auth#sigv4`` or + ``smithy.api#httpBearerAuth``. + + Configs default ``auth_schemes`` to the SigV4 scheme for the trait's signing + name, the bearer scheme, or both. The credential fields come from + ``AwsConfig``; the bearer fields are ``token`` and ``token_identity_resolver``. + A client's ``_post_setup`` fills each identity resolver the config leaves + unset: the default AWS credentials chain, and for bearer auth the static + token resolver when the config has a ``token`` or else the default AWS token + provider chain. Both chains read the config's profile, region, and transport. + """ + + def matches(self, service: _model.ServiceShape) -> bool: + return service.has_trait(_SERVICE) and any( + service.has_trait(scheme.scheme_id) for scheme in _SCHEMES + ) + + def auth_schemes( + self, service: _model.ServiceShape + ) -> Mapping[_model.ShapeId, AuthContribution]: + del service + return {scheme.scheme_id: scheme for scheme in _SCHEMES} + + def write_client_methods( + self, + writer: PythonWriter, + plan: ClientPlan, + mode: ClientMode, + config: TypeReference, + ) -> None: + service = plan.selection.service + assert service is not None # noqa: S101 - ClientPlan requires a service + sync = not mode.is_async + define = "def " if sync else "async def " + wait = "" if sync else "await " + chain = ( + _aws("IdentityChain", "identity.chain.resolver") + if sync + else _aws("AsyncIdentityChain", "aio.identity.chain") + ) + http_client = ( + _http("HTTPClient", "interfaces") + if sync + else _http("AsyncHTTPClient", "aio.interfaces") + ) + static_token = ( + _http("StaticTokenResolver", "identity.token") + if sync + else _http("AsyncStaticTokenResolver", "aio.identity.token") + ) + + def write_chain(resolver: str, identity: TypeReference) -> None: + writer.line( + "config_file, profile_name = ", + wait, + "self._profile_overrides(config)", + ) + writer.line("config.", resolver, " = ", wait, chain, ".create(") + with writer.indent(): + writer.line(identity, ",") + writer.line("config_file=config_file,") + writer.line("profile_name=profile_name,") + writer.line("region_override=config.region,") + writer.line( + "http_client=", + _CAST, + "(", + http_client, + " | None, config.transport),", + ) + writer.line(")") + + writer.line() + writer.line(define, "_post_setup(self, config: ", config, ") -> None:") + with writer.indent(): + if service.has_trait(SIGV4.scheme_id): + writer.line("if config.aws_credentials_identity_resolver is None:") + with writer.indent(): + write_chain( + "aws_credentials_identity_resolver", _CREDENTIALS_IDENTITY + ) + if service.has_trait(AWS_HTTP_BEARER_AUTH.scheme_id): + if service.has_trait(SIGV4.scheme_id): + writer.line() + # A configured token gets the static resolver, which reads it from + # the identity properties the bearer scheme supplies. Otherwise the + # default token provider chain is consulted, as every AWS SDK does. + writer.line("if config.token_identity_resolver is None:") + with writer.indent(): + writer.line("if config.token is not None:") + with writer.indent(): + writer.line( + "config.token_identity_resolver = ", static_token, "()" + ) + writer.line("else:") + with writer.indent(): + write_chain("token_identity_resolver", _TOKEN_IDENTITY) + # Shared by every identity chain the client builds: the parsed config + # file and the explicit profile override, if any. + writer.line() + writer.line(define, "_profile_overrides(") + with writer.indent(): + writer.line("self, config: ", config) + writer.line(") -> tuple[", _MERGED_CONFIG, " | None, str | None]:") + with writer.indent(): + writer.line("config_context = config.resolution_context()") + writer.line("config_file = None") + writer.line("profile_name = None") + writer.line("if config_context is not None:") + with writer.indent(): + writer.line("config_file = ", wait, "config_context.parsed_profiles()") + writer.line( + "if config_context.profile_source is ", _CONFIG_SOURCE, ".OVERRIDE:" + ) + with writer.indent(): + writer.line("profile_name = config_context.profile_name") + writer.line("return config_file, profile_name") + + +def _aws(name: str, module: str) -> TypeReference: + return TypeReference( + name, f"smithy_aws_core.{module}", dependencies=(SMITHY_AWS_CORE,) + ) + + +def _http(name: str, module: str) -> TypeReference: + return TypeReference(name, f"smithy_http.{module}", dependencies=(SMITHY_HTTP,)) + + +def _signing_name(trait: _model.Node) -> str: + name = trait.get("name") if isinstance(trait, Mapping) else None + if not isinstance(name, str) or not name: + raise _exceptions.CodegenError("Invalid aws.auth#sigv4 trait: needs a name") + return name + + +def _scheme(reference: TypeReference) -> Callable[[_model.Node], tuple[Part, ...]]: + def build(trait: _model.Node) -> tuple[Part, ...]: + quoted = _models._quote(_signing_name(trait)) # pyright: ignore[reportPrivateUsage] + return (reference, f"(service={quoted})") + + return build + + +_SERVICE: Final = _model.ShapeId("aws.api", "service") +_CAST: Final = TypeReference("cast", "typing") +_CONFIG_SOURCE: Final = _aws("ConfigSource", "config.types") +_MERGED_CONFIG: Final = _aws("MergedConfig", "config.merged_config") +_CREDENTIALS_IDENTITY: Final = _aws("AWSCredentialsIdentity", "identity.components") +_TOKEN_IDENTITY: Final = _http("TokenIdentity", "identity") + +SIGV4: Final = AuthContribution( + scheme_id=_model.ShapeId("aws.auth", "sigv4"), + scheme=_scheme(_aws("SigV4AuthScheme", "auth.sigv4")), + async_scheme=_scheme(_aws("AsyncSigV4AuthScheme", "aio.auth.sigv4")), + # AwsConfig declares the credential fields and the credentials resolver. + fields=(), +) +"""SigV4 auth, from the ``aws.auth#sigv4`` trait.""" + +AWS_HTTP_BEARER_AUTH: Final = replace( + _CORE_BEARER_AUTH, + # The resolver defaults to None so _post_setup can choose between the static + # resolver and the token provider chain. + fields=tuple( + replace(field, default=(), async_default=()) + if field.name == TOKEN_IDENTITY_RESOLVER.name + else field + for field in _CORE_BEARER_AUTH.fields + ), +) +"""Bearer token auth for AWS services, which fall back to the token chain.""" + +_SCHEMES: Final = (SIGV4, AWS_HTTP_BEARER_AUTH) diff --git a/packages/smithy-python/src/smithy_python/aws/_sigv4.py b/packages/smithy-python/src/smithy_python/aws/_sigv4.py deleted file mode 100644 index d2792d4ac..000000000 --- a/packages/smithy-python/src/smithy_python/aws/_sigv4.py +++ /dev/null @@ -1,148 +0,0 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 -"""SigV4 auth and the default AWS credentials chain.""" - -from __future__ import annotations - -from collections.abc import Callable, Mapping -from typing import TYPE_CHECKING, Final - -from .. import exceptions as _exceptions -from .. import model as _model -from .. import models as _models -from .._auth import AuthContribution -from ..dependencies import SMITHY_HTTP -from ..integrations import ClientIntegration, ClientMode -from ..symbols import TypeReference -from ._dependencies import SMITHY_AWS_CORE - -if TYPE_CHECKING: - from ..clients import ClientPlan - from ..integrations import Part - from ..writer import PythonWriter - -__all__ = ["SIGV4", "AwsSigV4Integration"] - - -class AwsSigV4Integration(ClientIntegration): - """SigV4 auth for AWS services with the ``aws.auth#sigv4`` trait. - - Configs default ``auth_schemes`` to the SigV4 scheme for the trait's signing - name. The credential fields come from ``AwsConfig``. A client whose config has - no credentials resolver sets the default AWS credentials chain in - ``_post_setup``, built from the config's profile and region. - """ - - def matches(self, service: _model.ServiceShape) -> bool: - return service.has_trait(_SERVICE) and service.has_trait(SIGV4.scheme_id) - - def auth_schemes( - self, service: _model.ServiceShape - ) -> Mapping[_model.ShapeId, AuthContribution]: - del service - return {SIGV4.scheme_id: SIGV4} - - def write_client_methods( - self, - writer: PythonWriter, - plan: ClientPlan, - mode: ClientMode, - config: TypeReference, - ) -> None: - del plan - sync = not mode.is_async - wait = "" if sync else "await " - chain = ( - _aws("IdentityChain", "identity.chain.resolver") - if sync - else _aws("AsyncIdentityChain", "aio.identity.chain") - ) - http_client = ( - _http("HTTPClient", "interfaces") - if sync - else _http("AsyncHTTPClient", "aio.interfaces") - ) - writer.line() - writer.line( - "def " if sync else "async def ", - "_post_setup(self, config: ", - config, - ") -> None:", - ) - with writer.indent(): - writer.line("if config.aws_credentials_identity_resolver is None:") - with writer.indent(): - writer.line("config_context = config.resolution_context()") - writer.line("config_file = None") - writer.line("profile_name = None") - writer.line("if config_context is not None:") - with writer.indent(): - writer.line( - "config_file = ", wait, "config_context.parsed_profiles()" - ) - writer.line( - "if config_context.profile_source is ", - _CONFIG_SOURCE, - ".OVERRIDE:", - ) - with writer.indent(): - writer.line("profile_name = config_context.profile_name") - writer.line( - "config.aws_credentials_identity_resolver = ", - wait, - chain, - ".create(", - ) - with writer.indent(): - writer.line(_CREDENTIALS_IDENTITY, ",") - writer.line("config_file=config_file,") - writer.line("profile_name=profile_name,") - writer.line("region_override=config.region,") - writer.line( - "http_client=", - _CAST, - "(", - http_client, - " | None, config.transport),", - ) - writer.line(")") - - -def _aws(name: str, module: str) -> TypeReference: - return TypeReference( - name, f"smithy_aws_core.{module}", dependencies=(SMITHY_AWS_CORE,) - ) - - -def _http(name: str, module: str) -> TypeReference: - return TypeReference(name, f"smithy_http.{module}", dependencies=(SMITHY_HTTP,)) - - -def _signing_name(trait: _model.Node) -> str: - name = trait.get("name") if isinstance(trait, Mapping) else None - if not isinstance(name, str) or not name: - raise _exceptions.CodegenError("Invalid aws.auth#sigv4 trait: needs a name") - return name - - -def _scheme(reference: TypeReference) -> Callable[[_model.Node], tuple[Part, ...]]: - def build(trait: _model.Node) -> tuple[Part, ...]: - quoted = _models._quote(_signing_name(trait)) # pyright: ignore[reportPrivateUsage] - return (reference, f"(service={quoted})") - - return build - - -_SERVICE: Final = _model.ShapeId("aws.api", "service") -_CAST: Final = TypeReference("cast", "typing") -_CONFIG_SOURCE: Final = _aws("ConfigSource", "config.types") -_CREDENTIALS_IDENTITY: Final = _aws("AWSCredentialsIdentity", "identity.components") - -SIGV4: Final = AuthContribution( - scheme_id=_model.ShapeId("aws.auth", "sigv4"), - scheme=_scheme(_aws("SigV4AuthScheme", "auth.sigv4")), - async_scheme=_scheme(_aws("AsyncSigV4AuthScheme", "aio.auth.sigv4")), - # AwsConfig declares the credential fields and the credentials resolver. - fields=(), -) -"""SigV4 auth, from the ``aws.auth#sigv4`` trait.""" diff --git a/packages/smithy-python/tests/unit/test_client_generation.py b/packages/smithy-python/tests/unit/test_client_generation.py index c14ac2c1a..5b1d2f996 100644 --- a/packages/smithy-python/tests/unit/test_client_generation.py +++ b/packages/smithy-python/tests/unit/test_client_generation.py @@ -308,8 +308,8 @@ def test_generated_client_type_checks_for_consumers(tmp_path: Path) -> None: assert checked.returncode == 0, checked.stdout + checked.stderr -def _add_auth(shapes: dict[str, Any]) -> None: - shapes["example#Greeter"]["traits"]["smithy.api#httpBearerAuth"] = {} +def _add_basic_auth(shapes: dict[str, Any]) -> None: + shapes["example#Greeter"]["traits"]["smithy.api#httpBasicAuth"] = {} def _add_rules(shapes: dict[str, Any]) -> None: @@ -331,7 +331,7 @@ def _remove_protocol(shapes: dict[str, Any]) -> None: @pytest.mark.parametrize( ("change", "message"), [ - (_add_auth, "Operation example#Greet requires auth"), + (_add_basic_auth, "Operation example#Greet requires auth"), (_add_rules, "smithy.rules#endpointRuleSet"), (_add_stream, "Operation example#Greet streams"), (_remove_protocol, "has no supported protocol"), @@ -1253,12 +1253,57 @@ def test_api_key_auth_signs_requests_in_the_query( def test_an_operation_needs_one_supported_auth_scheme(tmp_path: Path) -> None: shapes = _shapes() _add_api_key(shapes) - _add_auth(shapes) - # Bearer auth is unsupported, but API key auth is a fallback. + _add_basic_auth(shapes) + # Basic auth is unsupported, but API key auth is a fallback. _generate(tmp_path / "fallback", "greeter_fallback", shapes) - shapes["example#Greet"]["traits"]["smithy.api#auth"] = ["smithy.api#httpBearerAuth"] + shapes["example#Greet"]["traits"]["smithy.api#auth"] = ["smithy.api#httpBasicAuth"] with pytest.raises(CodegenError, match="Operation example#Greet requires auth"): - _generate(tmp_path / "bearer", "greeter_bearer", shapes) + _generate(tmp_path / "basic", "greeter_basic", shapes) + + +def _add_bearer(shapes: dict[str, Any]) -> None: + shapes["example#Greeter"]["traits"]["smithy.api#httpBearerAuth"] = {} + + +def test_bearer_auth_signs_requests_in_the_authorization_header( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + shapes = _shapes() + _add_bearer(shapes) + _generate(tmp_path, "greeter_bearer", shapes) + monkeypatch.syspath_prepend( # pyright: ignore[reportUnknownMemberType] + str(tmp_path / "src") + ) + package = importlib.import_module("greeter_bearer") + transport = _Transport(body=_cbor_map({})) + config = package.Config( + token="s3cret", + endpoint_uri="https://example.com", + transport=transport, + retry_strategy=SimpleRetryStrategy(max_attempts=1), + ) + package.Greeter(config).greet(name="Ana") + (request,) = transport.requests + assert request.fields["Authorization"].as_string() == "Bearer s3cret" + + +def test_bearer_auth_defaults_to_the_static_token_resolver(tmp_path: Path) -> None: + # A service outside AWS has no token provider chain, so the config reads the + # token it was given and the client needs no setup step. + shapes = _shapes() + _add_bearer(shapes) + _generate(tmp_path, "greeter_bearer_static", shapes) + source = tmp_path / "src/greeter_bearer_static" + config = (source / "config.py").read_text() + assert ( + "self.token_identity_resolver = token_identity_resolver or " + "StaticTokenResolver()" + ) in config + assert 'ShapeID("smithy.api#httpBearerAuth"): BearerAuthScheme()' in config + assert "_post_setup" not in (source / "client.py").read_text() + async_config = (source / "aio/config.py").read_text() + assert "AsyncStaticTokenResolver()" in async_config + assert "AsyncBearerAuthScheme()" in async_config def test_api_key_auth_trait_must_name_a_location(tmp_path: Path) -> None: @@ -1372,6 +1417,21 @@ def test_integrations_apply_only_to_services_they_match(tmp_path: Path) -> None: assert not (tmp_path / "src/greeter_plain/user_agent.py").exists() +def test_bearer_auth_outside_aws_keeps_the_static_token_resolver( + tmp_path: Path, +) -> None: + # The token chain reads an AWS config, which a service without aws.api#service + # lacks, so the AWS integrations leave its bearer auth alone. + shapes = _shapes() + _add_bearer(shapes) + _aws_generate(tmp_path, "greeter_bearer_plain", shapes) + source = tmp_path / "src/greeter_bearer_plain" + config = (source / "config.py").read_text() + assert "class Config:" in config + assert "token_identity_resolver or StaticTokenResolver()" in config + assert "_post_setup" not in (source / "client.py").read_text() + + def test_aws_services_need_an_sdk_id(tmp_path: Path) -> None: shapes = _shapes() shapes["example#Greeter"]["traits"]["aws.api#service"] = {} @@ -1426,12 +1486,58 @@ def test_sigv4_services_sign_with_the_signing_name(tmp_path: Path) -> None: ) client = (source / "aio/client.py").read_text() assert "async def _post_setup(self, config: AsyncGreeterConfig) -> None:" in client + assert "config_file, profile_name = await self._profile_overrides(config)" in client assert "await AsyncIdentityChain.create(" in client + assert "token_identity_resolver" not in client assert "return await AsyncGreeterConfig.resolve()" in client + assert "_SHARED_FIELDS" not in config models = (source / "models.py").read_text() assert '("aws.auth#sigv4",)' in models +def test_aws_bearer_auth_falls_back_to_the_token_chain(tmp_path: Path) -> None: + shapes = _shapes() + shapes["example#Greeter"]["traits"]["aws.api#service"] = {"sdkId": "Greeter"} + _add_bearer(shapes) + _aws_generate(tmp_path, "greeter_bearer_aws", shapes) + source = tmp_path / "src/greeter_bearer_aws" + config = (source / "config.py").read_text() + assert 'ShapeID("smithy.api#httpBearerAuth"): BearerAuthScheme()' in config + # The resolver has no default, so _post_setup chooses one. + assert '"token_identity_resolver": FieldSpec(default=None),' in config + assert "StaticTokenResolver" not in config + # A deep copy of the config shares the resolver, which caches the token. + assert ( + "_SHARED_FIELDS: ClassVar[tuple[str, ...]] = (\n" + " *AwsConfig._SHARED_FIELDS,\n" + ' "token_identity_resolver",\n' + " )" + ) in config + client = (source / "client.py").read_text() + assert "def _post_setup(self, config: GreeterConfig) -> None:" in client + assert "if config.token_identity_resolver is None:" in client + assert "config.token_identity_resolver = StaticTokenResolver()" in client + assert "config.token_identity_resolver = IdentityChain.create(" in client + assert "TokenIdentity," in client + assert "aws_credentials_identity_resolver" not in client + async_client = (source / "aio/client.py").read_text() + assert "AsyncStaticTokenResolver()" in async_client + assert "await AsyncIdentityChain.create(" in async_client + + +def test_sigv4_and_bearer_auth_share_one_setup_step(tmp_path: Path) -> None: + shapes = _shapes() + _add_sigv4(shapes) + _add_bearer(shapes) + _aws_generate(tmp_path, "greeter_both", shapes) + client = (tmp_path / "src/greeter_both/client.py").read_text() + assert client.count("def _post_setup(") == 1 + assert client.count("def _profile_overrides(") == 1 + assert client.index("config.aws_credentials_identity_resolver = ") < client.index( + "config.token_identity_resolver = StaticTokenResolver()" + ) + + def test_sigv4_needs_the_aws_integrations(tmp_path: Path) -> None: # Without its definition in the AST, sigv4 is still an auth scheme, so a # client that can't sign it isn't generated as unsigned. diff --git a/scripts/api-snapshot/api-rex.json b/scripts/api-snapshot/api-rex.json index e6865e290..8dd5ff3b6 100644 --- a/scripts/api-snapshot/api-rex.json +++ b/scripts/api-snapshot/api-rex.json @@ -1377,7 +1377,7 @@ "AWS_JSON_11": "rex-ProtocolContribution", "AwsConfigIntegration": "rex-class", "AwsEndpointsIntegration": "rex-class", - "AwsSigV4Integration": "rex-class", + "AwsIdentityIntegration": "rex-class", "REST_JSON": "rex-ProtocolContribution", "SMITHY_AWS_CORE": "rex-Dependency" }, diff --git a/scripts/codegen-output-py/models/features.json b/scripts/codegen-output-py/models/features.json index 2da8b8be1..736b4c1c8 100644 --- a/scripts/codegen-output-py/models/features.json +++ b/scripts/codegen-output-py/models/features.json @@ -24,6 +24,9 @@ { "target": "example.features#Echo" }, + { + "target": "example.features#GetNote" + }, { "target": "example.features#GetThing" }, @@ -47,12 +50,13 @@ "aws.auth#sigv4": { "name": "fieldnotes" }, - "smithy.api#documentation": "An AWS service that uses every client feature the generator supports.\n\nIts endpoint rules read config, input, and operation values. Its operations\nuse SigV4, API key auth, optional auth, and no auth.", + "smithy.api#documentation": "An AWS service that uses every client feature the generator supports.\n\nIts endpoint rules read config, input, and operation values. Its operations\nuse SigV4, bearer token auth, API key auth, optional auth, and no auth.", "smithy.api#httpApiKeyAuth": { "name": "Authorization", "in": "header", "scheme": "ApiKey" }, + "smithy.api#httpBearerAuth": {}, "smithy.protocols#rpcv2Cbor": {}, "smithy.rules#clientContextParams": { "Stage": { @@ -698,6 +702,43 @@ } } }, + "example.features#GetNote": { + "type": "operation", + "input": { + "target": "example.features#GetNoteInput" + }, + "output": { + "target": "example.features#GetNoteOutput" + }, + "traits": { + "smithy.api#auth": [ + "smithy.api#httpBearerAuth" + ], + "smithy.api#documentation": "Reads a note, with a bearer token." + } + }, + "example.features#GetNoteInput": { + "type": "structure", + "members": { + "id": { + "target": "smithy.api#String" + } + }, + "traits": { + "smithy.api#input": {} + } + }, + "example.features#GetNoteOutput": { + "type": "structure", + "members": { + "text": { + "target": "smithy.api#String" + } + }, + "traits": { + "smithy.api#output": {} + } + }, "example.features#GetThing": { "type": "operation", "input": { diff --git a/scripts/codegen-output-py/models/features.smithy b/scripts/codegen-output-py/models/features.smithy index e9ac05d2c..499ab0684 100644 --- a/scripts/codegen-output-py/models/features.smithy +++ b/scripts/codegen-output-py/models/features.smithy @@ -14,11 +14,12 @@ use smithy.rules#staticContextParams /// An AWS service that uses every client feature the generator supports. /// /// Its endpoint rules read config, input, and operation values. Its operations -/// use SigV4, API key auth, optional auth, and no auth. +/// use SigV4, bearer token auth, API key auth, optional auth, and no auth. @service(sdkId: "Field Notes") @sigv4(name: "fieldnotes") @rpcv2Cbor @httpApiKeyAuth(name: "Authorization", in: "header", scheme: "ApiKey") +@httpBearerAuth @clientContextParams( Stage: { type: "string", documentation: "The deployment stage." } ForcePathStyle: { type: "boolean", documentation: "Forces path-style addressing." } @@ -214,7 +215,7 @@ use smithy.rules#staticContextParams }) service FieldNotes { version: "2026-11-20" - operations: [Echo, GetThing, ListNotes, Ping, PutNote, PutThing] + operations: [Echo, GetNote, GetThing, ListNotes, Ping, PutNote, PutThing] } /// Uses API key auth, but sends no key when it has none. @@ -222,6 +223,17 @@ service FieldNotes { @optionalAuth operation Echo {} +/// Reads a note, with a bearer token. +@auth([httpBearerAuth]) +operation GetNote { + input := { + id: String + } + output := { + text: String + } +} + /// Uses API key auth. @auth([httpApiKeyAuth]) operation GetThing { diff --git a/scripts/codegen-output-py/tests/test_client_snapshots.py b/scripts/codegen-output-py/tests/test_client_snapshots.py index ca2437ea1..c74fe5a31 100644 --- a/scripts/codegen-output-py/tests/test_client_snapshots.py +++ b/scripts/codegen-output-py/tests/test_client_snapshots.py @@ -16,7 +16,10 @@ from typing import Any import pytest +from smithy_aws_core.aio.identity.chain import AsyncIdentityChain from smithy_aws_core.config.exceptions import ConfigError +from smithy_aws_core.identity.chain.exceptions import IdentityChainError +from smithy_aws_core.identity.chain.resolver import IdentityChain from smithy_cbor import loads from smithy_core.aio.types import AsyncBytesReader from smithy_core.exceptions import SmithyIdentityError @@ -324,6 +327,33 @@ def test_sigv4_clients_default_to_the_credentials_chain( assert "Credential=AKIDFROMENV/" in authorization +@pytest.mark.parametrize("aio", [False, True]) +def test_bearer_auth_sends_the_configured_token( + features: ModuleType, aio: bool, aws_env: pytest.MonkeyPatch +) -> None: + client, transport = _client(features, aio, endpoint_uri=_ENDPOINT, token="t0k3n") + _call(aio, client.get_note(id="n1")) + # SigV4 stays the default for operations that do not choose bearer auth. + _call(aio, client.put_note(text="hi")) + get_note, put_note = transport.requests + assert get_note.fields["Authorization"].as_string() == "Bearer t0k3n" + assert put_note.fields["Authorization"].as_string().startswith("AWS4-HMAC-SHA256") + + +@pytest.mark.parametrize("aio", [False, True]) +def test_bearer_clients_default_to_the_token_chain( + features: ModuleType, aio: bool, aws_env: pytest.MonkeyPatch +) -> None: + # No token provider is installed here, so the chain, not the static resolver, + # reports the miss. + client, transport = _client(features, aio, endpoint_uri=_ENDPOINT) + with pytest.raises(IdentityChainError, match="No identity providers"): + _call(aio, client.get_note(id="n1")) + assert transport.requests == [] + chain = AsyncIdentityChain if aio else IdentityChain + assert isinstance(client._config.token_identity_resolver, chain) + + @pytest.fixture(scope="module") def handwritten() -> Iterator[ModuleType]: source = _ROOT / "codegen-output/my-handwritten-model/src" From fc7dd3e2ff4f5c7ca33b94c27fa99a3f48260e93 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Tue, 24 Nov 2026 14:37:03 -0500 Subject: [PATCH 09/11] Trim the shared config provider docstring --- .../smithy_aws_core/identity/chain/providers/shared_config.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/providers/shared_config.py b/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/providers/shared_config.py index b29f2beb6..a70d1c1c8 100644 --- a/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/providers/shared_config.py +++ b/packages/smithy-aws-core/src/smithy_aws_core/identity/chain/providers/shared_config.py @@ -29,9 +29,7 @@ def setup(self, identity_type: type[Identity], setup: _ChainSetupBase) -> Any: """Load and select the active profile for every identity type. This step registers no resolvers; it only makes the shared config and the - active profile name available to the profile-based providers that follow it, - whatever identity type the chain resolves (for example ``TokenIdentity`` - chains read ``sso_session`` from the same profile). + active profile name available to the profile-based providers that follow it. """ return setup._run(self._setup(setup)) # pyright: ignore[reportPrivateUsage] From f63c0e5a71f4d9aecd8b142aead0e47018f7f213 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Tue, 24 Nov 2026 15:50:50 -0500 Subject: [PATCH 10/11] Java codegen fix: apply the AWS identity chains only to AWS services --- .../aws/codegen/AwsIdentityIntegration.java | 33 +++++++--- .../codegen/AwsIdentityIntegrationTest.java | 64 +++++++++++++++++++ 2 files changed, 89 insertions(+), 8 deletions(-) create mode 100644 codegen/aws/core/src/test/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegrationTest.java diff --git a/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegration.java b/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegration.java index fe914eeae..a8dd3364d 100644 --- a/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegration.java +++ b/codegen/aws/core/src/main/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegration.java @@ -5,8 +5,10 @@ package software.amazon.smithy.python.aws.codegen; import java.util.List; +import software.amazon.smithy.aws.traits.ServiceTrait; import software.amazon.smithy.aws.traits.auth.SigV4Trait; import software.amazon.smithy.codegen.core.Symbol; +import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.traits.HttpBearerAuthTrait; import software.amazon.smithy.python.codegen.GenerationContext; import software.amazon.smithy.python.codegen.RuntimeTypes; @@ -22,10 +24,10 @@ /** * Sets up the default identity resolvers during client setup. * - *

For services using SigV4 this wires the default AWS credentials identity chain. - * For services using {@code smithy.api#httpBearerAuth} it wires a static token - * resolver when a {@code token} is configured, matching the generic client config, - * and the default token identity chain otherwise. + *

For AWS services using SigV4 this wires the default AWS credentials identity + * chain. For AWS services using {@code smithy.api#httpBearerAuth} it wires a static + * token resolver when a {@code token} is configured, matching the generic client + * config, and the default token identity chain otherwise. */ @SmithyInternalApi public class AwsIdentityIntegration implements PythonIntegration { @@ -35,12 +37,27 @@ public List> inte GenerationContext context ) { var service = context.settings().service(context.model()); - var hasSigV4 = service.hasTrait(SigV4Trait.class); - var hasBearer = service.hasTrait(HttpBearerAuthTrait.class); - if (!hasSigV4 && !hasBearer) { + if (!appliesTo(service)) { return List.of(); } - return List.of(new IdentitySetupInterceptor(hasSigV4, hasBearer)); + return List.of(new IdentitySetupInterceptor( + service.hasTrait(SigV4Trait.class), + service.hasTrait(HttpBearerAuthTrait.class))); + } + + /** + * Whether the identity chains apply to a service. + * + *

The chains read the profile and region of an AWS config, so a service outside + * AWS keeps the core generator's static token resolver even when it uses bearer + * auth. + * + * @param service The service being generated. + * @return true if the service is an AWS service with SigV4 or bearer auth. + */ + static boolean appliesTo(ServiceShape service) { + return service.hasTrait(ServiceTrait.class) + && (service.hasTrait(SigV4Trait.class) || service.hasTrait(HttpBearerAuthTrait.class)); } /** diff --git a/codegen/aws/core/src/test/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegrationTest.java b/codegen/aws/core/src/test/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegrationTest.java new file mode 100644 index 000000000..d9f2722ad --- /dev/null +++ b/codegen/aws/core/src/test/java/software/amazon/smithy/python/aws/codegen/AwsIdentityIntegrationTest.java @@ -0,0 +1,64 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package software.amazon.smithy.python.aws.codegen; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import software.amazon.smithy.aws.traits.ServiceTrait; +import software.amazon.smithy.aws.traits.auth.SigV4Trait; +import software.amazon.smithy.model.shapes.ServiceShape; +import software.amazon.smithy.model.shapes.ShapeId; +import software.amazon.smithy.model.traits.HttpBearerAuthTrait; + +public class AwsIdentityIntegrationTest { + + private static ServiceShape.Builder service() { + return ServiceShape.builder() + .id("smithy.example#TestService") + .version("2024-01-01"); + } + + private static ServiceTrait awsService() { + return ServiceTrait.builder() + .sdkId("Test") + .build(ShapeId.from("smithy.example#TestService")); + } + + @Test + public void testAppliesToAwsServicesWithSigV4() { + var shape = service() + .addTrait(awsService()) + .addTrait(SigV4Trait.builder().name("test").build()) + .build(); + + assertTrue(AwsIdentityIntegration.appliesTo(shape)); + } + + @Test + public void testAppliesToAwsServicesWithBearerAuth() { + var shape = service() + .addTrait(awsService()) + .addTrait(new HttpBearerAuthTrait()) + .build(); + + assertTrue(AwsIdentityIntegration.appliesTo(shape)); + } + + @Test + public void testSkipsAwsServicesWithoutIdentityAuth() { + assertFalse(AwsIdentityIntegration.appliesTo(service().addTrait(awsService()).build())); + } + + @Test + public void testSkipsBearerAuthOutsideAws() { + // The token chain reads an AWS config, which a service outside AWS lacks, so + // its generated config keeps the static token resolver. + var shape = service().addTrait(new HttpBearerAuthTrait()).build(); + + assertFalse(AwsIdentityIntegration.appliesTo(shape)); + } +} From 4a3c9dd5b425a8094a3b0cf82d74c51c9d869228 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Wed, 25 Nov 2026 00:11:00 -0500 Subject: [PATCH 11/11] Shorten the smithy-aws-core changelog entry for the secret token fields --- ...y-aws-core-enhancement-958c7cbfa9004679b551de251e33329b.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-958c7cbfa9004679b551de251e33329b.json b/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-958c7cbfa9004679b551de251e33329b.json index 83375d8e8..125431d57 100644 --- a/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-958c7cbfa9004679b551de251e33329b.json +++ b/packages/smithy-aws-core/.changes/next-release/smithy-aws-core-enhancement-958c7cbfa9004679b551de251e33329b.json @@ -1,4 +1,4 @@ { "type": "enhancement", - "description": "AWS configs now treat the generated `token` and `api_key` fields as secrets: they are hidden from `repr` and cannot be changed after resolution. Deep copies share the identity resolvers a generated config lists in `_SHARED_FIELDS`, like the credentials resolver. A `TokenIdentity` chain no longer logs or reports detected-but-unclaimed credential sources, and chain errors say \"identity providers\"." + "description": "AWS configs now treat the generated `token` and `api_key` fields as secrets: hidden from `repr` and frozen after resolution. Deep copies share every identity resolver that a generated config lists in `_SHARED_FIELDS`, not only the credentials resolver. The identity chain's \"no providers\" error now reads \"No identity providers\" instead of \"No credential providers\"." }