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
use {
    crate::{eval::regex_from_glob, serutil::StringLikeList, AspenError},
    log::debug,
    std::{
        fmt::{Display, Formatter, Result as FmtResult},
        str::FromStr,
    },
};

/// A list of actions. In JSON, this may be a string or an array of strings.
pub type ActionList = StringLikeList<Action>;

/// An action in an Aspen policy.
///
/// This can either be `Any` action (represented by the string `*`), or a service and an API pattern (`Specific`)
/// in the form `service:api_pattern`. The API pattern may contain wildcard characters (`*` and `?`).
#[derive(Clone, Debug)]
pub enum Action {
    /// Any action.
    Any,

    /// A specific action.
    Specific(SpecificActionDetails),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SpecificActionDetails {
    /// The service the action is for. This may not contain wildcards.
    service: String,

    /// The api pattern. This may contain wildcards.
    api: String,
}

impl PartialEq for Action {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Any, Self::Any) => true,
            (Self::Specific(my_details), Self::Specific(other_details)) => my_details == other_details,
            _ => false,
        }
    }
}

impl Eq for Action {}

impl Action {
    /// Create a new [Action::Specific] action.
    ///
    /// # Errors
    ///
    /// An [AspenError::InvalidAction] error is returned in any of the following cases:
    /// * `service` or `api` is empty.
    /// * `service` contains non-ASCII alphanumeric characters, hyphen (`-`), or underscore (`_`).
    /// * `service` begins or ends with a hyphen or underscore.
    /// * `api` contains non-ASCII alphanumeric characters, hyphen (`-`), underscore (`_`), asterisk (`*`), or
    ///    question mark (`?`).
    /// * `api` begins or ends with a hyphen or underscore.
    pub fn new<S: Into<String>, A: Into<String>>(service: S, api: A) -> Result<Self, AspenError> {
        let service = service.into();
        let api = api.into();

        if service.is_empty() {
            debug!("Action '{service}:{api}' has an empty service.");
            return Err(AspenError::InvalidAction(format!("{service}:{api}")));
        }

        if api.is_empty() {
            debug!("Action '{service}:{api}' has an empty API.");
            return Err(AspenError::InvalidAction(format!("{service}:{api}")));
        }

        if !service.is_ascii() || !api.is_ascii() {
            debug!("Action '{service}:{api}' is not ASCII.");
            return Err(AspenError::InvalidAction(format!("{service}:{api}")));
        }

        for (i, c) in service.bytes().enumerate() {
            if !c.is_ascii_alphanumeric() && !(i > 0 && i < service.len() - 1 && (c == b'-' || c == b'_')) {
                debug!("Action '{service}:{api}' has an invalid service.");
                return Err(AspenError::InvalidAction(format!("{service}:{api}")));
            }
        }

        for (i, c) in api.bytes().enumerate() {
            if !c.is_ascii_alphanumeric()
                && c != b'*'
                && c != b'?'
                && !(i > 0 && i < api.len() - 1 && (c == b'-' || c == b'_'))
            {
                debug!("Action '{service}:{api}' has an invalid API.");
                return Err(AspenError::InvalidAction(format!("{service}:{api}")));
            }
        }

        Ok(Action::Specific(SpecificActionDetails {
            service,
            api,
        }))
    }

    /// Returns true if this action is [Action::Any].
    #[inline]
    pub fn is_any(&self) -> bool {
        matches!(self, Self::Any)
    }

    /// If the action is [Action::Specific], returns the service and action.
    #[inline]
    pub fn specific(&self) -> Option<(&str, &str)> {
        match self {
            Self::Any => None,
            Self::Specific(details) => Some((&details.service, &details.api)),
        }
    }

    /// Returns the service for this action or "*" if this action is [Action::Any].
    #[inline]
    pub fn service(&self) -> &str {
        match self {
            Self::Any => "*",
            Self::Specific(SpecificActionDetails {
                service,
                ..
            }) => service,
        }
    }

    /// Returns the API for this action or "*" if this action is [Action::Any].
    #[inline]
    pub fn api(&self) -> &str {
        match self {
            Self::Any => "*",
            Self::Specific(SpecificActionDetails {
                api,
                ..
            }) => api,
        }
    }

    /// Indicates whether this action matches the given service and action.
    pub fn matches(&self, service: &str, api: &str) -> bool {
        match self {
            Self::Any => true,
            Self::Specific(SpecificActionDetails {
                service: self_service,
                api: self_api,
            }) => {
                if self_service == service {
                    regex_from_glob(self_api, false).is_match(api)
                } else {
                    false
                }
            }
        }
    }
}

impl FromStr for Action {
    type Err = AspenError;
    fn from_str(v: &str) -> Result<Self, Self::Err> {
        if v == "*" {
            return Ok(Self::Any);
        }

        let parts: Vec<&str> = v.split(':').collect();
        if parts.len() != 2 {
            return Err(AspenError::InvalidAction(v.to_string()));
        }

        let service = parts[0];
        let api = parts[1];

        Action::new(service, api)
    }
}

impl Display for Action {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        match self {
            Self::Any => f.write_str("*"),
            Self::Specific(details) => Display::fmt(details, f),
        }
    }
}

impl Display for SpecificActionDetails {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "{}:{}", self.service, self.api)
    }
}

#[cfg(test)]
mod tests {
    use {
        crate::{Action, ActionList},
        indoc::indoc,
        pretty_assertions::{assert_eq, assert_ne},
        std::{panic::catch_unwind, str::FromStr},
    };

    #[test_log::test]
    fn test_eq() {
        let a1a: ActionList = Action::new("s1", "a1").unwrap().into();
        let a1b: ActionList = vec![Action::new("s1", "a1").unwrap()].into();
        let a2a: ActionList = Action::new("s2", "a1").unwrap().into();
        let a2b: ActionList = vec![Action::new("s2", "a1").unwrap()].into();
        let a3a: ActionList = Action::new("s1", "a2").unwrap().into();
        let a3b: ActionList = vec![Action::new("s1", "a2").unwrap()].into();
        let a4a: ActionList = vec![].into();
        let a4b: ActionList = vec![].into();

        assert_eq!(a1a, a1a.clone());
        assert_eq!(a1b, a1b.clone());
        assert_eq!(a2a, a2a.clone());
        assert_eq!(a2b, a2b.clone());
        assert_eq!(a3a, a3a.clone());
        assert_eq!(a3b, a3b.clone());
        assert_eq!(a4a, a4a.clone());
        assert_eq!(a4b, a4b.clone());

        assert_eq!(a1a.len(), 1);
        assert_eq!(a1b.len(), 1);
        assert_eq!(a2a.len(), 1);
        assert_eq!(a2b.len(), 1);
        assert_eq!(a3a.len(), 1);
        assert_eq!(a3b.len(), 1);
        assert_eq!(a4a.len(), 0);
        assert_eq!(a4b.len(), 0);

        assert!(!a1a.is_empty());
        assert!(!a1b.is_empty());
        assert!(!a2a.is_empty());
        assert!(!a2b.is_empty());
        assert!(!a3a.is_empty());
        assert!(!a3b.is_empty());
        assert!(a4a.is_empty());
        assert!(a4b.is_empty());

        assert_eq!(a1a, a1b);
        assert_eq!(a1b, a1a);
        assert_eq!(a2a, a2b);
        assert_eq!(a2b, a2a);
        assert_eq!(a3a, a3b);
        assert_eq!(a3b, a3a);
        assert_eq!(a4a, a4b);
        assert_eq!(a4b, a4a);

        assert_ne!(a1a, a2a);
        assert_ne!(a1a, a2b);
        assert_ne!(a1a, a3a);
        assert_ne!(a1a, a3b);
        assert_ne!(a1a, a4a);
        assert_ne!(a1a, a4b);
        assert_ne!(a2a, a1a);
        assert_ne!(a2b, a1a);
        assert_ne!(a3a, a1a);
        assert_ne!(a3b, a1a);
        assert_ne!(a4a, a1a);
        assert_ne!(a4b, a1a);

        assert_ne!(a1b, a2a);
        assert_ne!(a1b, a2b);
        assert_ne!(a1b, a3a);
        assert_ne!(a1b, a3b);
        assert_ne!(a1b, a4a);
        assert_ne!(a1b, a4b);
        assert_ne!(a2a, a1b);
        assert_ne!(a2b, a1b);
        assert_ne!(a3a, a1b);
        assert_ne!(a3b, a1b);
        assert_ne!(a4a, a1b);
        assert_ne!(a4b, a1b);

        assert_ne!(a2a, a3a);
        assert_ne!(a2a, a3b);
        assert_ne!(a2a, a4a);
        assert_ne!(a2a, a4b);
        assert_ne!(a3a, a2a);
        assert_ne!(a3b, a2a);
        assert_ne!(a4a, a2a);
        assert_ne!(a4b, a2a);

        assert_ne!(a2b, a3a);
        assert_ne!(a2b, a3b);
        assert_ne!(a2b, a4a);
        assert_ne!(a2b, a4b);
        assert_ne!(a3a, a2b);
        assert_ne!(a3b, a2b);
        assert_ne!(a4a, a2b);
        assert_ne!(a4b, a2b);

        assert_ne!(a3a, a4a);
        assert_ne!(a3a, a4b);
        assert_ne!(a4a, a3a);
        assert_ne!(a4b, a3a);

        assert_ne!(a3b, a4a);
        assert_ne!(a3b, a4b);
        assert_ne!(a4a, a3b);
        assert_ne!(a4b, a3b);

        assert_eq!(Action::Any, Action::Any);
    }

    #[test_log::test]
    fn test_from() {
        let a1a: ActionList = vec![Action::new("s1", "a1").unwrap()].into();
        let a1b: ActionList = Action::new("s1", "a1").unwrap().into();
        let a2a: ActionList = vec![Action::Any].into();

        assert_eq!(a1a, a1b);
        assert_eq!(a1b, a1a);
        assert_ne!(a1a, a2a);

        assert_eq!(a1a[0], a1b[0]);

        assert_eq!(
            format!("{a1a}"),
            indoc! {r#"
            [
                "s1:a1"
            ]"#}
        );
        assert_eq!(format!("{a1b}"), r#""s1:a1""#);
        assert_eq!(
            format!("{a2a}"),
            indoc! {r#"
            [
                "*"
            ]"#}
        );

        assert_eq!(format!("{}", a2a[0]), "*");

        let e = catch_unwind(|| {
            println!("This will not be printed: {}", a1b[1]);
        })
        .unwrap_err();
        assert_eq!(*e.downcast::<String>().unwrap(), "index out of bounds: the len is 1 but the index is 1");
    }

    #[test_log::test]
    fn test_bad_strings() {
        assert_eq!(Action::from_str("").unwrap_err().to_string(), "Invalid action: ");
        assert_eq!(Action::from_str("ec2:").unwrap_err().to_string(), "Invalid action: ec2:");
        assert_eq!(
            Action::from_str(":DescribeInstances").unwrap_err().to_string(),
            "Invalid action: :DescribeInstances"
        );
        assert_eq!(
            Action::from_str("🦀:DescribeInstances").unwrap_err().to_string(),
            "Invalid action: 🦀:DescribeInstances"
        );
        assert_eq!(Action::from_str("ec2:🦀").unwrap_err().to_string(), "Invalid action: ec2:🦀");
        assert_eq!(
            Action::from_str("-ec2:DescribeInstances").unwrap_err().to_string(),
            "Invalid action: -ec2:DescribeInstances"
        );
        assert_eq!(
            Action::from_str("_ec2:DescribeInstances").unwrap_err().to_string(),
            "Invalid action: _ec2:DescribeInstances"
        );
        assert_eq!(
            Action::from_str("ec2-:DescribeInstances").unwrap_err().to_string(),
            "Invalid action: ec2-:DescribeInstances"
        );
        assert_eq!(
            Action::from_str("ec2_:DescribeInstances").unwrap_err().to_string(),
            "Invalid action: ec2_:DescribeInstances"
        );
        assert_eq!(
            Action::from_str("ec2:-DescribeInstances").unwrap_err().to_string(),
            "Invalid action: ec2:-DescribeInstances"
        );
        assert_eq!(
            Action::from_str("ec2:_DescribeInstances").unwrap_err().to_string(),
            "Invalid action: ec2:_DescribeInstances"
        );
        assert_eq!(
            Action::from_str("ec2:DescribeInstances-").unwrap_err().to_string(),
            "Invalid action: ec2:DescribeInstances-"
        );
        assert_eq!(
            Action::from_str("ec2:DescribeInstances_").unwrap_err().to_string(),
            "Invalid action: ec2:DescribeInstances_"
        );

        assert_eq!(Action::from_str("e_c-2:De-scribe_Instances").unwrap().service(), "e_c-2");
        assert_eq!(Action::from_str("e_c-2:De-scribe_Instances").unwrap().api(), "De-scribe_Instances");
        assert!(Action::from_str("e_c-2:De-scribe_Instances").unwrap().specific().is_some());
        assert!(!Action::from_str("e_c-2:De-scribe_Instances").unwrap().is_any());
        assert_eq!(Action::from_str("*").unwrap().service(), "*");
        assert_eq!(Action::from_str("*").unwrap().api(), "*");
        assert!(Action::from_str("*").unwrap().is_any());
        assert!(Action::from_str("*").unwrap().specific().is_none());
    }
}