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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use std::os::unix::prelude::OsStrExt;

use mountpoint_s3_crt::{
    auth::signing_config::SigningAlgorithm,
    common::{allocator::Allocator, uri::Uri},
    s3::endpoint_resolver::{RequestContext, ResolvedEndpoint, ResolverError, RuleEngine},
};
use thiserror::Error;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AddressingStyle {
    /// Use virtual addressing if possible, but fall back to path addressing if necessary
    #[default]
    Automatic,
    /// Always use path addressing
    Path,
}

#[derive(Debug, Clone)]
pub struct AuthScheme {
    disable_double_encoding: bool,
    scheme_name: SigningAlgorithm,
    signing_name: String,
    signing_region: String,
}

impl AuthScheme {
    /// Get the siging name from [AuthScheme]
    pub fn signing_name(&self) -> &str {
        &self.signing_name
    }

    /// Get the signing region from [AuthScheme]
    pub fn signing_region(&self) -> &str {
        &self.signing_region
    }

    /// Get Disable double encoding value for [AuthScheme]
    pub fn disable_double_encoding(&self) -> bool {
        self.disable_double_encoding
    }

    /// Get the name of [AuthScheme]
    pub fn scheme_name(&self) -> SigningAlgorithm {
        self.scheme_name
    }
}

/// Configuration for resolution of S3 endpoints
#[derive(Debug, Clone)]
pub struct EndpointConfig {
    region: String,
    use_fips: bool,
    use_accelerate: bool,
    use_dual_stack: bool,
    endpoint: Option<Uri>,
    addressing_style: AddressingStyle,
}

impl EndpointConfig {
    /// Create a new endpoint configuration for a given region
    pub fn new(region: &str) -> Self {
        Self {
            region: region.to_owned(),
            use_fips: false,
            use_accelerate: false,
            use_dual_stack: false,
            endpoint: None,
            addressing_style: AddressingStyle::Automatic,
        }
    }

    /// Set region for a given endpoint config
    #[must_use = "EndpointConfig follows a builder pattern"]
    pub fn region(mut self, region: &str) -> Self {
        self.region = region.to_owned();
        self
    }

    /// use FIPS config for S3
    #[must_use = "EndpointConfig follows a builder pattern"]
    pub fn use_fips(mut self, fips: bool) -> Self {
        self.use_fips = fips;
        self
    }

    /// use Transfer Acceleration config for S3
    #[must_use = "EndpointConfig follows a builder pattern"]
    pub fn use_accelerate(mut self, accelerate: bool) -> Self {
        self.use_accelerate = accelerate;
        self
    }

    /// use dual stack config for S3
    #[must_use = "EndpointConfig follows a builder pattern"]
    pub fn use_dual_stack(mut self, dual_stack: bool) -> Self {
        self.use_dual_stack = dual_stack;
        self
    }

    /// Set predefined url for endpoint configuration
    #[must_use = "EndpointConfig follows a builder pattern"]
    pub fn endpoint(mut self, endpoint: Uri) -> Self {
        self.endpoint = Some(endpoint);
        self
    }

    /// Set addressing style for [EndpointConfig]
    #[must_use = "EndpointConfig follows a builder pattern"]
    pub fn addressing_style(mut self, addressing_style: AddressingStyle) -> Self {
        self.addressing_style = addressing_style;
        self
    }

    /// get the region from the [EndpointConfig]
    pub fn get_region(&self) -> &str {
        &self.region
    }

    /// get the fips config from the [EndpointConfig]
    pub fn get_fips(&self) -> bool {
        self.use_fips
    }

    /// get the transfer acceleration config from the [EndpointConfig]
    pub fn get_accelerate(&self) -> bool {
        self.use_accelerate
    }

    /// get the dual stack config from the [EndpointConfig]
    pub fn get_dual_stack(&self) -> bool {
        self.use_dual_stack
    }

    /// get the endpoint uri if provided from [EndpointConfig]
    pub fn get_endpoint(&self) -> Option<Uri> {
        self.endpoint.clone()
    }

    /// get the addressing style from the [EndpointConfig]
    pub fn get_addressing_style(&self) -> AddressingStyle {
        self.addressing_style
    }

    /// resolve the endpoint from the [EndpointConfig] and the bucket name
    pub fn resolve_for_bucket(&self, bucket: &str) -> Result<ResolvedEndpointInfo, EndpointError> {
        let allocator = Allocator::default();
        let mut endpoint_request_context: RequestContext = RequestContext::new(&allocator).unwrap();
        let endpoint_rule_engine = RuleEngine::new(&allocator).unwrap();

        endpoint_request_context
            .add_string(&allocator, "Region", &self.region)
            .unwrap();
        endpoint_request_context
            .add_string(&allocator, "Bucket", bucket)
            .unwrap();
        if let Some(endpoint_uri) = &self.endpoint {
            endpoint_request_context
                .add_string(&allocator, "Endpoint", endpoint_uri.as_os_str())
                .unwrap()
        };
        if self.use_fips {
            endpoint_request_context
                .add_boolean(&allocator, "UseFIPS", true)
                .unwrap()
        };
        if self.use_dual_stack {
            endpoint_request_context
                .add_boolean(&allocator, "UseDualStack", true)
                .unwrap()
        };
        if self.use_accelerate {
            endpoint_request_context
                .add_boolean(&allocator, "Accelerate", true)
                .unwrap()
        };
        if self.addressing_style == AddressingStyle::Path {
            endpoint_request_context
                .add_boolean(&allocator, "ForcePathStyle", true)
                .unwrap()
        };

        let resolved_endpoint = endpoint_rule_engine
            .resolve(endpoint_request_context)
            .map_err(EndpointError::UnresolvedEndpoint)?;

        Ok(ResolvedEndpointInfo(resolved_endpoint))
    }
}

/// Wrapper for [ResolvedEndpoint] from CRT to get [Uri] and [AuthScheme]
#[derive(Debug)]
pub struct ResolvedEndpointInfo(ResolvedEndpoint);

impl ResolvedEndpointInfo {
    /// Get the [Uri] from [ResolvedEndpointInfo]
    pub fn uri(&self) -> Result<Uri, EndpointError> {
        let allocator = Allocator::default();
        let endpoint_url = self.0.get_url();
        Uri::new_from_str(&allocator, endpoint_url)
            .map_err(|e| EndpointError::InvalidUri(InvalidUriError::CouldNotParse(e)))
    }

    /// Get the [AuthScheme] from [ResolvedEndpointInfo] for the signing config
    pub fn auth_scheme(&self) -> Result<AuthScheme, EndpointError> {
        // ResolvedEndpoint is wrapper for aws_endpoints_resolved_endpoint which has url, properties and header for the endpoint.
        // Property if in json format containing the AuthScheme. Egs. -
        // {\"authSchemes\":[{\"disableDoubleEncoding\":true,\"name\":\"sigv4\",\"signingName\":\"s3\",\"signingRegion\":\"us-east-2\"}]}
        let endpoint_properties = self.0.get_properties();
        let auth_scheme_data: serde_json::Value = serde_json::from_slice(endpoint_properties.as_bytes())?;
        let auth_scheme_value = auth_scheme_data["authSchemes"]
            .get(0)
            .ok_or_else(|| EndpointError::MissingAuthSchemeField("authSchemes"))?;
        let disable_double_encoding = auth_scheme_value["disableDoubleEncoding"]
            .as_bool()
            .ok_or_else(|| EndpointError::MissingAuthSchemeField("disableDoubleEncoding"))?;
        let scheme_name = auth_scheme_value["name"]
            .as_str()
            .ok_or_else(|| EndpointError::MissingAuthSchemeField("name"))?;
        let scheme_name = match scheme_name {
            "sigv4" => SigningAlgorithm::SigV4,
            "sigv4a" => SigningAlgorithm::SigV4A,
            _ => return Err(EndpointError::InvalidAuthSchemeField("name", scheme_name.to_owned())),
        };

        let signing_name = auth_scheme_value["signingName"]
            .as_str()
            .ok_or_else(|| EndpointError::MissingAuthSchemeField("signingName"))?;
        let signing_region = auth_scheme_value
            .get("signingRegion")
            .or_else(|| auth_scheme_value["signingRegionSet"].get(0))
            .and_then(|t| t.as_str())
            .ok_or_else(|| EndpointError::MissingAuthSchemeField("signingRegion or signingRegionSet"))?;

        Ok(AuthScheme {
            disable_double_encoding,
            scheme_name,
            signing_name: signing_name.to_owned(),
            signing_region: signing_region.to_owned(),
        })
    }
}

#[derive(Debug, Error)]
pub enum EndpointError {
    #[error("invalid URI")]
    InvalidUri(#[from] InvalidUriError),
    #[error("endpoint could not be resolved")]
    UnresolvedEndpoint(#[from] ResolverError),
    #[error("Endpoint properties could not be parsed")]
    ParseError(#[from] serde_json::Error),
    #[error("AuthScheme field missing: {0}")]
    MissingAuthSchemeField(&'static str),
    #[error("invalid value {1} for AuthScheme field {0}")]
    InvalidAuthSchemeField(&'static str, String),
}

#[derive(Debug, Error)]
pub enum InvalidUriError {
    #[error("URI could not be parsed")]
    CouldNotParse(#[from] mountpoint_s3_crt::common::error::Error),
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_virtual_addr() {
        let endpoint_config = EndpointConfig::new("eu-west-1").addressing_style(AddressingStyle::Automatic);
        let endpoint_uri = endpoint_config
            .resolve_for_bucket("doc-example-bucket")
            .unwrap()
            .uri()
            .unwrap();
        assert_eq!(
            "https://doc-example-bucket.s3.eu-west-1.amazonaws.com",
            endpoint_uri.as_os_str()
        );
    }

    #[test]
    fn test_path_addr_endpoint_arg() {
        let endpoint_config = EndpointConfig::new("eu-west-1")
            .addressing_style(AddressingStyle::Path)
            .endpoint(Uri::new_from_str(&Allocator::default(), "https://example.com").unwrap());
        let endpoint_uri = endpoint_config
            .resolve_for_bucket("doc-example-bucket")
            .unwrap()
            .uri()
            .unwrap();
        assert_eq!("https://example.com/doc-example-bucket", endpoint_uri.as_os_str());
    }

    #[test]
    fn test_endpoint_arg_with_region() {
        let endpoint_config = EndpointConfig::new("us-east-1")
            .endpoint(Uri::new_from_str(&Allocator::default(), "https://s3.eu-west-1.amazonaws.com").unwrap());
        let resolved_endpoint = endpoint_config.resolve_for_bucket("doc-example-bucket").unwrap();
        let endpoint_uri = resolved_endpoint.uri().unwrap();
        // region is ignored when endpoint_url is specified
        assert_eq!(
            "https://doc-example-bucket.s3.eu-west-1.amazonaws.com",
            endpoint_uri.as_os_str()
        );
        let endpoint_auth_scheme = resolved_endpoint.auth_scheme().unwrap();
        let signing_region = endpoint_auth_scheme.signing_region();
        //signing region is still the region provided
        assert_eq!(signing_region, "us-east-1");
    }

    #[test]
    fn test_fips_dual_stack() {
        let endpoint_config = EndpointConfig::new("eu-west-1").use_fips(true).use_dual_stack(true);
        let endpoint_uri = endpoint_config
            .resolve_for_bucket("doc-example-bucket")
            .unwrap()
            .uri()
            .unwrap();
        assert_eq!(
            "https://doc-example-bucket.s3-fips.dualstack.eu-west-1.amazonaws.com",
            endpoint_uri.as_os_str()
        );
    }

    #[test]
    fn test_dual_stack_accelerate() {
        let endpoint_config = EndpointConfig::new("eu-west-1")
            .use_accelerate(true)
            .use_dual_stack(true);
        let endpoint_uri = endpoint_config
            .resolve_for_bucket("doc-example-bucket")
            .unwrap()
            .uri()
            .unwrap();
        assert_eq!(
            "https://doc-example-bucket.s3-accelerate.dualstack.amazonaws.com",
            endpoint_uri.as_os_str()
        );
    }

    #[test]
    fn test_dual_stack_path_addr() {
        let endpoint_config = EndpointConfig::new("eu-west-1")
            .use_dual_stack(true)
            .addressing_style(AddressingStyle::Path);
        let endpoint_uri = endpoint_config
            .resolve_for_bucket("doc-example-bucket")
            .unwrap()
            .uri()
            .unwrap();
        assert_eq!(
            "https://s3.dualstack.eu-west-1.amazonaws.com/doc-example-bucket",
            endpoint_uri.as_os_str()
        );
    }

    #[test]
    fn test_arn_as_bucket() {
        let endpoint_config = EndpointConfig::new("eu-west-1");
        let endpoint_uri = endpoint_config
            .resolve_for_bucket("arn:aws:s3::accountID:accesspoint/s3-bucket-test.mrap")
            .unwrap()
            .uri()
            .unwrap();
        assert_eq!(
            "https://s3-bucket-test.mrap.accesspoint.s3-global.amazonaws.com",
            endpoint_uri.as_os_str()
        );
    }

    #[test]
    fn test_arn_override_region() {
        let endpoint_config = EndpointConfig::new("cn-north-1");
        // Also a test for China region
        let endpoint_uri = endpoint_config
            .resolve_for_bucket("arn:aws-cn:s3:cn-north-2:555555555555:accesspoint/china-region-ap")
            .unwrap()
            .uri()
            .unwrap();
        assert_eq!(
            "https://china-region-ap-555555555555.s3-accesspoint.cn-north-2.amazonaws.com.cn",
            endpoint_uri.as_os_str()
        );
    }

    #[test]
    fn test_outpost() {
        let endpoint_config = EndpointConfig::new("us-gov-west-1");
        let endpoint_uri = endpoint_config
            .resolve_for_bucket("mountpoint-o-o000s3-bucket-test0000000000000000000000000--op-s3")
            .unwrap()
            .uri()
            .unwrap();
        assert_eq!(
            "https://mountpoint-o-o000s3-bucket-test0000000000000000000000000--op-s3.op-000s3-bucket-test.s3-outposts.us-gov-west-1.amazonaws.com",
            endpoint_uri.as_os_str()
        );
    }

    #[test]
    fn test_bucket_arn() {
        let endpoint_config = EndpointConfig::new("eu-west-1");
        let endpoint_err = endpoint_config
            .resolve_for_bucket("arn:aws:s3:::testbucket")
            .unwrap_err();
        assert!(matches!(
            endpoint_err,
            EndpointError::UnresolvedEndpoint(ResolverError::EndpointNotResolved(_))
        ));
        if let EndpointError::UnresolvedEndpoint(ResolverError::EndpointNotResolved(str)) = endpoint_err {
            let err_str = "Invalid ARN: Unrecognized format: arn:aws:s3:::testbucket (type: testbucket)".to_owned();
            assert_eq!(str, err_str);
        }
    }

    #[test]
    fn test_auth_scheme_for_arn() {
        let endpoint_config = EndpointConfig::new("eu-west-1");
        let endpoint_auth_scheme = endpoint_config
            .resolve_for_bucket("arn:aws:s3::accountID:accesspoint/s3-bucket-test.mrap")
            .unwrap()
            .auth_scheme()
            .unwrap();

        let signing_region = endpoint_auth_scheme.signing_region();
        assert_eq!(signing_region, "*");
        let signing_name = endpoint_auth_scheme.signing_name();
        assert_eq!(signing_name, "s3");
    }

    #[test]
    fn test_auth_scheme_for_bucket() {
        let endpoint_config = EndpointConfig::new("eu-west-1");
        let endpoint_auth_scheme = endpoint_config
            .resolve_for_bucket("test-bucket")
            .unwrap()
            .auth_scheme()
            .unwrap();

        let signing_region = endpoint_auth_scheme.signing_region();
        assert_eq!(signing_region, "eu-west-1");
        let signing_name = endpoint_auth_scheme.signing_name();
        assert_eq!(signing_name, "s3");
    }
}