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
use super::role::RoleValidate;
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

/// Role Table Level.
///
/// For example:
///
/// ```yaml
/// - name: role_table
///   grants:
///     - SELECT
///     - INSERT
///     - UPDATE
///     - DELETE
///   schemas:
///   - public
///   tables:
///     - ALL
///     - +table1
///     - -table2
///     - -public.table2
/// ```
///
/// The above example grants SELECT, INSERT, UPDATE, DELETE to all tables in the public schema
/// except table2.
/// The ALL is a special keyword that means all tables in the public schema.
/// If the table does not have a schema, it is assumed to be in all schema.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct RoleTableLevel {
    pub name: String,
    pub grants: Vec<String>,
    pub schemas: Vec<String>,
    pub tables: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
struct Table {
    name: String,
    sign: String,
}

impl Table {
    fn new(name: &str) -> Self {
        let sign = match name.chars().next() {
            Some('+') => "+".to_string(),
            Some('-') => "-".to_string(),
            _ => "+".to_string(),
        };
        let name = name.trim_start_matches(&sign).to_string();

        Self { name, sign }
    }
}

impl RoleTableLevel {
    /// Generate role table to sql.
    ///
    /// ```sql
    /// {GRANT | REVOKE} { { SELECT | INSERT | UPDATE | DELETE | DROP | REFERENCES } [,...] | ALL [ PRIVILEGES ] }
    /// ON { [ TABLE ] table_name [, ...] | ALL TABLES IN SCHEMA schema_name [, ...] }
    /// TO { username [ WITH GRANT OPTION ] | GROUP group_name | PUBLIC } [, ...]
    /// ```
    pub fn to_sql(&self, user: &str) -> String {
        let mut sqls = vec![];
        let mut tables = self
            .tables
            .iter()
            .map(|t| Table::new(t))
            .collect::<Vec<Table>>();

        // grant all privileges if grants contains "ALL"
        let grants = if self.grants.contains(&"ALL".to_string()) {
            "ALL PRIVILEGES".to_string()
        } else {
            self.grants.join(", ")
        };

        // if `tables` only contains `ALL`
        if let Some(table_named_all) = tables.iter().find(|t| t.name == "ALL") {
            let sql = match table_named_all.sign.as_str() {
                "+" => format!(
                    "GRANT {} ON ALL TABLES IN SCHEMA {} TO {};",
                    grants,
                    self.schemas.join(", "),
                    user
                ),
                "-" => format!(
                    "REVOKE {} ON ALL TABLES IN SCHEMA {} FROM {};",
                    grants,
                    self.schemas.join(", "),
                    user
                ),
                _ => "".to_string(),
            };
            sqls.push(sql);

            // remove name `ALL` and all tables start with `+`
            for table in tables.clone() {
                if table.name == "ALL" || table.sign == "+" {
                    tables.retain(|x| x != &table);
                }
            }
        }

        // grant on tables sign `+`
        let grant_tables = tables.iter().filter(|x| x.sign == "+").collect::<Vec<_>>();
        if !grant_tables.is_empty() {
            let _with_schema = grant_tables
                .iter()
                .flat_map(|t| {
                    if t.name.contains('.') {
                        vec![t.name.clone()]
                    } else {
                        self.schemas
                            .iter()
                            .map(|s| format!("{}.{}", s, &t.name))
                            .collect::<Vec<_>>()
                    }
                })
                .collect::<Vec<String>>()
                .join(", ");

            let sql = format!("GRANT {} ON {} TO {};", grants, _with_schema, user);
            sqls.push(sql);

            // remove all tables start with `+`
            for table in tables.clone() {
                if table.sign == "+" {
                    tables.retain(|x| x != &table);
                }
            }
        }

        // revoke on tables start with `-`
        let revoke_tables = tables.iter().filter(|x| x.sign == "-").collect::<Vec<_>>();
        if !revoke_tables.is_empty() {
            let _with_schema = revoke_tables
                .iter()
                .flat_map(|t| {
                    if t.name.contains('.') {
                        vec![t.name.clone()]
                    } else {
                        self.schemas
                            .iter()
                            .map(|s| format!("{}.{}", s, &t.name))
                            .collect::<Vec<_>>()
                    }
                })
                .collect::<Vec<String>>()
                .join(", ");

            let sql = format!("REVOKE {} ON {} FROM {};", grants, _with_schema, user);
            sqls.push(sql);
        }

        sqls.join(" ")
    }
}

impl RoleValidate for RoleTableLevel {
    fn validate(&self) -> Result<()> {
        if self.name.is_empty() {
            return Err(anyhow!("role.name is empty"));
        }

        if self.schemas.is_empty() {
            return Err(anyhow!("role.schemas is empty"));
        }

        // TODO: support schemas=[ALL]
        if self.schemas.contains(&"ALL".to_string()) {
            return Err(anyhow!("role.schemas is not supported yet: ALL"));
        }

        if self.tables.is_empty() {
            return Err(anyhow!("role.tables is empty"));
        }

        if self.grants.is_empty() {
            return Err(anyhow!("role.grants is empty"));
        }

        // Check valid grants: SELECT, INSERT, UPDATE, DELETE, DROP, REFERENCES, ALL
        let valid_grants = vec![
            "SELECT",
            "INSERT",
            "UPDATE",
            "DELETE",
            "DROP",
            "REFERENCES",
            "ALL",
        ];
        let mut grants = HashSet::new();
        for grant in &self.grants {
            if !valid_grants.contains(&&grant[..]) {
                return Err(anyhow!(
                    "role.grants invalid: {}, expected: {:?}",
                    grant,
                    valid_grants
                ));
            }
            grants.insert(grant.to_string());
        }

        Ok(())
    }
}

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

    #[test]
    fn test_role_table_level() {
        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["SELECT".to_string()],
            schemas: vec!["public".to_string()],
            tables: vec!["test".to_string()],
        };
        assert_eq!(role.to_sql("test"), "GRANT SELECT ON public.test TO test;");

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["SELECT".to_string(), "INSERT".to_string()],
            schemas: vec!["public".to_string()],
            tables: vec!["test".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT SELECT, INSERT ON public.test TO test;"
        );

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["SELECT".to_string(), "INSERT".to_string()],
            schemas: vec!["public".to_string(), "test".to_string()],
            tables: vec!["test".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT SELECT, INSERT ON public.test, test.test TO test;"
        );

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["ALL".to_string()],
            schemas: vec!["public".to_string()],
            tables: vec!["test".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT ALL PRIVILEGES ON public.test TO test;"
        );

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["SELECT".to_string(), "INSERT".to_string()],
            schemas: vec!["public".to_string()],
            tables: vec!["ALL".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT SELECT, INSERT ON ALL TABLES IN SCHEMA public TO test;"
        );

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["ALL".to_string()],
            schemas: vec!["public".to_string(), "test".to_string()],
            tables: vec!["ALL".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public, test TO test;"
        );

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["SELECT".to_string(), "INSERT".to_string()],
            schemas: vec!["public".to_string(), "test".to_string()],
            tables: vec!["ALL".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT SELECT, INSERT ON ALL TABLES IN SCHEMA public, test TO test;"
        );

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["SELECT".to_string(), "INSERT".to_string()],
            schemas: vec!["public".to_string(), "test".to_string()],
            tables: vec!["test".to_string(), "test.test2".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT SELECT, INSERT ON public.test, test.test, test.test2 TO test;"
        );

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["SELECT".to_string(), "INSERT".to_string()],
            schemas: vec!["public".to_string(), "test".to_string()],
            tables: vec!["test".to_string(), "-test.test2".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT SELECT, INSERT ON public.test, test.test TO test; REVOKE SELECT, INSERT ON test.test2 FROM test;"
        );

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["SELECT".to_string(), "INSERT".to_string()],
            schemas: vec!["public".to_string(), "test".to_string()],
            tables: vec!["test".to_string(), "-test2".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT SELECT, INSERT ON public.test, test.test TO test; REVOKE SELECT, INSERT ON public.test2, test.test2 FROM test;"
        );

        let role = RoleTableLevel {
            name: "test".to_string(),
            grants: vec!["SELECT".to_string(), "INSERT".to_string()],
            schemas: vec!["public".to_string(), "test".to_string()],
            tables: vec!["ALL".to_string(), "-test.test2".to_string()],
        };
        assert_eq!(
            role.to_sql("test"),
            "GRANT SELECT, INSERT ON ALL TABLES IN SCHEMA public, test TO test; REVOKE SELECT, INSERT ON test.test2 FROM test;"
        );
    }
}