From 03c5fb4e7bf5eecc7c4862c2d3b8f317ff9e8d55 Mon Sep 17 00:00:00 2001 From: Sean O'Brien <60306702+stobrien89@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:07:17 -0500 Subject: [PATCH] Generate API key auth for Python clients --- .../.smithy-python-manifest.json | 19 +++ .../api-key-auth-client/README.md | 5 + .../api-key-auth-client/pyproject.toml | 37 ++++ .../src/api_key_auth_client/__init__.py | 25 +++ .../api_key_auth_client/_private/__init__.py | 0 .../api_key_auth_client/_private/endpoints.py | 27 +++ .../api_key_auth_client/_private/schemas.py | 105 ++++++++++++ .../src/api_key_auth_client/aio/__init__.py | 19 +++ .../src/api_key_auth_client/aio/client.py | 120 +++++++++++++ .../src/api_key_auth_client/aio/config.py | 122 +++++++++++++ .../src/api_key_auth_client/client.py | 120 +++++++++++++ .../src/api_key_auth_client/config.py | 121 +++++++++++++ .../src/api_key_auth_client/models.py | 77 +++++++++ .../src/api_key_auth_client/models.pyi | 104 +++++++++++ .../src/api_key_auth_client/py.typed | 0 designs/codegen/client.md | 41 ++++- ...ture-f68b6cc3a9b648179a6f6f6fbbb1af4d.json | 4 + .../smithy-python/src/smithy_python/_auth.py | 161 ++++++++++++++++++ .../src/smithy_python/_client_emitter.py | 74 +++++++- .../tests/unit/test_client_generation.py | 47 +++++ .../codegen-output-py/client-projections.json | 7 + .../models/api-key-auth.json | 89 ++++++++++ .../models/api-key-auth.smithy | 31 ++++ scripts/codegen-output-py/pyrightconfig.json | 1 + .../tests/test_client_snapshots.py | 56 ++++++ scripts/verifications/import-cost.json | 2 +- 26 files changed, 1404 insertions(+), 10 deletions(-) create mode 100644 codegen-output-py/api-key-auth-client/.smithy-python-manifest.json create mode 100644 codegen-output-py/api-key-auth-client/README.md create mode 100644 codegen-output-py/api-key-auth-client/pyproject.toml create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/__init__.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/__init__.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/endpoints.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/schemas.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/__init__.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/client.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/config.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/client.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/config.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/models.py create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/models.pyi create mode 100644 codegen-output-py/api-key-auth-client/src/api_key_auth_client/py.typed create mode 100644 packages/smithy-python/.changes/next-release/smithy-python-feature-f68b6cc3a9b648179a6f6f6fbbb1af4d.json create mode 100644 packages/smithy-python/src/smithy_python/_auth.py create mode 100644 scripts/codegen-output-py/models/api-key-auth.json create mode 100644 scripts/codegen-output-py/models/api-key-auth.smithy diff --git a/codegen-output-py/api-key-auth-client/.smithy-python-manifest.json b/codegen-output-py/api-key-auth-client/.smithy-python-manifest.json new file mode 100644 index 000000000..4ab6967d4 --- /dev/null +++ b/codegen-output-py/api-key-auth-client/.smithy-python-manifest.json @@ -0,0 +1,19 @@ +{ + "files": { + "README.md": "0575cdb9dbd9d11ba72c347ebd2cfb1a9e68b50208ce144d07c01e46802e1a10", + "pyproject.toml": "94e3cbb02f22fa0b7c2b081fbbb7a797a151ff4e368303e49f69f95f8ae0c96c", + "src/api_key_auth_client/__init__.py": "c9cc2cd353b5b05a7dce3ad05a0e499c8cb368281e2146219dcff4c269e3a1bb", + "src/api_key_auth_client/_private/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "src/api_key_auth_client/_private/endpoints.py": "7d515fe771678e82ddbe07798d6b7e48c25c6c9bec19cec9318deb0bc5064ead", + "src/api_key_auth_client/_private/schemas.py": "64ebd9bc142c33fba620c877d1c1e6f3d258a4875ad38dbf905bcaa2505d471d", + "src/api_key_auth_client/aio/__init__.py": "01574d80de484082fae6de0f710510098e064007fd330bffd9f2e63efc5e75e6", + "src/api_key_auth_client/aio/client.py": "03ff3b33f191c3debf70cd95b37611c6937ecdd21c708ec68a492ca0ca2182fa", + "src/api_key_auth_client/aio/config.py": "5f9cefe2070a5a2a0d69c9fd45c0b2fbff065fdd9e09c4b56fc99db67ec3676d", + "src/api_key_auth_client/client.py": "d5de89636e23b7912a79b21712c5759e8efc98db5501cf05a986996d7471b03b", + "src/api_key_auth_client/config.py": "63a8567780b54a2ffb89e7df6f38b1a2c6d5838fa371f03e32011582ee5ebcff", + "src/api_key_auth_client/models.py": "a05bc9c5dcb44288446bb6ac4a5c0f98cbd1612adb9fb7cbf935e1401617091f", + "src/api_key_auth_client/models.pyi": "8a0650b60d4aa7b90f260cf404e1c67b3014db96f18d837011629eff59725bfb", + "src/api_key_auth_client/py.typed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "version": 1 +} diff --git a/codegen-output-py/api-key-auth-client/README.md b/codegen-output-py/api-key-auth-client/README.md new file mode 100644 index 000000000..7fe7f5b53 --- /dev/null +++ b/codegen-output-py/api-key-auth-client/README.md @@ -0,0 +1,5 @@ + + +## api_key_auth_client Client Package + +Python client for the API key auth fixture diff --git a/codegen-output-py/api-key-auth-client/pyproject.toml b/codegen-output-py/api-key-auth-client/pyproject.toml new file mode 100644 index 000000000..837fb9337 --- /dev/null +++ b/codegen-output-py/api-key-auth-client/pyproject.toml @@ -0,0 +1,37 @@ +# Code generated by smithy-python-codegen DO NOT EDIT. + +[project] +name = "api_key_auth_client" +version = "0.0.1" +description = "Python client for the API key auth fixture" +readme = "README.md" +requires-python = ">=3.12" +keywords = ["smithy", "api_key_auth_client"] +license = {text = "Apache-2.0"} +dependencies = [ + "smithy-core~=0.13.0", + "smithy-http[aiohttp,cbor,urllib3]~=0.10.0", +] + +[build-system] +requires = [ + "hatchling", +] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = [ + "src/api_key_auth_client", +] + +[tool.pyright] +typeCheckingMode = "strict" + +[tool.ruff] +target-version = "py312" + +[tool.ruff.lint] +ignore = ["F841"] + +[tool.ruff.format] +skip-magic-trailing-comma = true diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/__init__.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/__init__.py new file mode 100644 index 000000000..c9035ee5f --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/__init__.py @@ -0,0 +1,25 @@ +from importlib import import_module +from typing import TYPE_CHECKING, Any + +__version__: str = "0.0.1" + +if TYPE_CHECKING: + from .aio.client import AsyncApiKeyService + from .aio.config import AsyncConfig + from .client import ApiKeyService + from .config import Config + +__all__ = ["ApiKeyService", "AsyncApiKeyService", "AsyncConfig", "Config"] + +_EXPORTS = { + "ApiKeyService": ".client", + "Config": ".config", + "AsyncApiKeyService": ".aio.client", + "AsyncConfig": ".aio.config", +} + + +def __getattr__(name: str) -> Any: + if name in _EXPORTS: + return getattr(import_module(_EXPORTS[name], __name__), name) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/__init__.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/endpoints.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/endpoints.py new file mode 100644 index 000000000..ad3066783 --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/endpoints.py @@ -0,0 +1,27 @@ +from smithy_core.endpoints import EndpointBdd + +# fmt: off +# Tags: ref=0, attr=1, call=2, list=3, map=4, error=5, endpoint=6. +BDD = EndpointBdd( + # (name, type, required, default, builtin, client_context_attribute) + parameters=( + ("endpoint", "string", False, None, "SDK::Endpoint", None), + ), + functions=("isSet",), + conditions=( + ((2, "isSet", (0, "endpoint")), None), # 0: isSet(endpoint) + ), + results=( + None, # 0: no match + (6, (0, "endpoint"), None, ()), # 1 + (5, "(default endpointRuleSet) endpoint is not set - you must configure an endpoint."), # 2 + ), + root=2, + # (condition, high, low); 1 and -1 are terminals, a negative reference is a + # complement edge, and 100_000_000 + k is result k. + nodes=( + -1, 1, -1, + 0, 100_000_001, 100_000_002, + ), +) +# fmt: on diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/schemas.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/schemas.py new file mode 100644 index 000000000..791b44a6a --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/_private/schemas.py @@ -0,0 +1,105 @@ +from smithy_core._schema_compact import StaticOperationSchema, StaticSchema + +n0 = "example.apikey" +_s0 = "GetThingInput" +_s1 = "smithy.synthetic#originalShapeId" +_s2 = "example.apikey#GetThingInput" +_s3 = "smithy.api#input" +_s4 = "name" +_s5 = "GetThingOutput" +_s6 = "example.apikey#GetThingOutput" +_s7 = "smithy.api#output" +_s8 = "value" +_s9 = "HealthInput" +_s10 = "smithy.api#Unit" +_s11 = "HealthOutput" +_s12 = "PingInput" +_s13 = "PingOutput" +_s14 = "GetThing" +_s15 = "Health" +_s16 = "Ping" +_s17 = "ApiKeyService" +_s18 = "smithy.protocols#rpcv2Cbor" + +GET_THING_INPUT: StaticSchema = ( + 18, + n0, + _s0, + {_s1: _s2, _s3: None}, + (_s4,), + ((3, 0),), +) + +GET_THING_OUTPUT: StaticSchema = ( + 18, + n0, + _s5, + {_s1: _s6, _s7: None}, + (_s8,), + ((3, 0),), +) + +HEALTH_INPUT: StaticSchema = ( + 18, + n0, + _s9, + {_s1: _s10, _s3: None}, +) + +HEALTH_OUTPUT: StaticSchema = ( + 18, + n0, + _s11, + {_s1: _s10, _s7: None}, +) + +PING_INPUT: StaticSchema = ( + 18, + n0, + _s12, + {_s1: _s10, _s3: None}, +) + +PING_OUTPUT: StaticSchema = ( + 18, + n0, + _s13, + {_s1: _s10, _s7: None}, +) + +GET_THING: StaticOperationSchema = ( + 23, + n0, + _s14, + 0, + GET_THING_INPUT, + GET_THING_OUTPUT, + (), +) + +HEALTH: StaticOperationSchema = ( + 23, + n0, + _s15, + 0, + HEALTH_INPUT, + HEALTH_OUTPUT, + (), +) + +PING: StaticOperationSchema = ( + 23, + n0, + _s16, + 0, + PING_INPUT, + PING_OUTPUT, + (), +) + +API_KEY_SERVICE: StaticSchema = ( + 21, + n0, + _s17, + {_s18: None}, +) diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/__init__.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/__init__.py new file mode 100644 index 000000000..61152f98d --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/__init__.py @@ -0,0 +1,19 @@ +from importlib import import_module +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from .client import AsyncApiKeyService + from .config import AsyncConfig + +__all__ = ["AsyncApiKeyService", "AsyncConfig"] + +_EXPORTS = { + "AsyncApiKeyService": ".client", + "AsyncConfig": ".config", +} + + +def __getattr__(name: str) -> Any: + if name in _EXPORTS: + return getattr(import_module(_EXPORTS[name], __name__), name) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/client.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/client.py new file mode 100644 index 000000000..4dafdcad6 --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/client.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +from typing import Unpack, overload + +from smithy_core.aio.client import AsyncClient +from smithy_http.plugins import user_agent_plugin + +from api_key_auth_client import models +from api_key_auth_client.aio.config import AsyncConfig, Plugin + + +class AsyncApiKeyService(AsyncClient[AsyncConfig]): + "A service that authenticates with an API key." + + _client_plugins = (user_agent_plugin,) + + @overload + async def get_thing( + self, + request: models.GetThingInput | models.GetThingInputDict, + /, + *, + plugins: list[Plugin] | None = None, + ) -> models.GetThingOutput: ... + + @overload + async def get_thing( + self, + /, + *, + plugins: list[Plugin] | None = None, + **kwargs: Unpack[models.GetThingInputDict], + ) -> models.GetThingOutput: + """ + Uses the service's API key auth. + + :param plugins: Callables that change the configuration for this call + only. + """ + + async def get_thing( + self, /, *args: object, plugins: list[Plugin] | None = None, **kwargs: object + ) -> models.GetThingOutput: + return await self._invoke( + self._select_input(models.GET_THING, args, kwargs), + models.GET_THING, + [], + plugins, + ) + + @overload + async def health( + self, + request: models.HealthInput | models.HealthInputDict, + /, + *, + plugins: list[Plugin] | None = None, + ) -> models.HealthOutput: ... + + @overload + async def health( + self, + /, + *, + plugins: list[Plugin] | None = None, + **kwargs: Unpack[models.HealthInputDict], + ) -> models.HealthOutput: + """ + Needs no auth. + + :param plugins: Callables that change the configuration for this call + only. + """ + + async def health( + self, /, *args: object, plugins: list[Plugin] | None = None, **kwargs: object + ) -> models.HealthOutput: + return await self._invoke( + self._select_input(models.HEALTH, args, kwargs), + models.HEALTH, + [], + plugins, + ) + + @overload + async def ping( + self, + request: models.PingInput | models.PingInputDict, + /, + *, + plugins: list[Plugin] | None = None, + ) -> models.PingOutput: ... + + @overload + async def ping( + self, + /, + *, + plugins: list[Plugin] | None = None, + **kwargs: Unpack[models.PingInputDict], + ) -> models.PingOutput: + """ + Sends the API key when it has one. + + :param plugins: Callables that change the configuration for this call + only. + """ + + async def ping( + self, /, *args: object, plugins: list[Plugin] | None = None, **kwargs: object + ) -> models.PingOutput: + return await self._invoke( + self._select_input(models.PING, args, kwargs), + models.PING, + [], + plugins, + ) + + def _new_config(self) -> AsyncConfig: + return AsyncConfig() diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/config.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/config.py new file mode 100644 index 000000000..4ea9e2359 --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/aio/config.py @@ -0,0 +1,122 @@ +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, cast + +from smithy_core.aio.interfaces import AsyncClientTransport, AsyncEndpointResolver +from smithy_core.aio.interfaces.auth import AsyncAuthScheme +from smithy_core.aio.interfaces.identity import AsyncIdentityResolver +from smithy_core.auth import DefaultAuthResolver +from smithy_core.endpoints import BddEndpointResolver +from smithy_core.interceptors import Interceptor +from smithy_core.interfaces import ( + ClientProtocol, + EndpointResolver, + ProtocolConstructor, + ProtocolSettings, + URI, +) +from smithy_core.interfaces.auth import AuthSchemeResolver +from smithy_core.interfaces.retries import RetryStrategy +from smithy_core.retries import RetryStrategyOptions +from smithy_core.shapes import ShapeID +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.identity.apikey import AsyncAPIKeyIdentityResolver +from smithy_http.aio.protocols import AsyncRpcV2CborClientProtocol +from smithy_http.identity import APIKeyIdentity, APIKeyIdentityProperties + +from api_key_auth_client._private.endpoints import BDD +from api_key_auth_client._private.schemas import API_KEY_SERVICE + +_PROTOCOL_SETTINGS = ProtocolSettings( + namespace="example.apikey", + service_target="ApiKeyService", + version="2026-11-17", + service_schema=API_KEY_SERVICE, +) + + +@dataclass(init=False) +class AsyncConfig: + "Configuration for AsyncApiKeyService." + + api_key: str | None + "The API key to send along with requests." + + api_key_identity_resolver: ( + AsyncIdentityResolver[APIKeyIdentity, APIKeyIdentityProperties] | None + ) + "Resolves the API key." + + auth_scheme_resolver: AuthSchemeResolver + "Determines the auth scheme for each operation." + + auth_schemes: dict[ShapeID, AsyncAuthScheme[Any, Any, Any, Any]] + "Auth schemes by auth scheme ID." + + endpoint_resolver: EndpointResolver | AsyncEndpointResolver + "Resolves the endpoint of each operation." + + endpoint_uri: str | URI | None + "The endpoint URI, read by the endpoint rules as ``SDK::Endpoint``." + + interceptors: list[Interceptor[Any, Any, Any, Any]] + "Hooks called during the execution of a request." + + protocol: ClientProtocol[Any, Any] + "Serializes requests and deserializes responses." + + retry_strategy: RetryStrategy | RetryStrategyOptions | None + "The retry strategy, or options to create one." + + transport: AsyncClientTransport[Any, Any] + "Sends requests, such as an HTTP client." + + def __init__( + self, + *, + api_key: str | None = None, + api_key_identity_resolver: AsyncIdentityResolver[ + APIKeyIdentity, APIKeyIdentityProperties + ] + | None = None, + auth_scheme_resolver: AuthSchemeResolver | None = None, + auth_schemes: dict[ShapeID, AsyncAuthScheme[Any, Any, Any, Any]] | None = None, + endpoint_resolver: EndpointResolver | AsyncEndpointResolver | None = None, + endpoint_uri: str | URI | None = None, + interceptors: list[Interceptor[Any, Any, Any, Any]] | None = None, + protocol: ClientProtocol[Any, Any] + | ProtocolConstructor[ClientProtocol[Any, Any]] + | None = None, + retry_strategy: RetryStrategy | RetryStrategyOptions | None = None, + transport: AsyncClientTransport[Any, Any] | None = None, + ) -> None: + self.api_key = api_key + self.api_key_identity_resolver = ( + api_key_identity_resolver or AsyncAPIKeyIdentityResolver() + ) + self.auth_scheme_resolver = auth_scheme_resolver or DefaultAuthResolver() + self.auth_schemes = auth_schemes or { + ShapeID("smithy.api#httpApiKeyAuth"): AsyncAPIKeyAuthScheme( + name="Authorization", location=APIKeyLocation.HEADER, scheme="ApiKey" + ), + } + self.endpoint_resolver = endpoint_resolver or BddEndpointResolver(BDD) + self.endpoint_uri = endpoint_uri + self.interceptors = interceptors or [] + if isinstance(protocol, type): + protocol = protocol(_PROTOCOL_SETTINGS) + self.protocol = cast( + ClientProtocol[Any, Any], protocol + ) or AsyncRpcV2CborClientProtocol(_PROTOCOL_SETTINGS) + self.retry_strategy = retry_strategy + self.transport = transport or AIOHTTPClient() + + def set_auth_scheme(self, scheme: AsyncAuthScheme[Any, Any, Any, Any]) -> None: + "Set an auth scheme under its scheme ID." + self.auth_schemes[scheme.scheme_id] = scheme + + +type Plugin = Callable[[AsyncConfig], None] +"A callable that customizes the client configuration." diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/client.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/client.py new file mode 100644 index 000000000..1cc76139a --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/client.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +from typing import Unpack, overload + +from smithy_core.client import Client +from smithy_http.plugins import user_agent_plugin + +from api_key_auth_client import models +from api_key_auth_client.config import Config, Plugin + + +class ApiKeyService(Client[Config]): + "A service that authenticates with an API key." + + _client_plugins = (user_agent_plugin,) + + @overload + def get_thing( + self, + request: models.GetThingInput | models.GetThingInputDict, + /, + *, + plugins: list[Plugin] | None = None, + ) -> models.GetThingOutput: ... + + @overload + def get_thing( + self, + /, + *, + plugins: list[Plugin] | None = None, + **kwargs: Unpack[models.GetThingInputDict], + ) -> models.GetThingOutput: + """ + Uses the service's API key auth. + + :param plugins: Callables that change the configuration for this call + only. + """ + + def get_thing( + self, /, *args: object, plugins: list[Plugin] | None = None, **kwargs: object + ) -> models.GetThingOutput: + return self._invoke( + self._select_input(models.GET_THING, args, kwargs), + models.GET_THING, + [], + plugins, + ) + + @overload + def health( + self, + request: models.HealthInput | models.HealthInputDict, + /, + *, + plugins: list[Plugin] | None = None, + ) -> models.HealthOutput: ... + + @overload + def health( + self, + /, + *, + plugins: list[Plugin] | None = None, + **kwargs: Unpack[models.HealthInputDict], + ) -> models.HealthOutput: + """ + Needs no auth. + + :param plugins: Callables that change the configuration for this call + only. + """ + + def health( + self, /, *args: object, plugins: list[Plugin] | None = None, **kwargs: object + ) -> models.HealthOutput: + return self._invoke( + self._select_input(models.HEALTH, args, kwargs), + models.HEALTH, + [], + plugins, + ) + + @overload + def ping( + self, + request: models.PingInput | models.PingInputDict, + /, + *, + plugins: list[Plugin] | None = None, + ) -> models.PingOutput: ... + + @overload + def ping( + self, + /, + *, + plugins: list[Plugin] | None = None, + **kwargs: Unpack[models.PingInputDict], + ) -> models.PingOutput: + """ + Sends the API key when it has one. + + :param plugins: Callables that change the configuration for this call + only. + """ + + def ping( + self, /, *args: object, plugins: list[Plugin] | None = None, **kwargs: object + ) -> models.PingOutput: + return self._invoke( + self._select_input(models.PING, args, kwargs), + models.PING, + [], + plugins, + ) + + def _new_config(self) -> Config: + return Config() diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/config.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/config.py new file mode 100644 index 000000000..74922ff65 --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/config.py @@ -0,0 +1,121 @@ +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, cast + +from smithy_core.auth import DefaultAuthResolver +from smithy_core.endpoints import BddEndpointResolver +from smithy_core.interceptors import Interceptor +from smithy_core.interfaces import ( + ClientProtocol, + ClientTransport, + EndpointResolver, + ProtocolConstructor, + ProtocolSettings, + URI, +) +from smithy_core.interfaces.auth import AuthScheme, AuthSchemeResolver +from smithy_core.interfaces.identity import IdentityResolver +from smithy_core.interfaces.retries import RetryStrategy +from smithy_core.retries import RetryStrategyOptions +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.identity.apikey import APIKeyIdentityResolver +from smithy_http.protocols import RpcV2CborClientProtocol +from smithy_http.urllib3 import Urllib3HTTPClient + +from api_key_auth_client._private.endpoints import BDD +from api_key_auth_client._private.schemas import API_KEY_SERVICE + +_PROTOCOL_SETTINGS = ProtocolSettings( + namespace="example.apikey", + service_target="ApiKeyService", + version="2026-11-17", + service_schema=API_KEY_SERVICE, +) + + +@dataclass(init=False) +class Config: + "Configuration for ApiKeyService." + + api_key: str | None + "The API key to send along with requests." + + api_key_identity_resolver: ( + IdentityResolver[APIKeyIdentity, APIKeyIdentityProperties] | None + ) + "Resolves the API key." + + auth_scheme_resolver: AuthSchemeResolver + "Determines the auth scheme for each operation." + + auth_schemes: dict[ShapeID, AuthScheme[Any, Any, Any, Any]] + "Auth schemes by auth scheme ID." + + endpoint_resolver: EndpointResolver + "Resolves the endpoint of each operation." + + endpoint_uri: str | URI | None + "The endpoint URI, read by the endpoint rules as ``SDK::Endpoint``." + + interceptors: list[Interceptor[Any, Any, Any, Any]] + "Hooks called during the execution of a request." + + protocol: ClientProtocol[Any, Any] + "Serializes requests and deserializes responses." + + retry_strategy: RetryStrategy | RetryStrategyOptions | None + "The retry strategy, or options to create one." + + transport: ClientTransport[Any, Any] + "Sends requests, such as an HTTP client." + + def __init__( + self, + *, + api_key: str | None = None, + api_key_identity_resolver: IdentityResolver[ + APIKeyIdentity, APIKeyIdentityProperties + ] + | None = None, + auth_scheme_resolver: AuthSchemeResolver | None = None, + auth_schemes: dict[ShapeID, AuthScheme[Any, Any, Any, Any]] | None = None, + endpoint_resolver: EndpointResolver | None = None, + endpoint_uri: str | URI | None = None, + interceptors: list[Interceptor[Any, Any, Any, Any]] | None = None, + protocol: ClientProtocol[Any, Any] + | ProtocolConstructor[ClientProtocol[Any, Any]] + | None = None, + retry_strategy: RetryStrategy | RetryStrategyOptions | None = None, + transport: ClientTransport[Any, Any] | None = None, + ) -> None: + self.api_key = api_key + self.api_key_identity_resolver = ( + api_key_identity_resolver or APIKeyIdentityResolver() + ) + self.auth_scheme_resolver = auth_scheme_resolver or DefaultAuthResolver() + self.auth_schemes = auth_schemes or { + ShapeID("smithy.api#httpApiKeyAuth"): APIKeyAuthScheme( + name="Authorization", location=APIKeyLocation.HEADER, scheme="ApiKey" + ), + } + self.endpoint_resolver = endpoint_resolver or BddEndpointResolver(BDD) + self.endpoint_uri = endpoint_uri + self.interceptors = interceptors or [] + if isinstance(protocol, type): + protocol = protocol(_PROTOCOL_SETTINGS) + self.protocol = cast( + ClientProtocol[Any, Any], protocol + ) or RpcV2CborClientProtocol(_PROTOCOL_SETTINGS) + self.retry_strategy = retry_strategy + self.transport = transport or Urllib3HTTPClient() + + def set_auth_scheme(self, scheme: AuthScheme[Any, Any, Any, Any]) -> None: + "Set an auth scheme under its scheme ID." + self.auth_schemes[scheme.scheme_id] = scheme + + +type Plugin = Callable[[Config], None] +"A callable that customizes the client configuration." diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/models.py b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/models.py new file mode 100644 index 000000000..5140b3314 --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/models.py @@ -0,0 +1,77 @@ +from smithy_core._dynamic_models import ModelRegistry +from smithy_core.exceptions import ModeledError + +from ._private import schemas + + +class ServiceError(ModeledError): + """ + Base error for all errors in the service. + + Some exceptions do not extend from this class, including synthetic, + implicit, and shared exception types. + """ + + +_MODEL_INDEX = { + "GetThingInput": "GET_THING_INPUT", + "GetThingOutput": "GET_THING_OUTPUT", + "HealthInput": "HEALTH_INPUT", + "HealthOutput": "HEALTH_OUTPUT", + "PingInput": "PING_INPUT", + "PingOutput": "PING_OUTPUT", +} + +_RENAMES: dict[str, str] = {} + +_TARGET_NAMES: dict[str, str] = {} + +_OPERATIONS: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = { + "GET_THING": ( + (), + ("smithy.api#httpApiKeyAuth",), + ), + "HEALTH": ( + (), + ("smithy.api#noAuth",), + ), + "PING": ( + (), + ("smithy.api#httpApiKeyAuth", "smithy.api#noAuth"), + ), +} + +_MODEL_NAMES = tuple(_MODEL_INDEX) +__all__ = ("ServiceError", *_MODEL_NAMES, *_OPERATIONS) # pyright: ignore[reportUnsupportedDunderAll] + + +_registry = ModelRegistry( + schemas, + renames=_RENAMES, + index=_MODEL_INDEX, + target_names=_TARGET_NAMES, + shape_names=frozenset( + { + "GetThingInput", + "GetThingOutput", + "HealthInput", + "HealthOutput", + "PingInput", + "PingOutput", + } + ), + service_error="ServiceError", +) +del schemas, ModelRegistry, ModeledError + + +def __getattr__(name: str): + if (data := _OPERATIONS.get(name)) is not None: + return globals().setdefault(name, _registry.build_operation(name, *data)) + value = _registry.build(name) + globals()[name] = value + return value + + +def __dir__() -> list[str]: + return sorted({*globals(), *__all__}) diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/models.pyi b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/models.pyi new file mode 100644 index 000000000..78bb20062 --- /dev/null +++ b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/models.pyi @@ -0,0 +1,104 @@ +from dataclasses import dataclass +from typing import Self, TypedDict + +from smithy_core.deserializers import ShapeDeserializer +from smithy_core.exceptions import ModeledError +from smithy_core.response import ResponseMetadata +from smithy_core.schemas import APIOperation +from smithy_core.serializers import ShapeSerializer + +__all__ = [ + "GET_THING", + "HEALTH", + "PING", + "GetThingInput", + "GetThingOutput", + "HealthInput", + "HealthOutput", + "PingInput", + "PingOutput", + "ServiceError", +] + +class _SerdeShape: + def serialize(self, serializer: ShapeSerializer) -> None: ... + def serialize_members(self, serializer: ShapeSerializer) -> None: ... + @classmethod + def deserialize(cls, deserializer: ShapeDeserializer) -> Self: ... + +class ServiceError(ModeledError): + """ + Base error for all errors in the service. + + Some exceptions do not extend from this class, including synthetic, + implicit, and shared exception types. + """ + +@dataclass(kw_only=True) +class GetThingInput(_SerdeShape): + "Dataclass for GetThingInput structure." + + name: str | None = ... + +class GetThingInputDict(TypedDict, total=False): + "Dictionary form of `GetThingInput`." + + name: str | None + +@dataclass(kw_only=True) +class GetThingOutput(_SerdeShape): + "Dataclass for GetThingOutput structure." + + value: 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 HealthInput(_SerdeShape): + "Dataclass for HealthInput structure." + +class HealthInputDict(TypedDict, total=False): + "Dictionary form of `HealthInput`." + +@dataclass(kw_only=True) +class HealthOutput(_SerdeShape): + "Dataclass for HealthOutput structure." + + 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 PingInput(_SerdeShape): + "Dataclass for PingInput structure." + +class PingInputDict(TypedDict, total=False): + "Dictionary form of `PingInput`." + +@dataclass(kw_only=True) +class PingOutput(_SerdeShape): + "Dataclass for PingOutput structure." + + 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. + """ + +GET_THING: APIOperation[GetThingInput, GetThingOutput] +HEALTH: APIOperation[HealthInput, HealthOutput] +PING: APIOperation[PingInput, PingOutput] diff --git a/codegen-output-py/api-key-auth-client/src/api_key_auth_client/py.typed b/codegen-output-py/api-key-auth-client/src/api_key_auth_client/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/designs/codegen/client.md b/designs/codegen/client.md index b928cd108..c51505fc1 100644 --- a/designs/codegen/client.md +++ b/designs/codegen/client.md @@ -5,7 +5,8 @@ This document describes how the Python generator produces client packages. It defines client settings, operation discovery, I/O normalization, client symbols, the client plan, operation and schema emission, protocol selection, -endpoint rules, endpoint tests, and the generated client and config modules. +endpoint rules, endpoint tests, auth, and the generated client and config +modules. ## Goals @@ -257,6 +258,31 @@ service lacks, or a member its input lacks, fails generation. The module marks its tests with `pytest.mark.asyncio`. The package's `test` dependency group adds `pytest`, `pytest-asyncio`, and `smithy-test`. +## Auth + +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: + +| Part | Sync | Async | +| --- | --- | --- | +| Scheme | `APIKeyAuthScheme` | `AsyncAPIKeyAuthScheme` | +| `api_key_identity_resolver` default | `APIKeyIdentityResolver` | `AsyncAPIKeyIdentityResolver` | + +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. + +Both configs keep `DefaultAuthResolver`. It returns each operation's effective +auth scheme IDs in order, and the runtime signs with the first one in +`auth_schemes`. An operation whose schemes are only `noAuth`, such as one with +`@auth([])`, is sent unsigned. An operation with `@optionalAuth` is signed with +its first supported scheme. + +Generation fails for an operation whose effective schemes include neither +`noAuth` nor a supported scheme. + ## Clients and Configuration Service classes are thin subclasses of `Client[Config]` and @@ -314,10 +340,10 @@ runtime metadata. It covers `self`, `plugins`, defaults, and idempotency tokens. ## Supported Features -The generator supports unsigned, non-streaming RPCv2 CBOR and RPCv2 JSON -operations whose endpoint rules use the standard library. Models that require -auth schemes or event or data streams fail generation with a diagnostic naming -the operation and feature. +The generator supports non-streaming RPCv2 CBOR and RPCv2 JSON operations that +are unsigned or use API key auth, 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 credentials, region defaults, SigV4, query compatibility, AWS endpoint @@ -340,6 +366,11 @@ parameters. `models/endpoint-rules.smithy` is its source, and compiled by `CompileBdd`. The snapshot tests run the snapshot's generated endpoint tests. +The `api-key-auth-client` snapshot comes from `models/api-key-auth.smithy`, +assembled by Smithy into `models/api-key-auth.json`. Its operations use the +service's API key auth, `@auth([])`, and `@optionalAuth`. Tests check which +requests carry the key and that a missing key fails the call. + Client snapshots sit alongside the types snapshots and cover the provider-neutral RPCv2 CBOR and RPCv2 JSON projections. Checks cover deterministic regeneration, Ruff, strict Pyright consumer usage, lazy imports, diff --git a/packages/smithy-python/.changes/next-release/smithy-python-feature-f68b6cc3a9b648179a6f6f6fbbb1af4d.json b/packages/smithy-python/.changes/next-release/smithy-python-feature-f68b6cc3a9b648179a6f6f6fbbb1af4d.json new file mode 100644 index 000000000..3a1534b63 --- /dev/null +++ b/packages/smithy-python/.changes/next-release/smithy-python-feature-f68b6cc3a9b648179a6f6f6fbbb1af4d.json @@ -0,0 +1,4 @@ +{ + "type": "feature", + "description": "Generate clients for services with `httpApiKeyAuth`. Configs get `api_key` and `api_key_identity_resolver` fields, default to the API key auth scheme, and add `set_auth_scheme`." +} \ No newline at end of file diff --git a/packages/smithy-python/src/smithy_python/_auth.py b/packages/smithy-python/src/smithy_python/_auth.py new file mode 100644 index 000000000..8bc8937cc --- /dev/null +++ b/packages/smithy-python/src/smithy_python/_auth.py @@ -0,0 +1,161 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Auth scheme contributions to generated clients, keyed by auth trait ID. + +A contribution names the runtime auth schemes a client's configs default to, how +each is built from the service's auth trait, and the config fields its identity +resolver reads. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from types import MappingProxyType +from typing import Final + +from . import dependencies as _dependencies +from . import exceptions as _exceptions +from . import model as _model +from . import models as _models +from .symbols import TypeReference + +type Part = str | TypeReference +"""A piece of a generated line.""" + + +@dataclass(frozen=True, slots=True) +class ConfigField: + """A config field an auth scheme reads, in its sync and async forms.""" + + name: str + annotation: tuple[Part, ...] + async_annotation: tuple[Part, ...] + documentation: str + default: tuple[Part, ...] = () + """The value the field defaults to when unset, or nothing for None.""" + + async_default: tuple[Part, ...] = () + + +@dataclass(frozen=True, slots=True) +class AuthContribution: + """The runtime parts a generated client uses for one modeled auth scheme.""" + + scheme_id: _model.ShapeId + scheme: Callable[[_model.Node], tuple[Part, ...]] + """The sync auth scheme built from the service's auth trait value.""" + + async_scheme: Callable[[_model.Node], tuple[Part, ...]] + fields: tuple[ConfigField, ...] + + +def supported_schemes( + service: _model.ServiceShape, + contributions: Mapping[_model.ShapeId, AuthContribution] | None = None, +) -> tuple[AuthContribution, ...]: + """The contributions for the auth traits on a service, in shape ID order.""" + contributions = DEFAULT_AUTH_SCHEMES if contributions is None else contributions + return tuple( + contributions[trait_id] + for trait_id in sorted(service.traits, key=str) + if trait_id in contributions + ) + + +def _http(name: str, module: str) -> TypeReference: + return TypeReference( + name, f"smithy_http.{module}", dependencies=(_dependencies.SMITHY_HTTP,) + ) + + +def _core(name: str, module: str) -> TypeReference: + return TypeReference( + name, f"smithy_core.{module}", dependencies=(_dependencies.SMITHY_CORE,) + ) + + +def _api_key_arguments(trait: _model.Node) -> tuple[Part, ...]: + if not isinstance(trait, Mapping): + raise _exceptions.CodegenError("Invalid httpApiKeyAuth trait") + name = trait.get("name") + location = trait.get("in") + scheme = trait.get("scheme") + if not isinstance(name, str) or location not in ("header", "query"): + raise _exceptions.CodegenError( + "Invalid httpApiKeyAuth trait: needs a name and an in of header or query" + ) + if scheme is not None and not isinstance(scheme, str): + raise _exceptions.CodegenError("Invalid httpApiKeyAuth trait: bad scheme") + arguments: tuple[Part, ...] = ( + "(name=", + _quote(name), + ", location=", + _API_KEY_LOCATION, + ".", + location.upper(), + ) + if scheme is not None: + arguments += (", scheme=", _quote(scheme)) + return (*arguments, ")") + + +def _quote(value: str) -> str: + return _models._quote(value) # pyright: ignore[reportPrivateUsage] + + +_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_IDENTITY, + ", ", + _API_KEY_IDENTITY_PROPERTIES, + "]", +) + +HTTP_API_KEY_AUTH: Final = AuthContribution( + scheme_id=_model.ShapeId("smithy.api", "httpApiKeyAuth"), + scheme=lambda trait: ( + _http("APIKeyAuthScheme", "auth.apikey"), + *_api_key_arguments(trait), + ), + async_scheme=lambda trait: ( + _http("AsyncAPIKeyAuthScheme", "aio.auth.apikey"), + *_api_key_arguments(trait), + ), + fields=( + ConfigField( + name="api_key", + annotation=("str | None",), + async_annotation=("str | None",), + documentation="The API key to send along with requests.", + ), + ConfigField( + name="api_key_identity_resolver", + annotation=( + _core("IdentityResolver", "interfaces.identity"), + *_IDENTITY_ARGUMENTS, + " | None", + ), + async_annotation=( + _core("AsyncIdentityResolver", "aio.interfaces.identity"), + *_IDENTITY_ARGUMENTS, + " | None", + ), + documentation="Resolves the API key.", + default=(_http("APIKeyIdentityResolver", "identity.apikey"), "()"), + async_default=( + _http("AsyncAPIKeyIdentityResolver", "aio.identity.apikey"), + "()", + ), + ), + ), +) +"""API key auth, from the ``smithy.api#httpApiKeyAuth`` trait.""" + +DEFAULT_AUTH_SCHEMES: Final[Mapping[_model.ShapeId, AuthContribution]] = ( + MappingProxyType({HTTP_API_KEY_AUTH.scheme_id: HTTP_API_KEY_AUTH}) +) +"""The auth schemes generated clients support, by auth trait ID.""" diff --git a/packages/smithy-python/src/smithy_python/_client_emitter.py b/packages/smithy-python/src/smithy_python/_client_emitter.py index 01e1320ca..4071bc5ae 100644 --- a/packages/smithy-python/src/smithy_python/_client_emitter.py +++ b/packages/smithy-python/src/smithy_python/_client_emitter.py @@ -7,7 +7,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Final -from . import _endpoint_tests, _endpoints, _package +from . import _auth, _endpoint_tests, _endpoints, _package from . import dependencies as _dependencies from . import exceptions as _exceptions from . import model as _model @@ -26,9 +26,16 @@ def check_supported(plan: ClientPlan) -> None: :raises CodegenError: Naming the first unsupported operation and feature. """ + service = plan.selection.service + assert service is not None # noqa: S101 - ClientPlan requires a service + supported = {_NO_AUTH} | { + scheme.scheme_id for scheme in _auth.supported_schemes(service) + } for operation, exports in zip(plan.operations, plan.models.operations, strict=True): shape = operation.operation - if _NO_AUTH not in exports.auth_scheme_ids: + # The runtime signs with the first scheme the config supports, so an + # operation needs one, or noAuth, to send a request. + if not supported.intersection(exports.auth_scheme_ids): schemes = ", ".join(map(str, exports.auth_scheme_ids)) raise _exceptions.CodegenError( f"Operation {shape.id} requires auth ({schemes}), which client " @@ -51,7 +58,12 @@ def plan_endpoints(plan: ClientPlan) -> _endpoints.EndpointPlan: """ service = plan.selection.service assert service is not None # noqa: S101 - ClientPlan requires a service - return _endpoints.plan_endpoints(service, reserved=_CONFIG_FIELDS) + auth_fields = { + field.name + for scheme in _auth.supported_schemes(service) + for field in scheme.fields + } + return _endpoints.plan_endpoints(service, reserved=_CONFIG_FIELDS | auth_fields) def write_client( @@ -294,8 +306,18 @@ def _write_config( writer.line() endpoint_resolver = _join(mode.endpoint_resolver) auth_schemes = ("dict[", _SHAPE_ID, ", ", mode.auth_scheme, "]") + schemes = _auth.supported_schemes(service) + auth_fields = [field for scheme in schemes for field in scheme.fields] retry = (_RETRY_STRATEGY, " | ", _RETRY_STRATEGY_OPTIONS) fields: tuple[tuple[str, tuple[str | TypeReference, ...], str], ...] = ( + *( + ( + field.name, + field.async_annotation if mode.is_async else field.annotation, + field.documentation, + ) + for field in auth_fields + ), ( "auth_scheme_resolver", (_AUTH_SCHEME_RESOLVER,), @@ -350,6 +372,11 @@ def _write_config( with writer.indent(): writer.line("self,") writer.line("*,") + for field in auth_fields: + annotation = ( + field.async_annotation if mode.is_async else field.annotation + ) + writer.line(field.name, ": ", *annotation, " = None,") writer.line( "auth_scheme_resolver: ", _AUTH_SCHEME_RESOLVER, " | None = None," ) @@ -370,12 +397,39 @@ def _write_config( writer.line(field.attribute, ": ", field.type, " | None = None,") writer.line(") -> None:") with writer.indent(): + for field in auth_fields: + default = field.async_default if mode.is_async else field.default + writer.line( + "self.", + field.name, + " = ", + field.name, + *((" or ", *default) if default else ()), + ) + # The default resolver orders each operation's effective auth schemes, + # so an operation with noAuth first, such as one with @auth([]), is + # sent unsigned. writer.line( "self.auth_scheme_resolver = auth_scheme_resolver or ", _DEFAULT_AUTH_RESOLVER, "()", ) - writer.line("self.auth_schemes = auth_schemes or {}") + if not schemes: + writer.line("self.auth_schemes = auth_schemes or {}") + else: + writer.line("self.auth_schemes = auth_schemes or {") + with writer.indent(): + for scheme in schemes: + build = scheme.async_scheme if mode.is_async else scheme.scheme + writer.line( + _SHAPE_ID, + "(", + _models._quote(str(scheme.scheme_id)), # pyright: ignore[reportPrivateUsage] + "): ", + *build(service.get_trait(scheme.scheme_id)), + ",", + ) + writer.line("}") writer.line( "self.endpoint_resolver = endpoint_resolver or ", _BDD_ENDPOINT_RESOLVER, @@ -401,6 +455,18 @@ def _write_config( writer.line("self.transport = transport or ", mode.transport, "()") for field in endpoints.client_context_fields: writer.line("self.", field.attribute, " = ", field.attribute) + if schemes: + writer.line() + writer.line( + "def set_auth_scheme(self, scheme: ", mode.auth_scheme, ") -> None:" + ) + with writer.indent(): + writer.line( + _models._quote( # pyright: ignore[reportPrivateUsage] + "Set an auth scheme under its scheme ID." + ) + ) + writer.line("self.auth_schemes[scheme.scheme_id] = scheme") writer.line() writer.line() writer.line("type Plugin = ", _CALLABLE, "[[", mode.config, "], None]") diff --git a/packages/smithy-python/tests/unit/test_client_generation.py b/packages/smithy-python/tests/unit/test_client_generation.py index 32bc70285..4af59a552 100644 --- a/packages/smithy-python/tests/unit/test_client_generation.py +++ b/packages/smithy-python/tests/unit/test_client_generation.py @@ -581,3 +581,50 @@ def test_services_without_endpoint_tests_get_no_test_module(tmp_path: Path) -> N _generate(tmp_path, "greeter_no_endpoint_tests", shapes) assert not (tmp_path / "tests").exists() assert "[dependency-groups]" not in (tmp_path / "pyproject.toml").read_text() + + +def _add_api_key(shapes: dict[str, Any], **trait: Any) -> None: + shapes["example#Greeter"]["traits"]["smithy.api#httpApiKeyAuth"] = trait or { + "name": "key", + "in": "query", + } + + +def test_api_key_auth_signs_requests_in_the_query( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + shapes = _shapes() + _add_api_key(shapes) + _generate(tmp_path, "greeter_api_key", shapes) + monkeypatch.syspath_prepend( # pyright: ignore[reportUnknownMemberType] + str(tmp_path / "src") + ) + package = importlib.import_module("greeter_api_key") + transport = _Transport(body=_cbor_map({})) + config = package.Config( + api_key="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.destination.query == "key=s3cret" + + +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. + _generate(tmp_path / "fallback", "greeter_fallback", shapes) + shapes["example#Greet"]["traits"]["smithy.api#auth"] = ["smithy.api#httpBearerAuth"] + with pytest.raises(CodegenError, match="Operation example#Greet requires auth"): + _generate(tmp_path / "bearer", "greeter_bearer", shapes) + + +def test_api_key_auth_trait_must_name_a_location(tmp_path: Path) -> None: + shapes = _shapes() + _add_api_key(shapes, name="key", **{"in": "body"}) + with pytest.raises(CodegenError, match="Invalid httpApiKeyAuth trait"): + _generate(tmp_path, "greeter_bad_api_key", shapes) diff --git a/scripts/codegen-output-py/client-projections.json b/scripts/codegen-output-py/client-projections.json index 620057790..ccaf9ffcc 100644 --- a/scripts/codegen-output-py/client-projections.json +++ b/scripts/codegen-output-py/client-projections.json @@ -1,4 +1,11 @@ { + "api-key-auth-client": { + "description": "Python client for the API key auth fixture", + "model": "models/api-key-auth.json", + "package": "api_key_auth_client", + "service": "example.apikey#ApiKeyService", + "version": "0.0.1" + }, "endpoint-rules-client": { "description": "Python client for the endpoint rules fixture", "model": "models/endpoint-rules.json", diff --git a/scripts/codegen-output-py/models/api-key-auth.json b/scripts/codegen-output-py/models/api-key-auth.json new file mode 100644 index 000000000..acaa66b09 --- /dev/null +++ b/scripts/codegen-output-py/models/api-key-auth.json @@ -0,0 +1,89 @@ +{ + "smithy": "2.0", + "shapes": { + "example.apikey#ApiKeyService": { + "type": "service", + "version": "2026-11-17", + "operations": [ + { + "target": "example.apikey#GetThing" + }, + { + "target": "example.apikey#Health" + }, + { + "target": "example.apikey#Ping" + } + ], + "traits": { + "smithy.api#documentation": "A service that authenticates with an API key.", + "smithy.api#httpApiKeyAuth": { + "name": "Authorization", + "in": "header", + "scheme": "ApiKey" + }, + "smithy.protocols#rpcv2Cbor": {} + } + }, + "example.apikey#GetThing": { + "type": "operation", + "input": { + "target": "example.apikey#GetThingInput" + }, + "output": { + "target": "example.apikey#GetThingOutput" + }, + "traits": { + "smithy.api#documentation": "Uses the service's API key auth." + } + }, + "example.apikey#GetThingInput": { + "type": "structure", + "members": { + "name": { + "target": "smithy.api#String" + } + }, + "traits": { + "smithy.api#input": {} + } + }, + "example.apikey#GetThingOutput": { + "type": "structure", + "members": { + "value": { + "target": "smithy.api#String" + } + }, + "traits": { + "smithy.api#output": {} + } + }, + "example.apikey#Health": { + "type": "operation", + "input": { + "target": "smithy.api#Unit" + }, + "output": { + "target": "smithy.api#Unit" + }, + "traits": { + "smithy.api#auth": [], + "smithy.api#documentation": "Needs no auth." + } + }, + "example.apikey#Ping": { + "type": "operation", + "input": { + "target": "smithy.api#Unit" + }, + "output": { + "target": "smithy.api#Unit" + }, + "traits": { + "smithy.api#documentation": "Sends the API key when it has one.", + "smithy.api#optionalAuth": {} + } + } + } +} diff --git a/scripts/codegen-output-py/models/api-key-auth.smithy b/scripts/codegen-output-py/models/api-key-auth.smithy new file mode 100644 index 000000000..55d50cdaf --- /dev/null +++ b/scripts/codegen-output-py/models/api-key-auth.smithy @@ -0,0 +1,31 @@ +$version: "2.0" + +namespace example.apikey + +use smithy.protocols#rpcv2Cbor + +/// A service that authenticates with an API key. +@rpcv2Cbor +@httpApiKeyAuth(name: "Authorization", in: "header", scheme: "ApiKey") +service ApiKeyService { + version: "2026-11-17" + operations: [GetThing, Health, Ping] +} + +/// Uses the service's API key auth. +operation GetThing { + input := { + name: String + } + output := { + value: String + } +} + +/// Needs no auth. +@auth([]) +operation Health {} + +/// Sends the API key when it has one. +@optionalAuth +operation Ping {} diff --git a/scripts/codegen-output-py/pyrightconfig.json b/scripts/codegen-output-py/pyrightconfig.json index e72b183fd..f5bf90172 100644 --- a/scripts/codegen-output-py/pyrightconfig.json +++ b/scripts/codegen-output-py/pyrightconfig.json @@ -8,6 +8,7 @@ "tests/_typecheck.py" ], "extraPaths": [ + "../../codegen-output-py/api-key-auth-client/src", "../../codegen-output-py/aws-json-1-0/src", "../../codegen-output-py/aws-json-1-1/src", "../../codegen-output-py/aws-query/src", diff --git a/scripts/codegen-output-py/tests/test_client_snapshots.py b/scripts/codegen-output-py/tests/test_client_snapshots.py index 30194a37d..f21f3ef35 100644 --- a/scripts/codegen-output-py/tests/test_client_snapshots.py +++ b/scripts/codegen-output-py/tests/test_client_snapshots.py @@ -18,6 +18,7 @@ import pytest from smithy_cbor import loads from smithy_core.aio.types import AsyncBytesReader +from smithy_core.exceptions import SmithyIdentityError from smithy_core.retries import SimpleRetryStrategy from smithy_http import HTTPResponse, tuples_to_fields from smithy_http.interfaces import HTTPRequest, HTTPRequestConfiguration @@ -159,3 +160,58 @@ def test_generated_endpoint_tests_pass() -> None: ) assert result.returncode == 0, result.stdout + result.stderr assert "14 passed, 1 skipped" in result.stdout + + +@pytest.fixture(scope="module") +def api_key_package() -> Iterator[ModuleType]: + source = _ROOT / "codegen-output-py/api-key-auth-client/src" + name = _PROJECTIONS["api-key-auth-client"]["package"] + sys.path.insert(0, str(source)) + try: + yield importlib.import_module(name) + finally: + sys.path.remove(str(source)) + for module in tuple(sys.modules): + if module == name or module.startswith(name + "."): + del sys.modules[module] + + +def _api_key_client(package: ModuleType, aio: bool, **config: Any) -> Any: + transport = (_AsyncTransport if aio else _Transport)(b"\xa0") + client = (package.AsyncApiKeyService if aio else package.ApiKeyService)( + (package.AsyncConfig if aio else package.Config)( + endpoint_uri="https://example.com", + transport=transport, + retry_strategy=SimpleRetryStrategy(max_attempts=1), + **config, + ) + ) + return client, transport + + +def _call(aio: bool, call: Any) -> Any: + return asyncio.run(call) if aio else call + + +@pytest.mark.parametrize("aio", [False, True]) +def test_api_key_auth_signs_by_operation( + api_key_package: ModuleType, aio: bool +) -> None: + client, transport = _api_key_client(api_key_package, aio, api_key="secret") + _call(aio, client.get_thing(name="a")) + _call(aio, client.ping()) + _call(aio, client.health()) + get_thing, ping, health = transport.requests + assert get_thing.fields["Authorization"].values == ["ApiKey secret"] + assert ping.fields["Authorization"].values == ["ApiKey secret"] + # @auth([]) leaves only noAuth, so the request is unsigned. + assert "Authorization" not in health.fields + + +@pytest.mark.parametrize("aio", [False, True]) +def test_api_key_auth_requires_a_key(api_key_package: ModuleType, aio: bool) -> None: + client, transport = _api_key_client(api_key_package, aio) + with pytest.raises(SmithyIdentityError, match="api_key was not set"): + _call(aio, client.get_thing(name="a")) + _call(aio, client.health()) + assert len(transport.requests) == 1 diff --git a/scripts/verifications/import-cost.json b/scripts/verifications/import-cost.json index 4c85d5545..3d55bef32 100644 --- a/scripts/verifications/import-cost.json +++ b/scripts/verifications/import-cost.json @@ -16,7 +16,7 @@ "smithy_json": 21, "smithy_json (all public modules)": 21, "smithy_python": 1, - "smithy_python (all public modules)": 26, + "smithy_python (all public modules)": 27, "smithy_test": 44, "smithy_test (all public modules)": 60, "smithy_xml": 20,