cargo_lambda_remote/
lib.rs

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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use aws_config::{
    meta::region::RegionProviderChain,
    profile::{ProfileFileCredentialsProvider, ProfileFileRegionProvider},
    provider_config::ProviderConfig,
    retry::RetryConfig,
    BehaviorVersion,
};
use aws_types::{region::Region, SdkConfig};
use clap::Args;
use serde::{ser::SerializeStruct, Deserialize, Serialize};
pub mod tls;

const DEFAULT_REGION: &str = "us-east-1";

#[derive(Args, Clone, Debug, Default, Deserialize, Serialize)]
pub struct RemoteConfig {
    /// AWS configuration profile to use for authorization
    #[arg(short, long)]
    #[serde(default)]
    pub profile: Option<String>,

    /// AWS region to deploy, if there is no default
    #[arg(short, long)]
    #[serde(default)]
    pub region: Option<String>,

    /// AWS Lambda alias to associate the function to
    #[arg(short, long)]
    #[serde(default)]
    pub alias: Option<String>,

    /// Number of attempts to try failed operations
    #[arg(long, default_value = "1")]
    #[serde(default)]
    pub retry_attempts: Option<u32>,

    /// Custom endpoint URL to target
    #[arg(long)]
    #[serde(default)]
    pub endpoint_url: Option<String>,
}

impl RemoteConfig {
    fn retry_policy(&self) -> RetryConfig {
        let attempts = self.retry_attempts.unwrap_or(1);
        RetryConfig::standard().with_max_attempts(attempts)
    }

    pub async fn sdk_config(&self, retry: Option<RetryConfig>) -> SdkConfig {
        let explicit_region = self.region.clone().map(Region::new);

        let region_provider = RegionProviderChain::first_try(explicit_region.clone())
            .or_default_provider()
            .or_else(Region::new(DEFAULT_REGION));

        let retry = retry.unwrap_or_else(|| self.retry_policy());
        let mut config_loader = if let Some(ref endpoint_url) = self.endpoint_url {
            aws_config::defaults(BehaviorVersion::latest())
                .endpoint_url(endpoint_url)
                .region(region_provider)
                .retry_config(retry)
        } else {
            aws_config::defaults(BehaviorVersion::latest())
                .region(region_provider)
                .retry_config(retry)
        };

        if let Some(profile) = &self.profile {
            let profile_region = ProfileFileRegionProvider::builder()
                .profile_name(profile)
                .build();

            let region_provider =
                RegionProviderChain::first_try(explicit_region).or_else(profile_region);
            let region = region_provider.region().await;

            let conf = ProviderConfig::default().with_region(region);

            let creds_provider = ProfileFileCredentialsProvider::builder()
                .profile_name(profile)
                .configure(&conf)
                .build();

            config_loader = config_loader
                .region(region_provider)
                .credentials_provider(creds_provider);
        }

        config_loader.load().await
    }

    pub fn count_fields(&self) -> usize {
        self.profile.is_some() as usize
            + self.region.is_some() as usize
            + self.alias.is_some() as usize
            + self.retry_attempts.is_some() as usize
            + self.endpoint_url.is_some() as usize
    }

    pub fn serialize_fields<S>(
        &self,
        state: &mut <S as serde::Serializer>::SerializeStruct,
    ) -> Result<(), S::Error>
    where
        S: serde::Serializer,
    {
        if let Some(ref profile) = self.profile {
            state.serialize_field("profile", profile)?;
        }
        if let Some(ref region) = self.region {
            state.serialize_field("region", region)?;
        }
        if let Some(ref alias) = self.alias {
            state.serialize_field("alias", alias)?;
        }
        if let Some(ref retry_attempts) = self.retry_attempts {
            state.serialize_field("retry_attempts", retry_attempts)?;
        }
        if let Some(ref endpoint_url) = self.endpoint_url {
            state.serialize_field("endpoint_url", endpoint_url)?;
        }

        Ok(())
    }
}

pub mod aws_sdk_config {
    pub use aws_types::SdkConfig;
}
pub use aws_sdk_lambda;

#[cfg(test)]
mod tests {
    use aws_sdk_lambda::config::{ProvideCredentials, Region};

    use crate::RemoteConfig;

    fn setup() {
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        std::env::set_var(
            "AWS_CONFIG_FILE",
            format!("{manifest_dir}/test-data/aws_config"),
        );
        std::env::set_var(
            "AWS_SHARED_CREDENTIALS_FILE",
            format!("{manifest_dir}/test-data/aws_credentials"),
        );
    }

    /// Specify a profile which does not exist
    /// Expectations:
    /// - Region is undefined
    /// - Credentials are undefined
    #[tokio::test]
    async fn undefined_profile() {
        setup();

        let args = RemoteConfig {
            profile: Some("durian".to_owned()),
            region: None,
            alias: None,
            retry_attempts: Some(1),
            endpoint_url: None,
        };

        let config = args.sdk_config(None).await;
        let creds = config
            .credentials_provider()
            .unwrap()
            .provide_credentials()
            .await;

        assert_eq!(config.region(), None);
        assert!(creds.is_err());
    }

    /// Specify a profile which exists in the credentials file but not in the config file
    /// Expectations:
    /// - Region is undefined
    /// - Credentials are used from the profile
    #[tokio::test]
    async fn undefined_profile_with_creds() {
        setup();

        let args = RemoteConfig {
            profile: Some("cherry".to_owned()),
            region: None,
            alias: None,
            retry_attempts: Some(1),
            endpoint_url: None,
        };

        let config = args.sdk_config(None).await;
        let creds = config
            .credentials_provider()
            .unwrap()
            .provide_credentials()
            .await
            .unwrap();

        assert_eq!(config.region(), None);
        assert_eq!(creds.access_key_id(), "CCCCCCCCCCCCCCCCCCCC");
    }

    /// Specify a profile which has a region associated to it
    /// Expectations:
    /// - Region is used from the profile
    /// - Credentials are used from the profile
    #[tokio::test]
    async fn profile_with_region() {
        setup();

        let args = RemoteConfig {
            profile: Some("apple".to_owned()),
            region: None,
            alias: None,
            retry_attempts: Some(1),
            endpoint_url: None,
        };

        let config = args.sdk_config(None).await;
        let creds = config
            .credentials_provider()
            .unwrap()
            .provide_credentials()
            .await
            .unwrap();

        assert_eq!(config.region(), Some(&Region::from_static("ca-central-1")));
        assert_eq!(creds.access_key_id(), "AAAAAAAAAAAAAAAAAAAA");
    }

    /// Specify a profile which does not have a region associated to it
    /// Expectations:
    /// - Region is undefined
    /// - Credentials are used from the profile
    #[tokio::test]
    async fn profile_without_region() {
        setup();

        let args = RemoteConfig {
            profile: Some("banana".to_owned()),
            region: None,
            alias: None,
            retry_attempts: Some(1),
            endpoint_url: None,
        };

        let config = args.sdk_config(None).await;
        let creds = config
            .credentials_provider()
            .unwrap()
            .provide_credentials()
            .await
            .unwrap();

        assert_eq!(config.region(), None);
        assert_eq!(creds.access_key_id(), "BBBBBBBBBBBBBBBBBBBB");
    }

    /// Use the default profile which has a region associated to it
    /// Expectations:
    /// - Region is used from the profile
    /// - Credentials are used from the profile
    #[tokio::test]
    async fn default_profile() {
        setup();

        let args = RemoteConfig {
            profile: None,
            region: None,
            alias: None,
            retry_attempts: Some(1),
            endpoint_url: None,
        };

        let config = args.sdk_config(None).await;
        let creds = config
            .credentials_provider()
            .unwrap()
            .provide_credentials()
            .await
            .unwrap();

        assert_eq!(config.region(), Some(&Region::from_static("af-south-1")));
        assert_eq!(creds.access_key_id(), "DDDDDDDDDDDDDDDDDDDD");
    }
}