aws-iam 0.2.2

A Rust crate for dealing with AWS IAM Policy resources
Documentation
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
use crate::document::visitor::*;
use crate::model::*;
use std::io::{stdout, Write};

// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------

///
/// This types implements `PolicyVisitor`, `StatementVisitor`, and `ConditionVisitor` to
/// produce [LaTeX](https://www.latex-project.org/) formatted documentation for a Policy.
///
#[allow(missing_debug_implementations)]
pub struct LatexGenerator {
    writer: Box<dyn Write>,
    stand_alone: bool,
    has_conditions: bool,
}

// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------

const IO_ERROR_MSG: &str = "Unexpected write error";

impl LatexGenerator {
    ///
    /// Create a new generator that will write formatted content to `writer`. If you wish
    /// to write to `stdout` use `Default::default()`. If `stand_alone` is true a document
    /// class, header and operator appendix are included, otherwise a single section is output.
    ///
    pub fn new<T>(writer: T, stand_alone: bool) -> Self
    where
        T: Write + Sized + 'static,
    {
        LatexGenerator {
            writer: Box::new(writer),
            stand_alone,
            has_conditions: false,
        }
    }

    fn newln(&mut self) {
        writeln!(self.writer.as_mut()).expect(IO_ERROR_MSG);
    }
}

impl Default for LatexGenerator {
    fn default() -> Self {
        LatexGenerator {
            writer: Box::new(stdout()),
            stand_alone: true,
            has_conditions: false,
        }
    }
}

impl PolicyVisitor for LatexGenerator {
    fn start(&mut self) {
        if self.stand_alone {
            writeln!(
                self.writer.as_mut(),
                r#"\documentclass[10pt,letterpaper]{{article}}

\usepackage[T1]{{fontenc}}
\usepackage{{libertine}}
\usepackage{{amsfonts}}

\usepackage{{sectsty}}
\sectionfont{{\LARGE\normalfont\sffamily}}
\subsectionfont{{\Large\normalfont\sffamily}}
\subsubsectionfont{{\large\normalfont\sffamily}}

\begin{{document}}
"#
            )
            .expect(IO_ERROR_MSG);
        }
        writeln!(self.writer.as_mut(), "\\section{{Policy}}").expect(IO_ERROR_MSG);
    }

    fn id(&mut self, i: &str) {
        self.newln();
        writeln!(
            self.writer.as_mut(),
            "The policy identifier is \\texttt{{\\small{{{}}}}}. ",
            i
        )
        .expect(IO_ERROR_MSG);
    }

    fn version(&mut self, v: &Version) {
        self.newln();
        writeln!(
            self.writer.as_mut(),
            "The \\textsc{{iam}} policy language version is {}.",
            match v {
                Version::V2008 => "2008-10-17",
                Version::V2012 => "2012-10-17",
            }
        )
        .expect(IO_ERROR_MSG);
    }

    fn statement_visitor(&mut self) -> Option<Box<&mut dyn StatementVisitor>> {
        Some(Box::new(self))
    }

    fn finish(&mut self) {
        self.newln();
        if self.stand_alone {
            writeln!(
                self.writer.as_mut(),
                r#"\appendix
\section{{Operators}}

\begin{{tabular}}{{|c|l|p{{3.25in}}|}}
  \hline
  \textbf{{Symbol}} & \textbf{{Operation}} & \textbf{{Applies To}} \\
  \hline
  $=$ & equality & strings, numbers, dates, \textsc{{ip}} addresses, \textsc{{arn}}\small{{s}}, principal identifiers, actions, resources \\
  \hline
  $\neq$ & not equality & strings, numbers, dates, \textsc{{ip}} addresses, \textsc{{arn}}\small{{s}}, principal identifiers, actions, resources \\
  \hline
  $\equiv$ & case insensitive equality & strings \\
  \hline
  $\not\equiv$ & case insensitive not equality & strings \\
  \hline
  $\approx$ & \textit{{likeness}} & strings, \textsc{{arn}}\small{{s}}, principal identifiers, actions, resources \\
  \hline
  $\not\approx$ & not \textit{{likeness}} & strings, \textsc{{arn}}\small{{s}}, principal identifiers, actions, resources \\
  \hline
  $<$ & less than & numbers, dates \\
  \hline
  $\leq$ & less than or equal to & numbers, dates \\
  \hline
  $>$ & greater than & numbers, dates \\
  \hline
  $\geq$ & greater than or equal to & numbers, dates \\
  \hline
  $?$ & is null & strings, numbers, dates, \textsc{{ip}} addresses, \textsc{{arn}}\small{{s}} \\
  \hline
  $\in$ & set inclusion & strings, numbers, principal identifiers, actions, resources \\
  \hline
  $\notin$ & not set inclusion & strings, numbers, principal identifiers, actions, resources \\
  \hline
\end{{tabular}}

\hfill

\noindent Also not our use of the symbol $\mathbb{{U}}$, defined as \textit{{the set of all elements being considered}},
in the expression $\in \mathbb{{U}}$ representing the universal wildcard ``*''.

\end{{document}}
"#
            )
            .expect(IO_ERROR_MSG);
        }
    }
}

impl StatementVisitor for LatexGenerator {
    fn start(&mut self) {
        self.newln();
        writeln!(self.writer.as_mut(), "\\subsection{{Statement}}").expect(IO_ERROR_MSG);
        self.newln();
    }

    fn sid(&mut self, s: &str) {
        write!(
            self.writer.as_mut(),
            "The statement \\textit{{identifier}} is \\texttt{{\\small{{{}}}}}. ",
            s
        )
        .expect(IO_ERROR_MSG);
    }

    fn effect(&mut self, e: &Effect) {
        writeln!(
            self.writer.as_mut(),
            "The effect of this statement is to \\textbf{{{}}} the requesting principal to perform the requested action if all of the following conditions are met:",
            match e {
                Effect::Allow => "allow",
                Effect::Deny => "deny",
            }
        )
        .expect(IO_ERROR_MSG);
        self.newln();
        writeln!(self.writer.as_mut(), "\\begin{{itemize}}").expect(IO_ERROR_MSG);
    }

    fn principal(&mut self, p: &Principal) {
        let (negated, values) = match p {
            Principal::Principal(v) => (false, v),
            Principal::NotPrincipal(v) => (true, v),
        };
        writeln!(
            self.writer.as_mut(),
            "    \\item The request \\textit{{principal}} matches any of: "
        )
        .expect(IO_ERROR_MSG);
        writeln!(self.writer.as_mut(), "    \\begin{{itemize}}").expect(IO_ERROR_MSG);
        for (kind, value) in values {
            writeln!(
                self.writer.as_mut(),
                "        \\item \\textit{{type}} $=$ {:?} $\\wedge$ \\textit{{id}} {}.",
                kind,
                match value {
                    OneOrAny::Any => any(negated),
                    OneOrAny::One(v) => string_or_any(v, negated),
                    OneOrAny::AnyOf(vs) => format!(
                        "{} \\{{{}\\}}",
                        if negated { "$\\notin$" } else { "$\\in$" },
                        vs.iter()
                            .map(|s| string_value(s))
                            .collect::<Vec<String>>()
                            .join(", ")
                    ),
                }
            )
            .expect(IO_ERROR_MSG);
        }
        writeln!(self.writer.as_mut(), "    \\end{{itemize}}").expect(IO_ERROR_MSG);
    }

    fn action(&mut self, a: &Action) {
        let (negated, value) = match a {
            Action::Action(v) => (false, v),
            Action::NotAction(v) => (true, v),
        };
        writeln!(
            self.writer.as_mut(),
            "    \\item The request's \\textit{{action}} {}.",
            match value {
                OneOrAny::Any => any(negated),
                OneOrAny::One(v) => string_or_any(&v.to_string(), negated),
                OneOrAny::AnyOf(vs) => format!(
                    "{} \\{{{}\\}}",
                    if negated { "$\\notin$" } else { "$\\in$" },
                    vs.iter()
                        .map(|s| string_value(&s.to_string()))
                        .collect::<Vec<String>>()
                        .join(", ")
                ),
            }
        )
        .expect(IO_ERROR_MSG);
    }

    fn resource(&mut self, r: &Resource) {
        let (negated, value) = match r {
            Resource::Resource(v) => (false, v),
            Resource::NotResource(v) => (true, v),
        };
        writeln!(
            self.writer.as_mut(),
            "    \\item The request's \\textit{{resource}} {}.",
            match value {
                OneOrAny::Any => any(negated),
                OneOrAny::One(v) => string_or_any(v, negated),
                OneOrAny::AnyOf(vs) => format!(
                    "{} \\{{{}\\}}",
                    if negated { "$\\notin$" } else { "$\\in$" },
                    vs.iter()
                        .map(|s| string_value(s))
                        .collect::<Vec<String>>()
                        .join(", ")
                ),
            }
        )
        .expect(IO_ERROR_MSG);
    }

    fn condition_visitor(&mut self) -> Option<Box<&mut dyn ConditionVisitor>> {
        self.has_conditions = true;
        writeln!(
            self.writer.as_mut(),
            "    \\item The request matches all of the following conditions:"
        )
        .expect(IO_ERROR_MSG);
        writeln!(self.writer.as_mut(), "    \\begin{{itemize}}").expect(IO_ERROR_MSG);
        Some(Box::new(self))
    }

    fn finish(&mut self) {
        if self.has_conditions {
            self.has_conditions = false;
            writeln!(self.writer.as_mut(), "    \\end{{itemize}}").expect(IO_ERROR_MSG);
        }
        writeln!(self.writer.as_mut(), "\\end{{itemize}}").expect(IO_ERROR_MSG);
    }
}

impl ConditionVisitor for LatexGenerator {
    fn left(&mut self, f: &QString, op: &ConditionOperator) {
        write!(
            self.writer.as_mut(),
            "        \\item {}{}{}",
            if op.if_exists {
                format!(
                    "\\textbf{{if exists}} \\textit{{{}}} \\textbf{{then}} \\\\ ",
                    f
                )
            } else {
                "".to_string()
            },
            match op.quantifier {
                None => "",
                Some(ConditionOperatorQuantifier::ForAllValues) => "$\\forall(v)$",
                Some(ConditionOperatorQuantifier::ForAnyValue) => "$\\exists(v)$",
            },
            format!("\\textit{{{}}}", f)
        )
        .expect(IO_ERROR_MSG);
    }

    fn operator(&mut self, op: &ConditionOperator) {
        write!(self.writer.as_mut(), " {} ", operator_string(op),).expect(IO_ERROR_MSG);
    }

    fn right(&mut self, v: &OneOrAll<ConditionValue>, _op: &ConditionOperator) {
        writeln!(
            self.writer.as_mut(),
            "{}",
            match v {
                OneOrAll::One(v) => {
                    condition_value(v)
                }
                OneOrAll::All(vs) => format!(
                    "\\{{{}\\}}",
                    vs.iter()
                        .map(condition_value)
                        .collect::<Vec<String>>()
                        .join(", ")
                ),
            }
        )
        .expect(IO_ERROR_MSG);
    }
}

// ------------------------------------------------------------------------------------------------
// Private Functions
// ------------------------------------------------------------------------------------------------

fn string_value(v: &str) -> String {
    format!("``{}''", v)
        .replace('$', r"\$")
        .replace('{', r"\{")
        .replace('}', r"\}")
}

fn condition_value(v: &ConditionValue) -> String {
    match v {
        ConditionValue::String(v) => string_value(v),
        ConditionValue::Integer(v) => v.to_string(),
        ConditionValue::Float(v) => v.to_string(),
        ConditionValue::Bool(v) => v.to_string(),
    }
}

fn any(negated: bool) -> String {
    format!(
        "${} \\mathbb{{U}}$",
        if negated { "\\notin" } else { "\\in " }
    )
}

fn string_or_any(v: &str, negated: bool) -> String {
    if v == "*" {
        any(negated)
    } else if v.contains('*') {
        format!(
            "{} {}",
            if negated {
                "$\\not\\approx$"
            } else {
                "$\\approx$"
            },
            string_value(v)
        )
    } else {
        format!(
            "{} {}",
            if negated { "$\\neq$" } else { "$=$" },
            string_value(v)
        )
    }
}

#[inline]
fn op_str(op: &str) -> String {
    format!("${}$", op)
}

fn operator_string(op: &ConditionOperator) -> String {
    match &op.operator {
        GlobalConditionOperator::StringEquals => op_str("="),
        GlobalConditionOperator::StringNotEquals => op_str("\\neq"),
        GlobalConditionOperator::StringEqualsIgnoreCase => op_str("\\equiv"),
        GlobalConditionOperator::StringNotEqualsIgnoreCase => op_str("\\not\\equiv"),
        GlobalConditionOperator::StringLike => op_str("\\approx"),
        GlobalConditionOperator::StringNotLike => op_str("\\not\\approx"),

        GlobalConditionOperator::NumericEquals => op_str("="),
        GlobalConditionOperator::NumericNotEquals => op_str("\\neq"),
        GlobalConditionOperator::NumericLessThan => op_str("<"),
        GlobalConditionOperator::NumericLessThanEquals => op_str("\\leq"),
        GlobalConditionOperator::NumericGreaterThan => op_str(">"),
        GlobalConditionOperator::NumericGreaterThanEquals => op_str("\\geq"),

        GlobalConditionOperator::DateEquals => op_str("="),
        GlobalConditionOperator::DateNotEquals => op_str("\\neq"),
        GlobalConditionOperator::DateLessThan => op_str("<"),
        GlobalConditionOperator::DateLessThanEquals => op_str("\\leq"),
        GlobalConditionOperator::DateGreaterThan => op_str(">"),
        GlobalConditionOperator::DateGreaterThanEquals => op_str("\\geq"),

        GlobalConditionOperator::Bool => op_str("="),

        GlobalConditionOperator::BinaryEquals => op_str("="),

        GlobalConditionOperator::IpAddress => op_str("="),
        GlobalConditionOperator::NotIpAddress => op_str("\\neq"),

        GlobalConditionOperator::ArnEquals => op_str("="),
        GlobalConditionOperator::ArnLike => op_str("\\approx"),
        GlobalConditionOperator::ArnNotEquals => op_str("\\neq"),
        GlobalConditionOperator::ArnNotLike => op_str("\\not\\approx"),

        GlobalConditionOperator::Null => op_str("?"),

        GlobalConditionOperator::Other(id) => op_str(&id.to_string()),
    }
}