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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use {
    crate::{
        utils::{validate_account_id, validate_partition, validate_region, validate_service},
        ArnError,
    },
    serde::{de, Deserialize, Serialize},
    std::{
        cmp::Ordering,
        fmt::{Display, Formatter, Result as FmtResult},
        hash::Hash,
        str::FromStr,
    },
};

const PARTITION_START: usize = 4;

/// An Amazon Resource Name (ARN) representing an exact resource.
///
/// This is used to represent a known resource, such as an S3 bucket, EC2 instance, assumed role instance, etc. This is
/// _not_ used to represent resource _statements_ in the IAM Aspen policy language, which may contain wildcards.
///
/// [Arn] objects are immutable.
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub struct Arn {
    arn: String,
    service_start: usize,
    region_start: usize,
    account_id_start: usize,
    resource_start: usize,
}

impl Arn {
    /// Create a new ARN from the specified components.
    ///
    /// * `partition` - The partition the resource is in (required). This is usually `aws`, `aws-cn`, or `aws-us-gov`
    ///     for actual AWS resources, but may be any string meeting the rules specified in [validate_partition] for
    ///     non-AWS resources.
    /// * `service` - The service the resource belongs to (required). This is a service name like `ec2` or `s3`.
    ///     Non-AWS resources must conform to the naming rules specified in [validate_service].
    /// * `region` - The region the resource is in (optional). If the resource is regional (and may other regions
    ///     may have the resources with the same name), this is the region name. If the resource is global, this is
    ///     empty. This is usually a region name like `us-east-1` or `us-west-2`, but may be any string meeting the
    ///     rules specified in [validate_region].
    /// * `account_id` - The account ID the resource belongs to (optional). This is the 12-digit account ID or the
    ///     string `aws` for certain AWS-owned resources. Some resources (such as S3 buckets and objects) do not need
    ///     the account ID (the bucket name is globally unique within a partition), so this may be empty.
    /// * `resource` - The resource name (required). This is the name of the resource. The formatting is
    ///     service-specific, but must be a valid UTF-8 string.
    ///
    /// # Errors
    ///
    /// * If the partition is invalid, [ArnError::InvalidPartition] is returned.
    /// * If the service is invalid, [ArnError::InvalidService] is returned.
    /// * If the region is invalid, [ArnError::InvalidRegion] is returned.
    /// * If the account ID is invalid, [ArnError::InvalidAccountId] is returned.
    pub fn new(
        partition: &str,
        service: &str,
        region: &str,
        account_id: &str,
        resource: &str,
    ) -> Result<Self, ArnError> {
        validate_partition(partition)?;
        validate_service(service)?;
        if !region.is_empty() {
            validate_region(region)?
        }
        if !account_id.is_empty() {
            validate_account_id(account_id)?
        }

        // Safety: We have met the preconditions specified for new_unchecked above.
        unsafe { Ok(Self::new_unchecked(partition, service, region, account_id, resource)) }
    }

    /// Create a new ARN from the specified components, bypassing any validation.
    ///
    /// # Safety
    ///
    /// The following constraints must be met:
    ///
    /// * `partition` - Must meet the rules specified in [validate_partition].
    /// * `service` - Must meet the rules specified in [validate_service].
    /// * `region` - Must be empty or meet the rules specified in [validate_region].
    /// * `account_id` - Must be empty, a 12 ASCII digit account ID, or the string `aws`.
    /// * `resource` - A valid UTF-8 string.
    pub unsafe fn new_unchecked(
        partition: &str,
        service: &str,
        region: &str,
        account_id: &str,
        resource: &str,
    ) -> Self {
        let arn = format!("arn:{}:{}:{}:{}:{}", partition, service, region, account_id, resource);
        let service_start = PARTITION_START + partition.len() + 1;
        let region_start = service_start + service.len() + 1;
        let account_id_start = region_start + region.len() + 1;
        let resource_start = account_id_start + account_id.len() + 1;

        Self {
            arn,
            service_start,
            region_start,
            account_id_start,
            resource_start,
        }
    }

    /// Retrieve the partition the resource is in.
    #[inline]
    pub fn partition(&self) -> &str {
        &self.arn[PARTITION_START..self.service_start - 1]
    }

    /// Retrieve the service the resource belongs to.
    #[inline]
    pub fn service(&self) -> &str {
        &self.arn[self.service_start..self.region_start - 1]
    }

    /// Retrieve the region the resource is in.
    #[inline]
    pub fn region(&self) -> &str {
        &self.arn[self.region_start..self.account_id_start - 1]
    }

    /// Retrieve the account ID the resource belongs to.
    #[inline]
    pub fn account_id(&self) -> &str {
        &self.arn[self.account_id_start..self.resource_start - 1]
    }

    /// Retrieve the resource name.
    #[inline]
    pub fn resource(&self) -> &str {
        &self.arn[self.resource_start..]
    }
}

impl Display for Arn {
    /// Return the ARN.
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.write_str(&self.arn)
    }
}

/// Parse a string into an [Arn].
impl FromStr for Arn {
    /// [ArnError] is returned if the string is not a valid ARN.
    type Err = ArnError;

    /// Parse an ARN from a string.
    ///
    /// # Errors
    ///
    /// * If the ARN is not composed of 6 colon-separated components, [ArnError::InvalidArn] is returned.
    /// * If the ARN does not start with `arn:`, [ArnError::InvalidArn] is returned.
    /// * If the partition is invalid, [ArnError::InvalidPartition] is returned.
    /// * If the service is invalid, [ArnError::InvalidService] is returned.
    /// * If the region is invalid, [ArnError::InvalidRegion] is returned.
    /// * If the account ID is invalid, [ArnError::InvalidAccountId] is returned.
    fn from_str(s: &str) -> Result<Self, ArnError> {
        let parts: Vec<&str> = s.splitn(6, ':').collect();
        if parts.len() != 6 {
            return Err(ArnError::InvalidArn(s.to_string()));
        }

        if parts[0] != "arn" {
            return Err(ArnError::InvalidScheme(parts[0].to_string()));
        }

        Self::new(parts[1], parts[2], parts[3], parts[4], parts[5])
    }
}

/// Orders ARNs by partition, service, region, account ID, and resource.
impl PartialOrd for Arn {
    /// Returns the relative ordering between this and another ARN.
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Orders ARNs by partition, service, region, account ID, and resource.
impl Ord for Arn {
    /// Returns the relative ordering between this and another ARN.
    fn cmp(&self, other: &Self) -> Ordering {
        match self.partition().cmp(other.partition()) {
            Ordering::Equal => match self.service().cmp(other.service()) {
                Ordering::Equal => match self.region().cmp(other.region()) {
                    Ordering::Equal => match self.account_id().cmp(other.account_id()) {
                        Ordering::Equal => self.resource().cmp(other.resource()),
                        x => x,
                    },
                    x => x,
                },
                x => x,
            },
            x => x,
        }
    }
}

impl<'de> Deserialize<'de> for Arn {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::from_str(&s).map_err(de::Error::custom)
    }
}

impl Serialize for Arn {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.arn)
    }
}

#[cfg(test)]
mod test {
    use {
        super::Arn,
        crate::{
            utils::{validate_account_id, validate_region},
            ArnError,
        },
        pretty_assertions::assert_eq,
        std::{
            collections::hash_map::DefaultHasher,
            hash::{Hash, Hasher},
            str::FromStr,
        },
    };

    #[test]
    fn check_arn_derived() {
        let arn1a = Arn::from_str("arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap();
        let arn1b = Arn::from_str("arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap();
        let arn2 = Arn::from_str("arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef1").unwrap();
        let arn3 = Arn::from_str("arn:aws:ec2:us-east-1:123456789013:instance/i-1234567890abcdef0").unwrap();
        let arn4 = Arn::from_str("arn:aws:ec2:us-east-2:123456789012:instance/i-1234567890abcdef0").unwrap();
        let arn5 = Arn::from_str("arn:aws:ec3:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap();
        let arn6 = Arn::from_str("arn:awt:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap();

        assert_eq!(arn1a, arn1b);
        assert!(arn1a < arn2);
        assert!(arn2 < arn3);
        assert!(arn3 < arn4);
        assert!(arn4 < arn5);
        assert!(arn5 < arn6);

        assert_eq!(arn1a, arn1a.clone());

        // Ensure ordering is logical.
        assert!(arn1a <= arn1b);
        assert!(arn1a < arn2);
        assert!(arn2 > arn1a);
        assert!(arn2 < arn3);
        assert!(arn1a < arn3);
        assert!(arn3 > arn2);
        assert!(arn3 > arn1a);
        assert!(arn3 < arn4);
        assert!(arn4 > arn3);
        assert!(arn4 < arn5);
        assert!(arn5 > arn4);
        assert!(arn5 < arn6);
        assert!(arn6 > arn5);

        assert!(arn3.clone().min(arn4.clone()) == arn3);
        assert!(arn4.clone().max(arn3) == arn4);

        // Ensure we can derive a hash for the arn.
        let mut h1a = DefaultHasher::new();
        let mut h1b = DefaultHasher::new();
        arn1a.hash(&mut h1a);
        arn1b.hash(&mut h1b);
        assert_eq!(h1a.finish(), h1b.finish());

        let mut h2 = DefaultHasher::new();
        arn2.hash(&mut h2);

        // Ensure we can debug print the arn.
        _ = format!("{:?}", arn1a);

        assert_eq!(arn1a.to_string(), "arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0".to_string());
    }

    #[test]
    fn check_arn_components() {
        let arn = Arn::from_str("arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap();
        assert_eq!(arn.partition(), "aws");
        assert_eq!(arn.service(), "ec2");
        assert_eq!(arn.region(), "us-east-1");
        assert_eq!(arn.account_id(), "123456789012");
        assert_eq!(arn.resource(), "instance/i-1234567890abcdef0");
    }

    #[test]
    fn check_arn_empty() {
        let arn1 = Arn::from_str("arn:aws:s3:::bucket").unwrap();
        let arn2 = Arn::from_str("arn:aws:s3:us-east-1::bucket").unwrap();
        let arn3 = Arn::from_str("arn:aws:s3:us-east-1:123456789012:bucket").unwrap();

        assert!(arn1 < arn2);
        assert!(arn2 < arn3);
        assert!(arn1 < arn3);
    }

    #[test]
    fn check_unicode() {
        let arn = Arn::from_str("arn:aws-中国:één:日本-東京-1:123456789012:instance/i-1234567890abcdef0").unwrap();
        assert_eq!(arn.partition(), "aws-中国");
        assert_eq!(arn.service(), "één");
        assert_eq!(arn.region(), "日本-東京-1");

        let arn = Arn::from_str(
            "arn:việtnam:nœrøyfjorden:ap-southeast-7-hòa-hiệp-bắc-3:123456789012:instance/i-1234567890abcdef0",
        )
        .unwrap();
        assert_eq!(arn.partition(), "việtnam");
        assert_eq!(arn.service(), "nœrøyfjorden");
        assert_eq!(arn.region(), "ap-southeast-7-hòa-hiệp-bắc-3");
    }

    #[test]
    fn check_malformed_arns() {
        let wrong_parts =
            vec!["arn", "arn:aws", "arn:aws:ec2", "arn:aws:ec2:us-east-1", "arn:aws:ec2:us-east-1:123456789012"];
        for wrong_part in wrong_parts {
            assert_eq!(Arn::from_str(wrong_part).unwrap_err(), ArnError::InvalidArn(wrong_part.to_string()));
        }
    }

    #[test]
    fn check_invalid_scheme() {
        let err = Arn::from_str("http:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid scheme: "http""#.to_string());
    }

    #[test]
    fn check_invalid_partition() {
        let err = Arn::from_str("arn:Aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid partition: "Aws""#.to_string());

        let err = Arn::from_str("arn:local-:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid partition: "local-""#.to_string());

        let err = Arn::from_str("arn::ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid partition: """#.to_string());

        let err = Arn::from_str("arn:-local:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid partition: "-local""#.to_string());

        let err = Arn::from_str("arn:aws--1:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid partition: "aws--1""#.to_string());

        let err = Arn::from_str(
            "arn:this-partition-has-too-many-chars:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0",
        )
        .unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid partition: "this-partition-has-too-many-chars""#.to_string());

        let err = Arn::from_str("arn:🦀:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid partition: "🦀""#.to_string());
    }

    #[test]
    fn check_invalid_services() {
        let err = Arn::from_str("arn:aws:ec2-:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid service name: "ec2-""#.to_string());

        let err = Arn::from_str("arn:aws:-ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid service name: "-ec2""#.to_string());

        let err = Arn::from_str("arn:aws:Ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid service name: "Ec2""#.to_string());

        let err = Arn::from_str("arn:aws:ec--2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid service name: "ec--2""#.to_string());

        let err = Arn::from_str("arn:aws:🦀:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid service name: "🦀""#.to_string());

        let err = Arn::from_str("arn:aws::us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid service name: """#.to_string());
    }

    #[test]
    fn check_valid_regions() {
        let arn = Arn::from_str("arn:aws:ec2:local:123456789012:instance/i-1234567890abcdef0").unwrap();
        assert_eq!(arn.region(), "local");

        let arn = Arn::from_str("arn:aws:ec2:us-east-1-bos-1:123456789012:instance/i-1234567890abcdef0").unwrap();
        assert_eq!(arn.region(), "us-east-1-bos-1");
    }

    #[test]
    fn check_invalid_region() {
        let err = Arn::from_str("arn:aws:ec2:us-east-1-:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid region: "us-east-1-""#.to_string());

        let err = Arn::from_str("arn:aws:ec2:us-east-1a:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid region: "us-east-1a""#.to_string());

        let err = Arn::from_str("arn:aws:ec2:us-east1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid region: "us-east1""#.to_string());

        let err = Arn::from_str("arn:aws:ec2:-us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid region: "-us-east-1""#.to_string());

        let err = Arn::from_str("arn:aws:ec2:us-east:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid region: "us-east""#.to_string());

        let err = Arn::from_str("arn:aws:ec2:Us-East-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid region: "Us-East-1""#.to_string());

        let err = Arn::from_str("arn:aws:ec2:us-east--1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid region: "us-east--1""#.to_string());

        let err =
            Arn::from_str("arn:aws:ec2:us-east-1-bos-1-lax-1:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid region: "us-east-1-bos-1-lax-1""#.to_string());

        let err = Arn::from_str("arn:aws:ec2:us-east-🦀:123456789012:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid region: "us-east-🦀""#.to_string());

        let err = validate_region("").unwrap_err();
        assert_eq!(err, ArnError::InvalidRegion("".to_string()));
    }

    #[test]
    fn check_valid_account_ids() {
        let arn = Arn::from_str("arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0").unwrap();
        assert_eq!(arn.account_id(), "123456789012");

        let arn = Arn::from_str("arn:aws:ec2:us-east-1:aws:instance/i-1234567890abcdef0").unwrap();
        assert_eq!(arn.account_id(), "aws");
    }

    #[test]
    fn check_invalid_account_ids() {
        let err = Arn::from_str("arn:aws:ec2:us-east-1:1234567890123:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid account id: "1234567890123""#.to_string());

        let err = Arn::from_str("arn:aws:ec2:us-east-1:12345678901:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid account id: "12345678901""#.to_string());

        let err = Arn::from_str("arn:aws:ec2:us-east-1:12345678901a:instance/i-1234567890abcdef0").unwrap_err();
        assert_eq!(err.to_string(), r#"Invalid account id: "12345678901a""#.to_string());

        let err = validate_account_id("").unwrap_err();
        assert_eq!(err, ArnError::InvalidAccountId("".to_string()));
    }

    #[test]
    fn check_serialization() {
        let arn: Arn =
            serde_json::from_str(r#""arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0""#).unwrap();
        assert_eq!(arn.partition(), "aws");
        assert_eq!(arn.service(), "ec2");
        assert_eq!(arn.region(), "us-east-1");
        assert_eq!(arn.account_id(), "123456789012");
        assert_eq!(arn.resource(), "instance/i-1234567890abcdef0");

        let arn_str = serde_json::to_string(&arn).unwrap();
        assert_eq!(arn_str, r#""arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0""#);

        let arn_err = serde_json::from_str::<Arn>(r#""arn:aws:ec2:us-east-1""#).unwrap_err();
        assert_eq!(arn_err.to_string(), r#"Invalid ARN: "arn:aws:ec2:us-east-1""#);

        let arn_err = serde_json::from_str::<Arn>(r#"{}"#);
        assert_eq!(arn_err.unwrap_err().to_string(), "invalid type: map, expected a string at line 1 column 0");
    }
}