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
use {
    crate::{utils::validate_dns, PrincipalError},
    scratchstack_arn::utils::validate_region,
    std::fmt::{Display, Formatter, Result as FmtResult},
};

/// Details about an AWS or AWS-like service.
///
/// Service structs are immutable.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Service {
    /// Name of the service.
    service_name: String,

    /// The region the service is running in. If None, the service is global.
    region: Option<String>,

    /// The DNS suffix of the service. This is usually amazonaws.com.
    dns_suffix: String,
}

impl Service {
    /// Create a [Service] object representing an AWS(-ish) service.
    ///
    /// # Arguments
    ///
    /// * `service_name`: The name of the service. This must meet the following requirements or a
    ///     [PrincipalError::InvalidService] error will be returned:
    ///     *   The name must contain between 1 and 32 characters.
    ///     *   The name must be composed to ASCII alphanumeric characters or one of `, - . = @ _`.
    /// * `region`: The region the service is running in. If `None`, the service is global.
    /// * `dns_suffix`: The DNS suffix of the service. This is usually amazonaws.com.
    ///
    /// If all of the requirements are met, a [Service] object is returned.  Otherwise, a [PrincipalError] error is
    /// returned.
    ///
    /// # Example
    /// ```
    /// # use scratchstack_aws_principal::Service;
    /// let service = Service::new("s3", Some("us-east-1".to_string()), "amazonaws.com").unwrap();
    /// assert_eq!(service.service_name(), "s3");
    /// assert_eq!(service.region(), Some("us-east-1"));
    /// assert_eq!(service.dns_suffix(), "amazonaws.com");
    /// assert_eq!(service.regional_dns_name(), "s3.us-east-1.amazonaws.com");
    /// assert_eq!(service.global_dns_name(), "s3.amazonaws.com");
    /// ```
    pub fn new(service_name: &str, region: Option<String>, dns_suffix: &str) -> Result<Self, PrincipalError> {
        validate_dns(service_name, 32, PrincipalError::InvalidService)?;
        validate_dns(dns_suffix, 128, PrincipalError::InvalidService)?;

        let region = match region {
            None => None,
            Some(region) => {
                validate_region(region.as_str())?;
                Some(region)
            }
        };

        Ok(Self {
            service_name: service_name.to_string(),
            region,
            dns_suffix: dns_suffix.into(),
        })
    }

    /// The name of the service.
    #[inline]
    pub fn service_name(&self) -> &str {
        &self.service_name
    }

    /// The region of the service. If the service is global, this will be `None`.
    #[inline]
    pub fn region(&self) -> Option<&str> {
        self.region.as_deref()
    }

    /// The DNS suffix of the service.
    #[inline]
    pub fn dns_suffix(&self) -> &str {
        &self.dns_suffix
    }

    /// The regional DNS name of the service. If the service is global, this will be the same as the global DNS name.
    pub fn regional_dns_name(&self) -> String {
        match &self.region {
            None => format!("{}.{}", self.service_name, self.dns_suffix),
            Some(region) => format!("{}.{}.{}", self.service_name, region, self.dns_suffix),
        }
    }

    /// The global DNS name of the service (omitting the regional component, if any).
    pub fn global_dns_name(&self) -> String {
        format!("{}.{}", self.service_name, self.dns_suffix)
    }
}

impl Display for Service {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match &self.region {
            None => write!(f, "{}.{}", self.service_name, self.dns_suffix),
            Some(region) => write!(f, "{}.{}.{}", self.service_name, region, self.dns_suffix),
        }
    }
}

#[cfg(test)]
mod tests {
    use {
        super::Service,
        crate::{PrincipalIdentity, PrincipalSource},
        std::{
            collections::hash_map::DefaultHasher,
            hash::{Hash, Hasher},
        },
    };

    #[test]
    fn check_components() {
        let s1 = Service::new("s3", None, "amazonaws.com").unwrap();
        let s2 = Service::new("s3", Some("us-east-1".into()), "amazonaws.com").unwrap();

        assert_eq!(s1.service_name(), "s3");
        assert_eq!(s1.region(), None);
        assert_eq!(s1.dns_suffix(), "amazonaws.com");

        assert_eq!(s2.service_name(), "s3");
        assert_eq!(s2.region(), Some("us-east-1"));
        assert_eq!(s2.dns_suffix(), "amazonaws.com");

        let p = PrincipalIdentity::from(s1);
        let source = p.source();
        assert_eq!(source, PrincipalSource::Service);
        assert_eq!(source.to_string(), "Service".to_string());
    }

    #[test]
    fn check_derived() {
        let s1a = Service::new("s3", None, "amazonaws.com").unwrap();
        let s1b = Service::new("s3", None, "amazonaws.com").unwrap();
        let s2 = Service::new("s3", None, "amazonaws.net").unwrap();
        let s3 = Service::new("s3", Some("us-east-1".into()), "amazonaws.net").unwrap();
        let s4 = Service::new("s3", Some("us-east-2".into()), "amazonaws.net").unwrap();
        let s5 = Service::new("s4", None, "amazonaws.net").unwrap();
        let s6 = Service::new("s4", Some("us-east-1".into()), "amazonaws.net").unwrap();

        assert_eq!(s1a, s1b);
        assert_ne!(s1a, s2);
        assert_eq!(s1a, s1a);
        assert_ne!(s1a, s3);
        assert_ne!(s2, s3);
        assert_ne!(s3, s4);
        assert_ne!(s4, s5);
        assert_ne!(s5, s6);

        // Ensure we can hash a service.
        let mut h1a = DefaultHasher::new();
        let mut h1b = DefaultHasher::new();
        let mut h2 = DefaultHasher::new();
        s1a.hash(&mut h1a);
        s1b.hash(&mut h1b);
        s2.hash(&mut h2);
        let hash1a = h1a.finish();
        let hash1b = h1b.finish();
        let hash2 = h2.finish();
        assert_eq!(hash1a, hash1b);
        assert_ne!(hash1a, hash2);

        // Ensure ordering is logical.
        assert!(s1a <= s1b);
        assert!(s1a < s2);
        assert!(s2 > s1a);
        assert!(s1a < s3);
        assert!(s2 < s3);
        assert!(s1a < s4);
        assert!(s2 < s4);
        assert!(s3 < s4);
        assert!(s1a < s5);
        assert!(s2 < s5);
        assert!(s3 < s5);
        assert!(s4 < s5);
        assert!(s1a < s6);
        assert!(s2 < s6);
        assert!(s3 < s6);
        assert!(s4 < s6);
        assert!(s5 < s6);
        assert_eq!(s1a.clone().max(s2.clone()), s2);
        assert_eq!(s1a.clone().min(s3), s1a);

        // Ensure formatting is correct to the DNS name.
        assert_eq!(s1a.to_string(), "s3.amazonaws.com");
        assert_eq!(s6.to_string(), "s4.us-east-1.amazonaws.net");

        // Ensure we can debug print a service.
        let _ = format!("{s1a:?}");
    }

    #[test]
    fn check_valid_services() {
        let s1a = Service::new("service-name", None, "amazonaws.com").unwrap();
        let s1b = Service::new("service-name", None, "amazonaws.com").unwrap();
        let s2 = Service::new("service-name2", None, "amazonaws.com").unwrap();
        let s3 = Service::new("service-name", Some("us-east-1".to_string()), "amazonaws.com").unwrap();
        let s4 = Service::new("aservice-name-with-32-characters", None, "amazonaws.com").unwrap();

        assert_eq!(s1a, s1b);
        assert_ne!(s1a, s2);
        assert_eq!(s1a, s1a.clone());

        assert_eq!(s1a.to_string(), "service-name.amazonaws.com");
        assert_eq!(s2.to_string(), "service-name2.amazonaws.com");
        assert_eq!(s3.to_string(), "service-name.us-east-1.amazonaws.com");
        assert_eq!(s4.to_string(), "aservice-name-with-32-characters.amazonaws.com");

        assert_eq!(s1a.regional_dns_name(), "service-name.amazonaws.com");
        assert_eq!(s1a.global_dns_name(), "service-name.amazonaws.com");

        assert_eq!(s3.regional_dns_name(), "service-name.us-east-1.amazonaws.com");
        assert_eq!(s3.global_dns_name(), "service-name.amazonaws.com");
    }

    #[test]
    fn check_invalid_services() {
        assert_eq!(
            Service::new("service name", None, "amazonaws.com",).unwrap_err().to_string(),
            r#"Invalid service name: "service name""#
        );

        assert_eq!(
            Service::new("service name", Some("us-east-1".to_string()), "amazonaws.com",).unwrap_err().to_string(),
            r#"Invalid service name: "service name""#
        );

        assert_eq!(
            Service::new("service!name", None, "amazonaws.com",).unwrap_err().to_string(),
            r#"Invalid service name: "service!name""#
        );

        assert_eq!(
            Service::new("service!name", Some("us-east-1".to_string()), "amazonaws.com",).unwrap_err().to_string(),
            r#"Invalid service name: "service!name""#
        );

        assert_eq!(Service::new("", None, "amazonaws.com",).unwrap_err().to_string(), r#"Invalid service name: """#);

        assert_eq!(
            Service::new("a-service-name-with-33-characters", None, "amazonaws.com",).unwrap_err().to_string(),
            r#"Invalid service name: "a-service-name-with-33-characters""#
        );

        assert_eq!(
            Service::new("service-name", Some("us-east-".to_string()), "amazonaws.com",).unwrap_err().to_string(),
            r#"Invalid region: "us-east-""#
        );

        assert_eq!(
            Service::new("service-name", Some("us-east-1".to_string()), "amazonaws..com",).unwrap_err().to_string(),
            r#"Invalid service name: "amazonaws..com""#
        );
    }
}
// end tests -- do not delete; needed for coverage.