1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
//! Stedi SDK endpoint support.
#![allow(deprecated)]

use aws_smithy_http::endpoint::error::InvalidEndpointError;
use aws_smithy_http::endpoint::{Endpoint, EndpointPrefix};
use aws_types::region::{Region, SigningRegion};
use aws_types::SigningService;
use std::error::Error;
use std::fmt::Debug;

/// Endpoint to connect to an Stedi Service
///
/// An `StediEndpoint` captures all necessary information needed to connect to an Stedi service, including:
/// - The URI of the endpoint (needed to actually send the request)
/// - The name of the service (needed downstream for signing)
/// - The signing region (which may differ from the actual region)
#[derive(Clone, Debug)]
pub struct StediEndpoint {
    endpoint: Endpoint,
    credential_scope: CredentialScope,
}

impl StediEndpoint {
    /// Constructs a new Stedi endpoint.
    pub fn new(endpoint: Endpoint, credential_scope: CredentialScope) -> StediEndpoint {
        StediEndpoint {
            endpoint,
            credential_scope,
        }
    }

    /// Returns the underlying endpoint.
    pub fn endpoint(&self) -> &Endpoint {
        &self.endpoint
    }

    /// Returns the credential scope.
    pub fn credential_scope(&self) -> &CredentialScope {
        &self.credential_scope
    }

    /// Sets the endpoint on a given `uri` based on this endpoint
    pub fn set_endpoint(
        &self,
        uri: &mut http::Uri,
        endpoint_prefix: Option<&EndpointPrefix>,
    ) -> Result<(), InvalidEndpointError> {
        self.endpoint.set_endpoint(uri, endpoint_prefix)
    }
}

/// A boxed error.
pub type BoxError = Box<dyn Error + Send + Sync + 'static>;

/// Resolve the Stedi Endpoint for a given region
///
/// To provide a static endpoint, [`Endpoint`](aws_smithy_http::endpoint::Endpoint) implements this trait.
/// Example usage:
/// ```rust
/// # mod sftp {
/// # use stedi_sdk_config::endpoint::ResolveStediEndpoint;
/// # pub struct ConfigBuilder;
/// # impl ConfigBuilder {
/// #     pub fn endpoint(&mut self, resolver: impl ResolveStediEndpoint + 'static) {
/// #         // ...
/// #     }
/// # }
/// # pub struct Config;
/// # impl Config {
/// #     pub fn builder() -> ConfigBuilder {
/// #         ConfigBuilder
/// #     }
/// # }
/// # }
/// # fn wrapper() -> Result<(), aws_smithy_http::endpoint::error::InvalidEndpointError> {
/// use aws_smithy_http::endpoint::Endpoint;
/// let config = sftp::Config::builder()
///     .endpoint(Endpoint::immutable("http://localhost:8080")?);
/// #     Ok(())
/// # }
/// ```
/// Each Stedi service generates their own implementation of `ResolveStediEndpoint`.
pub trait ResolveStediEndpoint: Send + Sync + Debug {
    /// Resolves the Stedi endpoint for a given region.
    fn resolve_endpoint(&self, region: &Region) -> Result<StediEndpoint, BoxError>;
}

/// The scope for Stedi credentials.
#[derive(Clone, Default, Debug)]
pub struct CredentialScope {
    region: Option<SigningRegion>,
    service: Option<SigningService>,
}

impl CredentialScope {
    /// Creates a builder for [`CredentialScope`].
    pub fn builder() -> credential_scope::Builder {
        credential_scope::Builder::default()
    }
}

/// Types associated with [`CredentialScope`].
pub mod credential_scope {
    use crate::endpoint::CredentialScope;
    use aws_types::region::SigningRegion;
    use aws_types::SigningService;

    /// A builder for [`CredentialScope`].
    #[derive(Debug, Default)]
    pub struct Builder {
        region: Option<SigningRegion>,
        service: Option<SigningService>,
    }

    impl Builder {
        /// Sets the signing region.
        pub fn region(mut self, region: impl Into<SigningRegion>) -> Self {
            self.region = Some(region.into());
            self
        }

        /// Sets the signing service.
        pub fn service(mut self, service: impl Into<SigningService>) -> Self {
            self.service = Some(service.into());
            self
        }

        /// Constructs a [`CredentialScope`] from the builder.
        pub fn build(self) -> CredentialScope {
            CredentialScope {
                region: self.region,
                service: self.service,
            }
        }
    }
}

impl CredentialScope {
    /// Returns the signing region.
    pub fn region(&self) -> Option<&SigningRegion> {
        self.region.as_ref()
    }

    /// Returns the signing service.
    pub fn service(&self) -> Option<&SigningService> {
        self.service.as_ref()
    }

    /// Uses the values from `other` to fill in unconfigured parameters on this
    /// credential scope object.
    pub fn merge(&self, other: &CredentialScope) -> CredentialScope {
        CredentialScope {
            region: self.region.clone().or_else(|| other.region.clone()),
            service: self.service.clone().or_else(|| other.service.clone()),
        }
    }
}

/// An `Endpoint` can be its own resolver to support static endpoints
impl ResolveStediEndpoint for Endpoint {
    fn resolve_endpoint(&self, _region: &Region) -> Result<StediEndpoint, BoxError> {
        Ok(StediEndpoint {
            endpoint: self.clone(),
            credential_scope: Default::default(),
        })
    }
}

#[cfg(test)]
mod test {
    use crate::endpoint::CredentialScope;
    use aws_types::region::SigningRegion;
    use aws_types::SigningService;

    #[test]
    fn create_credentials_scope_from_strs() {
        let scope = CredentialScope::builder()
            .service("functions")
            .region("us")
            .build();
        assert_eq!(
            scope.service(),
            Some(&SigningService::from_static("functions"))
        );
        assert_eq!(scope.region(), Some(&SigningRegion::from_static("us")));
    }
}