aws_smithy_runtime_api/client/
auth.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! APIs for request authentication.
7
8use crate::box_error::BoxError;
9use crate::client::identity::{Identity, SharedIdentityResolver};
10use crate::client::orchestrator::HttpRequest;
11use crate::client::runtime_components::sealed::ValidateConfig;
12use crate::client::runtime_components::{GetIdentityResolver, RuntimeComponents};
13use crate::impl_shared_conversions;
14use aws_smithy_types::config_bag::{ConfigBag, FrozenLayer, Storable, StoreReplace};
15use aws_smithy_types::type_erasure::TypeErasedBox;
16use aws_smithy_types::Document;
17use std::borrow::Cow;
18use std::fmt;
19use std::sync::Arc;
20
21/// Auth schemes for the HTTP `Authorization` header.
22#[cfg(feature = "http-auth")]
23pub mod http;
24
25/// Static auth scheme option resolver.
26pub mod static_resolver;
27
28/// The output type from the [`ResolveAuthSchemeOptions::resolve_auth_scheme_options_v2`]
29///
30/// The resolver returns a list of these, in the order the auth scheme resolver wishes to use them.
31#[derive(Clone, Debug)]
32pub struct AuthSchemeOption {
33    scheme_id: AuthSchemeId,
34    properties: Option<FrozenLayer>,
35}
36
37impl AuthSchemeOption {
38    /// Builder struct for [`AuthSchemeOption`]
39    pub fn builder() -> AuthSchemeOptionBuilder {
40        AuthSchemeOptionBuilder::default()
41    }
42
43    /// Returns [`AuthSchemeId`], the ID of the scheme
44    pub fn scheme_id(&self) -> &AuthSchemeId {
45        &self.scheme_id
46    }
47
48    /// Returns optional properties for identity resolution or signing
49    ///
50    /// This config layer is applied to the [`ConfigBag`] to ensure the information is
51    /// available during both the identity resolution and signature generation processes.
52    pub fn properties(&self) -> Option<FrozenLayer> {
53        self.properties.clone()
54    }
55}
56
57impl From<AuthSchemeId> for AuthSchemeOption {
58    fn from(auth_scheme_id: AuthSchemeId) -> Self {
59        AuthSchemeOption::builder()
60            .scheme_id(auth_scheme_id)
61            .build()
62            .expect("required fields set")
63    }
64}
65
66/// Builder struct for [`AuthSchemeOption`]
67#[derive(Debug, Default)]
68pub struct AuthSchemeOptionBuilder {
69    scheme_id: Option<AuthSchemeId>,
70    properties: Option<FrozenLayer>,
71}
72
73impl AuthSchemeOptionBuilder {
74    /// Sets [`AuthSchemeId`] for the builder
75    pub fn scheme_id(mut self, auth_scheme_id: AuthSchemeId) -> Self {
76        self.set_scheme_id(Some(auth_scheme_id));
77        self
78    }
79
80    /// Sets [`AuthSchemeId`] for the builder
81    pub fn set_scheme_id(&mut self, auth_scheme_id: Option<AuthSchemeId>) {
82        self.scheme_id = auth_scheme_id;
83    }
84
85    /// Sets the properties for the builder
86    pub fn properties(mut self, properties: FrozenLayer) -> Self {
87        self.set_properties(Some(properties));
88        self
89    }
90
91    /// Sets the properties for the builder
92    pub fn set_properties(&mut self, properties: Option<FrozenLayer>) {
93        self.properties = properties;
94    }
95
96    /// Builds an [`AuthSchemeOption`], otherwise returns an [`AuthSchemeOptionBuilderError`] in the case of error
97    pub fn build(self) -> Result<AuthSchemeOption, AuthSchemeOptionBuilderError> {
98        let scheme_id = self
99            .scheme_id
100            .ok_or(ErrorKind::MissingRequiredField("auth_scheme_id"))?;
101        Ok(AuthSchemeOption {
102            scheme_id,
103            properties: self.properties,
104        })
105    }
106}
107
108#[derive(Debug)]
109enum ErrorKind {
110    MissingRequiredField(&'static str),
111}
112
113impl From<ErrorKind> for AuthSchemeOptionBuilderError {
114    fn from(kind: ErrorKind) -> Self {
115        Self { kind }
116    }
117}
118
119/// The error type returned when failing to build [`AuthSchemeOption`] from the builder
120#[derive(Debug)]
121pub struct AuthSchemeOptionBuilderError {
122    kind: ErrorKind,
123}
124
125impl fmt::Display for AuthSchemeOptionBuilderError {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        match self.kind {
128            ErrorKind::MissingRequiredField(name) => {
129                write!(f, "`{name}` is required")
130            }
131        }
132    }
133}
134
135impl std::error::Error for AuthSchemeOptionBuilderError {}
136
137/// New type around an auth scheme ID.
138///
139/// Each auth scheme must have a unique string identifier associated with it,
140/// which is used to refer to auth schemes by the auth scheme option resolver, and
141/// also used to select an identity resolver to use.
142#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
143pub struct AuthSchemeId {
144    scheme_id: Cow<'static, str>,
145}
146
147// See: https://doc.rust-lang.org/std/convert/trait.AsRef.html#reflexivity
148impl AsRef<AuthSchemeId> for AuthSchemeId {
149    fn as_ref(&self) -> &AuthSchemeId {
150        self
151    }
152}
153
154impl AuthSchemeId {
155    /// Creates a new auth scheme ID.
156    pub const fn new(scheme_id: &'static str) -> Self {
157        Self {
158            scheme_id: Cow::Borrowed(scheme_id),
159        }
160    }
161
162    /// Returns the string equivalent of this auth scheme ID.
163    #[deprecated(
164        note = "This function is no longer functional. Use `inner` instead",
165        since = "1.8.0"
166    )]
167    pub const fn as_str(&self) -> &'static str {
168        match self.scheme_id {
169            Cow::Borrowed(val) => val,
170            Cow::Owned(_) => {
171                // cannot obtain `&'static str` from `String` unless we use `Box::leak`
172                ""
173            }
174        }
175    }
176
177    /// Returns the string equivalent of this auth scheme ID.
178    pub fn inner(&self) -> &str {
179        &self.scheme_id
180    }
181}
182
183impl From<&'static str> for AuthSchemeId {
184    fn from(scheme_id: &'static str) -> Self {
185        Self::new(scheme_id)
186    }
187}
188
189impl From<Cow<'static, str>> for AuthSchemeId {
190    fn from(scheme_id: Cow<'static, str>) -> Self {
191        Self { scheme_id }
192    }
193}
194
195/// Parameters needed to resolve auth scheme options.
196///
197/// Most generated clients will use the [`StaticAuthSchemeOptionResolver`](static_resolver::StaticAuthSchemeOptionResolver),
198/// which doesn't require any parameters for resolution (and has its own empty params struct).
199///
200/// However, more complex auth scheme resolvers may need modeled parameters in order to resolve
201/// the auth scheme options. For those, this params struct holds a type erased box so that any
202/// kind of parameters can be contained within, and type casted by the auth scheme option resolver
203/// implementation.
204#[derive(Debug)]
205pub struct AuthSchemeOptionResolverParams(TypeErasedBox);
206
207impl AuthSchemeOptionResolverParams {
208    /// Creates a new [`AuthSchemeOptionResolverParams`].
209    pub fn new<T: fmt::Debug + Send + Sync + 'static>(params: T) -> Self {
210        Self(TypeErasedBox::new(params))
211    }
212
213    /// Returns the underlying parameters as the type `T` if they are that type.
214    pub fn get<T: fmt::Debug + Send + Sync + 'static>(&self) -> Option<&T> {
215        self.0.downcast_ref()
216    }
217}
218
219impl Storable for AuthSchemeOptionResolverParams {
220    type Storer = StoreReplace<Self>;
221}
222
223new_type_future! {
224    #[doc = "Future for [`ResolveAuthSchemeOptions::resolve_auth_scheme_options_v2`]."]
225    pub struct AuthSchemeOptionsFuture<'a, Vec<AuthSchemeOption>, BoxError>;
226}
227
228/// Resolver for auth scheme options.
229///
230/// The orchestrator needs to select an auth scheme to sign requests with, and potentially
231/// from several different available auth schemes. Smithy models have a number of ways
232/// to specify which operations can use which auth schemes under which conditions, as
233/// documented in the [Smithy spec](https://smithy.io/2.0/spec/authentication-traits.html).
234///
235/// The orchestrator uses the auth scheme option resolver runtime component to resolve
236/// an ordered list of options that are available to choose from for a given request.
237/// This resolver can be a simple static list, such as with the
238/// [`StaticAuthSchemeOptionResolver`](static_resolver::StaticAuthSchemeOptionResolver),
239/// or it can be a complex code generated resolver that incorporates parameters from both
240/// the model and the resolved endpoint.
241pub trait ResolveAuthSchemeOptions: Send + Sync + fmt::Debug {
242    #[deprecated(
243        note = "This method is deprecated, use `resolve_auth_scheme_options_v2` instead.",
244        since = "1.8.0"
245    )]
246    /// Returns a list of available auth scheme options to choose from.
247    fn resolve_auth_scheme_options(
248        &self,
249        _params: &AuthSchemeOptionResolverParams,
250    ) -> Result<Cow<'_, [AuthSchemeId]>, BoxError> {
251        unimplemented!("This method is deprecated, use `resolve_auth_scheme_options_v2` instead.");
252    }
253
254    #[allow(deprecated)]
255    /// Returns a list of available auth scheme options to choose from.
256    fn resolve_auth_scheme_options_v2<'a>(
257        &'a self,
258        params: &'a AuthSchemeOptionResolverParams,
259        _cfg: &'a ConfigBag,
260        _runtime_components: &'a RuntimeComponents,
261    ) -> AuthSchemeOptionsFuture<'a> {
262        AuthSchemeOptionsFuture::ready({
263            self.resolve_auth_scheme_options(params).map(|options| {
264                options
265                    .iter()
266                    .cloned()
267                    .map(|scheme_id| {
268                        AuthSchemeOption::builder()
269                            .scheme_id(scheme_id)
270                            .build()
271                            .expect("required fields set")
272                    })
273                    .collect::<Vec<_>>()
274            })
275        })
276    }
277}
278
279/// A shared auth scheme option resolver.
280#[derive(Clone, Debug)]
281pub struct SharedAuthSchemeOptionResolver(Arc<dyn ResolveAuthSchemeOptions>);
282
283impl SharedAuthSchemeOptionResolver {
284    /// Creates a new [`SharedAuthSchemeOptionResolver`].
285    pub fn new(auth_scheme_option_resolver: impl ResolveAuthSchemeOptions + 'static) -> Self {
286        Self(Arc::new(auth_scheme_option_resolver))
287    }
288}
289
290impl ResolveAuthSchemeOptions for SharedAuthSchemeOptionResolver {
291    #[allow(deprecated)]
292    fn resolve_auth_scheme_options(
293        &self,
294        params: &AuthSchemeOptionResolverParams,
295    ) -> Result<Cow<'_, [AuthSchemeId]>, BoxError> {
296        (*self.0).resolve_auth_scheme_options(params)
297    }
298
299    fn resolve_auth_scheme_options_v2<'a>(
300        &'a self,
301        params: &'a AuthSchemeOptionResolverParams,
302        cfg: &'a ConfigBag,
303        runtime_components: &'a RuntimeComponents,
304    ) -> AuthSchemeOptionsFuture<'a> {
305        (*self.0).resolve_auth_scheme_options_v2(params, cfg, runtime_components)
306    }
307}
308
309impl_shared_conversions!(
310    convert SharedAuthSchemeOptionResolver
311    from ResolveAuthSchemeOptions
312    using SharedAuthSchemeOptionResolver::new
313);
314
315/// An auth scheme.
316///
317/// Auth schemes have unique identifiers (the `scheme_id`),
318/// and provide an identity resolver and a signer.
319pub trait AuthScheme: Send + Sync + fmt::Debug {
320    /// Returns the unique identifier associated with this auth scheme.
321    ///
322    /// This identifier is used to refer to this auth scheme from the
323    /// [`ResolveAuthSchemeOptions`], and is also associated with
324    /// identity resolvers in the config.
325    fn scheme_id(&self) -> AuthSchemeId;
326
327    /// Returns the identity resolver that can resolve an identity for this scheme, if one is available.
328    ///
329    /// The [`AuthScheme`] doesn't actually own an identity resolver. Rather, identity resolvers
330    /// are configured as runtime components. The auth scheme merely chooses a compatible identity
331    /// resolver from the runtime components via the [`GetIdentityResolver`] trait. The trait is
332    /// given rather than the full set of runtime components to prevent complex resolution logic
333    /// involving multiple components from taking place in this function, since that's not the
334    /// intended use of this design.
335    fn identity_resolver(
336        &self,
337        identity_resolvers: &dyn GetIdentityResolver,
338    ) -> Option<SharedIdentityResolver>;
339
340    /// Returns the signing implementation for this auth scheme.
341    fn signer(&self) -> &dyn Sign;
342}
343
344/// Container for a shared auth scheme implementation.
345#[derive(Clone, Debug)]
346pub struct SharedAuthScheme(Arc<dyn AuthScheme>);
347
348impl SharedAuthScheme {
349    /// Creates a new [`SharedAuthScheme`] from the given auth scheme.
350    pub fn new(auth_scheme: impl AuthScheme + 'static) -> Self {
351        Self(Arc::new(auth_scheme))
352    }
353}
354
355impl AuthScheme for SharedAuthScheme {
356    fn scheme_id(&self) -> AuthSchemeId {
357        self.0.scheme_id()
358    }
359
360    fn identity_resolver(
361        &self,
362        identity_resolvers: &dyn GetIdentityResolver,
363    ) -> Option<SharedIdentityResolver> {
364        self.0.identity_resolver(identity_resolvers)
365    }
366
367    fn signer(&self) -> &dyn Sign {
368        self.0.signer()
369    }
370}
371
372impl ValidateConfig for SharedAuthScheme {}
373
374impl_shared_conversions!(convert SharedAuthScheme from AuthScheme using SharedAuthScheme::new);
375
376/// Signing implementation for an auth scheme.
377pub trait Sign: Send + Sync + fmt::Debug {
378    /// Sign the given request with the given identity, components, and config.
379    ///
380    /// If the provided identity is incompatible with this signer, an error must be returned.
381    fn sign_http_request(
382        &self,
383        request: &mut HttpRequest,
384        identity: &Identity,
385        auth_scheme_endpoint_config: AuthSchemeEndpointConfig<'_>,
386        runtime_components: &RuntimeComponents,
387        config_bag: &ConfigBag,
388    ) -> Result<(), BoxError>;
389}
390
391/// Endpoint configuration for the selected auth scheme.
392///
393/// The configuration held by this struct originates from the endpoint rule set in the service model.
394///
395/// This struct gets added to the request state by the auth orchestrator.
396#[non_exhaustive]
397#[derive(Clone, Debug)]
398pub struct AuthSchemeEndpointConfig<'a>(Option<&'a Document>);
399
400impl<'a> AuthSchemeEndpointConfig<'a> {
401    /// Creates an empty [`AuthSchemeEndpointConfig`].
402    pub fn empty() -> Self {
403        Self(None)
404    }
405
406    /// Returns the endpoint configuration as a [`Document`].
407    pub fn as_document(&self) -> Option<&'a Document> {
408        self.0
409    }
410}
411
412impl<'a> From<Option<&'a Document>> for AuthSchemeEndpointConfig<'a> {
413    fn from(value: Option<&'a Document>) -> Self {
414        Self(value)
415    }
416}
417
418impl<'a> From<&'a Document> for AuthSchemeEndpointConfig<'a> {
419    fn from(value: &'a Document) -> Self {
420        Self(Some(value))
421    }
422}
423
424/// An ordered list of [AuthSchemeId]s
425///
426/// Can be used to reorder already-resolved auth schemes by an auth scheme resolver.
427/// This list is intended as a hint rather than a strict override;
428/// any schemes not present in the resolved auth schemes will be ignored.
429#[derive(Clone, Debug, Default, Eq, PartialEq)]
430pub struct AuthSchemePreference {
431    preference_list: Vec<AuthSchemeId>,
432}
433
434impl Storable for AuthSchemePreference {
435    type Storer = StoreReplace<Self>;
436}
437
438impl IntoIterator for AuthSchemePreference {
439    type Item = AuthSchemeId;
440    type IntoIter = std::vec::IntoIter<Self::Item>;
441
442    fn into_iter(self) -> Self::IntoIter {
443        self.preference_list.into_iter()
444    }
445}
446
447impl<T> From<T> for AuthSchemePreference
448where
449    T: AsRef<[AuthSchemeId]>,
450{
451    fn from(slice: T) -> Self {
452        AuthSchemePreference {
453            preference_list: slice.as_ref().to_vec(),
454        }
455    }
456}